1use crate::{
2 ActiveDiagnostic, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext, ChunkReplacement,
3 CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker, ConflictsOuter,
4 ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape, CustomBlockId,
5 DisplayDiffHunk, DisplayPoint, DisplayRow, DocumentHighlightRead, DocumentHighlightWrite,
6 EditDisplayMode, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
7 FILE_HEADER_HEIGHT, FocusedBlock, GutterDimensions, HalfPageDown, HalfPageUp, HandleInput,
8 HoveredCursor, InlayHintRefreshReason, InlineCompletion, JumpData, LineDown, LineHighlight,
9 LineUp, MAX_LINE_LEN, MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts,
10 PageDown, PageUp, PhantomBreakpointIndicator, Point, RowExt, RowRangeExt, SelectPhase,
11 SelectedTextHighlight, Selection, SelectionDragState, SoftWrap, StickyHeaderExcerpt, ToPoint,
12 ToggleFold, ToggleFoldAll,
13 code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
14 display_map::{
15 Block, BlockContext, BlockStyle, ChunkRendererId, DisplaySnapshot, EditorMargins,
16 HighlightKey, HighlightedChunk, ToDisplayPoint,
17 },
18 editor_settings::{
19 CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, Minimap,
20 MinimapThumb, MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes,
21 ScrollbarDiagnostics, ShowMinimap, ShowScrollbar,
22 },
23 git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer},
24 hover_popover::{
25 self, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
26 POPOVER_RIGHT_OFFSET, hover_at,
27 },
28 inlay_hint_settings,
29 items::BufferSearchHighlights,
30 mouse_context_menu::{self, MenuPosition},
31 scroll::{ActiveScrollbarState, ScrollbarThumbState, scroll_amount::ScrollAmount},
32};
33use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
34use collections::{BTreeMap, HashMap};
35use file_icons::FileIcons;
36use git::{
37 Oid,
38 blame::{BlameEntry, ParsedCommitMessage},
39 status::FileStatus,
40};
41use gpui::{
42 Action, Along, AnyElement, App, AppContext, AvailableSpace, Axis as ScrollbarAxis, BorderStyle,
43 Bounds, ClickEvent, ContentMask, Context, Corner, Corners, CursorStyle, DispatchPhase, Edges,
44 Element, ElementInputHandler, Entity, Focusable as _, FontId, GlobalElementId, Hitbox,
45 HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero, Keystroke, Length,
46 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
47 ParentElement, Pixels, ScrollDelta, ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString,
48 Size, StatefulInteractiveElement, Style, Styled, TextRun, TextStyleRefinement, WeakEntity,
49 Window, anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline, point, px,
50 quad, relative, size, solid_background, transparent_black,
51};
52use itertools::Itertools;
53use language::language_settings::{
54 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
55};
56use markdown::Markdown;
57use multi_buffer::{
58 Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint,
59 MultiBufferRow, RowInfo,
60};
61
62use project::{
63 ProjectPath,
64 debugger::breakpoint_store::{Breakpoint, BreakpointSessionState},
65 project_settings::{GitGutterSetting, GitHunkStyleSetting, ProjectSettings},
66};
67use settings::Settings;
68use smallvec::{SmallVec, smallvec};
69use std::{
70 any::TypeId,
71 borrow::Cow,
72 cmp::{self, Ordering},
73 fmt::{self, Write},
74 iter, mem,
75 ops::{Deref, Range},
76 rc::Rc,
77 sync::Arc,
78 time::{Duration, Instant},
79};
80use sum_tree::Bias;
81use text::{BufferId, SelectionGoal};
82use theme::{ActiveTheme, Appearance, BufferLineHeight, PlayerColor};
83use ui::{ButtonLike, KeyBinding, POPOVER_Y_PADDING, Tooltip, h_flex, prelude::*};
84use unicode_segmentation::UnicodeSegmentation;
85use util::post_inc;
86use util::{RangeExt, ResultExt, debug_panic};
87use workspace::{CollaboratorId, Workspace, item::Item, notifications::NotifyTaskExt};
88
89const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 7.;
90
91/// Determines what kinds of highlights should be applied to a lines background.
92#[derive(Clone, Copy, Default)]
93struct LineHighlightSpec {
94 selection: bool,
95 breakpoint: bool,
96 _active_stack_frame: bool,
97}
98
99#[derive(Debug)]
100struct SelectionLayout {
101 head: DisplayPoint,
102 cursor_shape: CursorShape,
103 is_newest: bool,
104 is_local: bool,
105 range: Range<DisplayPoint>,
106 active_rows: Range<DisplayRow>,
107 user_name: Option<SharedString>,
108}
109
110struct InlineBlameLayout {
111 element: AnyElement,
112 bounds: Bounds<Pixels>,
113 entry: BlameEntry,
114}
115
116impl SelectionLayout {
117 fn new<T: ToPoint + ToDisplayPoint + Clone>(
118 selection: Selection<T>,
119 line_mode: bool,
120 cursor_shape: CursorShape,
121 map: &DisplaySnapshot,
122 is_newest: bool,
123 is_local: bool,
124 user_name: Option<SharedString>,
125 ) -> Self {
126 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
127 let display_selection = point_selection.map(|p| p.to_display_point(map));
128 let mut range = display_selection.range();
129 let mut head = display_selection.head();
130 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
131 ..map.next_line_boundary(point_selection.end).1.row();
132
133 // vim visual line mode
134 if line_mode {
135 let point_range = map.expand_to_line(point_selection.range());
136 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
137 }
138
139 // any vim visual mode (including line mode)
140 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
141 && !range.is_empty()
142 && !selection.reversed
143 {
144 if head.column() > 0 {
145 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
146 } else if head.row().0 > 0 && head != map.max_point() {
147 head = map.clip_point(
148 DisplayPoint::new(
149 head.row().previous_row(),
150 map.line_len(head.row().previous_row()),
151 ),
152 Bias::Left,
153 );
154 // updating range.end is a no-op unless you're cursor is
155 // on the newline containing a multi-buffer divider
156 // in which case the clip_point may have moved the head up
157 // an additional row.
158 range.end = DisplayPoint::new(head.row().next_row(), 0);
159 active_rows.end = head.row();
160 }
161 }
162
163 Self {
164 head,
165 cursor_shape,
166 is_newest,
167 is_local,
168 range,
169 active_rows,
170 user_name,
171 }
172 }
173}
174
175pub struct EditorElement {
176 editor: Entity<Editor>,
177 style: EditorStyle,
178}
179
180type DisplayRowDelta = u32;
181
182impl EditorElement {
183 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
184
185 pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
186 Self {
187 editor: editor.clone(),
188 style,
189 }
190 }
191
192 fn register_actions(&self, window: &mut Window, cx: &mut App) {
193 let editor = &self.editor;
194 editor.update(cx, |editor, cx| {
195 for action in editor.editor_actions.borrow().values() {
196 (action)(editor, window, cx)
197 }
198 });
199
200 crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
201 crate::clangd_ext::apply_related_actions(editor, window, cx);
202
203 register_action(editor, window, Editor::open_context_menu);
204 register_action(editor, window, Editor::move_left);
205 register_action(editor, window, Editor::move_right);
206 register_action(editor, window, Editor::move_down);
207 register_action(editor, window, Editor::move_down_by_lines);
208 register_action(editor, window, Editor::select_down_by_lines);
209 register_action(editor, window, Editor::move_up);
210 register_action(editor, window, Editor::move_up_by_lines);
211 register_action(editor, window, Editor::select_up_by_lines);
212 register_action(editor, window, Editor::select_page_down);
213 register_action(editor, window, Editor::select_page_up);
214 register_action(editor, window, Editor::cancel);
215 register_action(editor, window, Editor::newline);
216 register_action(editor, window, Editor::newline_above);
217 register_action(editor, window, Editor::newline_below);
218 register_action(editor, window, Editor::backspace);
219 register_action(editor, window, Editor::delete);
220 register_action(editor, window, Editor::tab);
221 register_action(editor, window, Editor::backtab);
222 register_action(editor, window, Editor::indent);
223 register_action(editor, window, Editor::outdent);
224 register_action(editor, window, Editor::autoindent);
225 register_action(editor, window, Editor::delete_line);
226 register_action(editor, window, Editor::join_lines);
227 register_action(editor, window, Editor::sort_lines_by_length);
228 register_action(editor, window, Editor::sort_lines_case_sensitive);
229 register_action(editor, window, Editor::sort_lines_case_insensitive);
230 register_action(editor, window, Editor::reverse_lines);
231 register_action(editor, window, Editor::shuffle_lines);
232 register_action(editor, window, Editor::toggle_case);
233 register_action(editor, window, Editor::convert_indentation_to_spaces);
234 register_action(editor, window, Editor::convert_indentation_to_tabs);
235 register_action(editor, window, Editor::convert_to_upper_case);
236 register_action(editor, window, Editor::convert_to_lower_case);
237 register_action(editor, window, Editor::convert_to_title_case);
238 register_action(editor, window, Editor::convert_to_snake_case);
239 register_action(editor, window, Editor::convert_to_kebab_case);
240 register_action(editor, window, Editor::convert_to_upper_camel_case);
241 register_action(editor, window, Editor::convert_to_lower_camel_case);
242 register_action(editor, window, Editor::convert_to_opposite_case);
243 register_action(editor, window, Editor::convert_to_rot13);
244 register_action(editor, window, Editor::convert_to_rot47);
245 register_action(editor, window, Editor::delete_to_previous_word_start);
246 register_action(editor, window, Editor::delete_to_previous_subword_start);
247 register_action(editor, window, Editor::delete_to_next_word_end);
248 register_action(editor, window, Editor::delete_to_next_subword_end);
249 register_action(editor, window, Editor::delete_to_beginning_of_line);
250 register_action(editor, window, Editor::delete_to_end_of_line);
251 register_action(editor, window, Editor::cut_to_end_of_line);
252 register_action(editor, window, Editor::duplicate_line_up);
253 register_action(editor, window, Editor::duplicate_line_down);
254 register_action(editor, window, Editor::duplicate_selection);
255 register_action(editor, window, Editor::move_line_up);
256 register_action(editor, window, Editor::move_line_down);
257 register_action(editor, window, Editor::transpose);
258 register_action(editor, window, Editor::rewrap);
259 register_action(editor, window, Editor::cut);
260 register_action(editor, window, Editor::kill_ring_cut);
261 register_action(editor, window, Editor::kill_ring_yank);
262 register_action(editor, window, Editor::copy);
263 register_action(editor, window, Editor::copy_and_trim);
264 register_action(editor, window, Editor::paste);
265 register_action(editor, window, Editor::undo);
266 register_action(editor, window, Editor::redo);
267 register_action(editor, window, Editor::move_page_up);
268 register_action(editor, window, Editor::move_page_down);
269 register_action(editor, window, Editor::next_screen);
270 register_action(editor, window, Editor::scroll_cursor_top);
271 register_action(editor, window, Editor::scroll_cursor_center);
272 register_action(editor, window, Editor::scroll_cursor_bottom);
273 register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
274 register_action(editor, window, |editor, _: &LineDown, window, cx| {
275 editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
276 });
277 register_action(editor, window, |editor, _: &LineUp, window, cx| {
278 editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
279 });
280 register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
281 editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
282 });
283 register_action(
284 editor,
285 window,
286 |editor, HandleInput(text): &HandleInput, window, cx| {
287 if text.is_empty() {
288 return;
289 }
290 editor.handle_input(text, window, cx);
291 },
292 );
293 register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
294 editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
295 });
296 register_action(editor, window, |editor, _: &PageDown, window, cx| {
297 editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
298 });
299 register_action(editor, window, |editor, _: &PageUp, window, cx| {
300 editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
301 });
302 register_action(editor, window, Editor::move_to_previous_word_start);
303 register_action(editor, window, Editor::move_to_previous_subword_start);
304 register_action(editor, window, Editor::move_to_next_word_end);
305 register_action(editor, window, Editor::move_to_next_subword_end);
306 register_action(editor, window, Editor::move_to_beginning_of_line);
307 register_action(editor, window, Editor::move_to_end_of_line);
308 register_action(editor, window, Editor::move_to_start_of_paragraph);
309 register_action(editor, window, Editor::move_to_end_of_paragraph);
310 register_action(editor, window, Editor::move_to_beginning);
311 register_action(editor, window, Editor::move_to_end);
312 register_action(editor, window, Editor::move_to_start_of_excerpt);
313 register_action(editor, window, Editor::move_to_start_of_next_excerpt);
314 register_action(editor, window, Editor::move_to_end_of_excerpt);
315 register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
316 register_action(editor, window, Editor::select_up);
317 register_action(editor, window, Editor::select_down);
318 register_action(editor, window, Editor::select_left);
319 register_action(editor, window, Editor::select_right);
320 register_action(editor, window, Editor::select_to_previous_word_start);
321 register_action(editor, window, Editor::select_to_previous_subword_start);
322 register_action(editor, window, Editor::select_to_next_word_end);
323 register_action(editor, window, Editor::select_to_next_subword_end);
324 register_action(editor, window, Editor::select_to_beginning_of_line);
325 register_action(editor, window, Editor::select_to_end_of_line);
326 register_action(editor, window, Editor::select_to_start_of_paragraph);
327 register_action(editor, window, Editor::select_to_end_of_paragraph);
328 register_action(editor, window, Editor::select_to_start_of_excerpt);
329 register_action(editor, window, Editor::select_to_start_of_next_excerpt);
330 register_action(editor, window, Editor::select_to_end_of_excerpt);
331 register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
332 register_action(editor, window, Editor::select_to_beginning);
333 register_action(editor, window, Editor::select_to_end);
334 register_action(editor, window, Editor::select_all);
335 register_action(editor, window, |editor, action, window, cx| {
336 editor.select_all_matches(action, window, cx).log_err();
337 });
338 register_action(editor, window, Editor::select_line);
339 register_action(editor, window, Editor::split_selection_into_lines);
340 register_action(editor, window, Editor::add_selection_above);
341 register_action(editor, window, Editor::add_selection_below);
342 register_action(editor, window, |editor, action, window, cx| {
343 editor.select_next(action, window, cx).log_err();
344 });
345 register_action(editor, window, |editor, action, window, cx| {
346 editor.select_previous(action, window, cx).log_err();
347 });
348 register_action(editor, window, |editor, action, window, cx| {
349 editor.find_next_match(action, window, cx).log_err();
350 });
351 register_action(editor, window, |editor, action, window, cx| {
352 editor.find_previous_match(action, window, cx).log_err();
353 });
354 register_action(editor, window, Editor::toggle_comments);
355 register_action(editor, window, Editor::select_larger_syntax_node);
356 register_action(editor, window, Editor::select_smaller_syntax_node);
357 register_action(editor, window, Editor::select_enclosing_symbol);
358 register_action(editor, window, Editor::move_to_enclosing_bracket);
359 register_action(editor, window, Editor::undo_selection);
360 register_action(editor, window, Editor::redo_selection);
361 if !editor.read(cx).is_singleton(cx) {
362 register_action(editor, window, Editor::expand_excerpts);
363 register_action(editor, window, Editor::expand_excerpts_up);
364 register_action(editor, window, Editor::expand_excerpts_down);
365 }
366 register_action(editor, window, Editor::go_to_diagnostic);
367 register_action(editor, window, Editor::go_to_prev_diagnostic);
368 register_action(editor, window, Editor::go_to_next_hunk);
369 register_action(editor, window, Editor::go_to_prev_hunk);
370 register_action(editor, window, |editor, action, window, cx| {
371 editor
372 .go_to_definition(action, window, cx)
373 .detach_and_log_err(cx);
374 });
375 register_action(editor, window, |editor, action, window, cx| {
376 editor
377 .go_to_definition_split(action, window, cx)
378 .detach_and_log_err(cx);
379 });
380 register_action(editor, window, |editor, action, window, cx| {
381 editor
382 .go_to_declaration(action, window, cx)
383 .detach_and_log_err(cx);
384 });
385 register_action(editor, window, |editor, action, window, cx| {
386 editor
387 .go_to_declaration_split(action, window, cx)
388 .detach_and_log_err(cx);
389 });
390 register_action(editor, window, |editor, action, window, cx| {
391 editor
392 .go_to_implementation(action, window, cx)
393 .detach_and_log_err(cx);
394 });
395 register_action(editor, window, |editor, action, window, cx| {
396 editor
397 .go_to_implementation_split(action, window, cx)
398 .detach_and_log_err(cx);
399 });
400 register_action(editor, window, |editor, action, window, cx| {
401 editor
402 .go_to_type_definition(action, window, cx)
403 .detach_and_log_err(cx);
404 });
405 register_action(editor, window, |editor, action, window, cx| {
406 editor
407 .go_to_type_definition_split(action, window, cx)
408 .detach_and_log_err(cx);
409 });
410 register_action(editor, window, Editor::open_url);
411 register_action(editor, window, Editor::open_selected_filename);
412 register_action(editor, window, Editor::fold);
413 register_action(editor, window, Editor::fold_at_level);
414 register_action(editor, window, Editor::fold_all);
415 register_action(editor, window, Editor::fold_function_bodies);
416 register_action(editor, window, Editor::fold_recursive);
417 register_action(editor, window, Editor::toggle_fold);
418 register_action(editor, window, Editor::toggle_fold_recursive);
419 register_action(editor, window, Editor::toggle_fold_all);
420 register_action(editor, window, Editor::unfold_lines);
421 register_action(editor, window, Editor::unfold_recursive);
422 register_action(editor, window, Editor::unfold_all);
423 register_action(editor, window, Editor::fold_selected_ranges);
424 register_action(editor, window, Editor::set_mark);
425 register_action(editor, window, Editor::swap_selection_ends);
426 register_action(editor, window, Editor::show_completions);
427 register_action(editor, window, Editor::show_word_completions);
428 register_action(editor, window, Editor::toggle_code_actions);
429 register_action(editor, window, Editor::open_excerpts);
430 register_action(editor, window, Editor::open_excerpts_in_split);
431 register_action(editor, window, Editor::open_proposed_changes_editor);
432 register_action(editor, window, Editor::toggle_soft_wrap);
433 register_action(editor, window, Editor::toggle_tab_bar);
434 register_action(editor, window, Editor::toggle_line_numbers);
435 register_action(editor, window, Editor::toggle_relative_line_numbers);
436 register_action(editor, window, Editor::toggle_indent_guides);
437 register_action(editor, window, Editor::toggle_inlay_hints);
438 register_action(editor, window, Editor::toggle_edit_predictions);
439 if editor.read(cx).diagnostics_enabled() {
440 register_action(editor, window, Editor::toggle_diagnostics);
441 }
442 if editor.read(cx).inline_diagnostics_enabled() {
443 register_action(editor, window, Editor::toggle_inline_diagnostics);
444 }
445 if editor.read(cx).supports_minimap(cx) {
446 register_action(editor, window, Editor::toggle_minimap);
447 }
448 register_action(editor, window, hover_popover::hover);
449 register_action(editor, window, Editor::reveal_in_finder);
450 register_action(editor, window, Editor::copy_path);
451 register_action(editor, window, Editor::copy_relative_path);
452 register_action(editor, window, Editor::copy_file_name);
453 register_action(editor, window, Editor::copy_file_name_without_extension);
454 register_action(editor, window, Editor::copy_highlight_json);
455 register_action(editor, window, Editor::copy_permalink_to_line);
456 register_action(editor, window, Editor::open_permalink_to_line);
457 register_action(editor, window, Editor::copy_file_location);
458 register_action(editor, window, Editor::toggle_git_blame);
459 register_action(editor, window, Editor::toggle_git_blame_inline);
460 register_action(editor, window, Editor::open_git_blame_commit);
461 register_action(editor, window, Editor::toggle_selected_diff_hunks);
462 register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
463 register_action(editor, window, Editor::stage_and_next);
464 register_action(editor, window, Editor::unstage_and_next);
465 register_action(editor, window, Editor::expand_all_diff_hunks);
466 register_action(editor, window, Editor::go_to_previous_change);
467 register_action(editor, window, Editor::go_to_next_change);
468
469 register_action(editor, window, |editor, action, window, cx| {
470 if let Some(task) = editor.format(action, window, cx) {
471 task.detach_and_notify_err(window, cx);
472 } else {
473 cx.propagate();
474 }
475 });
476 register_action(editor, window, |editor, action, window, cx| {
477 if let Some(task) = editor.format_selections(action, window, cx) {
478 task.detach_and_notify_err(window, cx);
479 } else {
480 cx.propagate();
481 }
482 });
483 register_action(editor, window, |editor, action, window, cx| {
484 if let Some(task) = editor.organize_imports(action, window, cx) {
485 task.detach_and_notify_err(window, cx);
486 } else {
487 cx.propagate();
488 }
489 });
490 register_action(editor, window, Editor::restart_language_server);
491 register_action(editor, window, Editor::stop_language_server);
492 register_action(editor, window, Editor::show_character_palette);
493 register_action(editor, window, |editor, action, window, cx| {
494 if let Some(task) = editor.confirm_completion(action, window, cx) {
495 task.detach_and_notify_err(window, cx);
496 } else {
497 cx.propagate();
498 }
499 });
500 register_action(editor, window, |editor, action, window, cx| {
501 if let Some(task) = editor.confirm_completion_replace(action, window, cx) {
502 task.detach_and_notify_err(window, cx);
503 } else {
504 cx.propagate();
505 }
506 });
507 register_action(editor, window, |editor, action, window, cx| {
508 if let Some(task) = editor.confirm_completion_insert(action, window, cx) {
509 task.detach_and_notify_err(window, cx);
510 } else {
511 cx.propagate();
512 }
513 });
514 register_action(editor, window, |editor, action, window, cx| {
515 if let Some(task) = editor.compose_completion(action, window, cx) {
516 task.detach_and_notify_err(window, cx);
517 } else {
518 cx.propagate();
519 }
520 });
521 register_action(editor, window, |editor, action, window, cx| {
522 if let Some(task) = editor.confirm_code_action(action, window, cx) {
523 task.detach_and_notify_err(window, cx);
524 } else {
525 cx.propagate();
526 }
527 });
528 register_action(editor, window, |editor, action, window, cx| {
529 if let Some(task) = editor.rename(action, window, cx) {
530 task.detach_and_notify_err(window, cx);
531 } else {
532 cx.propagate();
533 }
534 });
535 register_action(editor, window, |editor, action, window, cx| {
536 if let Some(task) = editor.confirm_rename(action, window, cx) {
537 task.detach_and_notify_err(window, cx);
538 } else {
539 cx.propagate();
540 }
541 });
542 register_action(editor, window, |editor, action, window, cx| {
543 if let Some(task) = editor.find_all_references(action, window, cx) {
544 task.detach_and_log_err(cx);
545 } else {
546 cx.propagate();
547 }
548 });
549 register_action(editor, window, Editor::show_signature_help);
550 register_action(editor, window, Editor::signature_help_prev);
551 register_action(editor, window, Editor::signature_help_next);
552 register_action(editor, window, Editor::next_edit_prediction);
553 register_action(editor, window, Editor::previous_edit_prediction);
554 register_action(editor, window, Editor::show_inline_completion);
555 register_action(editor, window, Editor::context_menu_first);
556 register_action(editor, window, Editor::context_menu_prev);
557 register_action(editor, window, Editor::context_menu_next);
558 register_action(editor, window, Editor::context_menu_last);
559 register_action(editor, window, Editor::display_cursor_names);
560 register_action(editor, window, Editor::unique_lines_case_insensitive);
561 register_action(editor, window, Editor::unique_lines_case_sensitive);
562 register_action(editor, window, Editor::accept_partial_inline_completion);
563 register_action(editor, window, Editor::accept_edit_prediction);
564 register_action(editor, window, Editor::restore_file);
565 register_action(editor, window, Editor::git_restore);
566 register_action(editor, window, Editor::apply_all_diff_hunks);
567 register_action(editor, window, Editor::apply_selected_diff_hunks);
568 register_action(editor, window, Editor::open_active_item_in_terminal);
569 register_action(editor, window, Editor::reload_file);
570 register_action(editor, window, Editor::spawn_nearest_task);
571 register_action(editor, window, Editor::insert_uuid_v4);
572 register_action(editor, window, Editor::insert_uuid_v7);
573 register_action(editor, window, Editor::open_selections_in_multibuffer);
574 register_action(editor, window, Editor::toggle_breakpoint);
575 register_action(editor, window, Editor::edit_log_breakpoint);
576 register_action(editor, window, Editor::enable_breakpoint);
577 register_action(editor, window, Editor::disable_breakpoint);
578 }
579
580 fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
581 let position_map = layout.position_map.clone();
582 window.on_key_event({
583 let editor = self.editor.clone();
584 move |event: &ModifiersChangedEvent, phase, window, cx| {
585 if phase != DispatchPhase::Bubble {
586 return;
587 }
588 editor.update(cx, |editor, cx| {
589 let inlay_hint_settings = inlay_hint_settings(
590 editor.selections.newest_anchor().head(),
591 &editor.buffer.read(cx).snapshot(cx),
592 cx,
593 );
594
595 if let Some(inlay_modifiers) = inlay_hint_settings
596 .toggle_on_modifiers_press
597 .as_ref()
598 .filter(|modifiers| modifiers.modified())
599 {
600 editor.refresh_inlay_hints(
601 InlayHintRefreshReason::ModifiersChanged(
602 inlay_modifiers == &event.modifiers,
603 ),
604 cx,
605 );
606 }
607
608 if editor.hover_state.focused(window, cx) {
609 return;
610 }
611
612 editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
613 })
614 }
615 });
616 }
617
618 fn mouse_left_down(
619 editor: &mut Editor,
620 event: &MouseDownEvent,
621 hovered_hunk: Option<Range<Anchor>>,
622 position_map: &PositionMap,
623 line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
624 window: &mut Window,
625 cx: &mut Context<Editor>,
626 ) {
627 if window.default_prevented() {
628 return;
629 }
630
631 let text_hitbox = &position_map.text_hitbox;
632 let gutter_hitbox = &position_map.gutter_hitbox;
633 let point_for_position = position_map.point_for_position(event.position);
634 let mut click_count = event.click_count;
635 let mut modifiers = event.modifiers;
636
637 if let Some(hovered_hunk) = hovered_hunk {
638 editor.toggle_single_diff_hunk(hovered_hunk, cx);
639 cx.notify();
640 return;
641 } else if gutter_hitbox.is_hovered(window) {
642 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
643 } else if !text_hitbox.is_hovered(window) {
644 return;
645 }
646
647 if EditorSettings::get_global(cx)
648 .drag_and_drop_selection
649 .enabled
650 && click_count == 1
651 {
652 let newest_anchor = editor.selections.newest_anchor();
653 let snapshot = editor.snapshot(window, cx);
654 let selection = newest_anchor.map(|anchor| anchor.to_display_point(&snapshot));
655 if point_for_position.intersects_selection(&selection) {
656 editor.selection_drag_state = SelectionDragState::ReadyToDrag {
657 selection: newest_anchor.clone(),
658 click_position: event.position,
659 mouse_down_time: Instant::now(),
660 };
661 cx.stop_propagation();
662 return;
663 }
664 }
665
666 let is_singleton = editor.buffer().read(cx).is_singleton();
667
668 if click_count == 2 && !is_singleton {
669 match EditorSettings::get_global(cx).double_click_in_multibuffer {
670 DoubleClickInMultibuffer::Select => {
671 // do nothing special on double click, all selection logic is below
672 }
673 DoubleClickInMultibuffer::Open => {
674 if modifiers.alt {
675 // if double click is made with alt, pretend it's a regular double click without opening and alt,
676 // and run the selection logic.
677 modifiers.alt = false;
678 } else {
679 let scroll_position_row =
680 position_map.scroll_pixel_position.y / position_map.line_height;
681 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
682 + position_map.scroll_pixel_position.y)
683 / position_map.line_height)
684 as u32;
685 let multi_buffer_row = position_map
686 .snapshot
687 .display_point_to_point(
688 DisplayPoint::new(DisplayRow(display_row), 0),
689 Bias::Right,
690 )
691 .row;
692 let line_offset_from_top = display_row - scroll_position_row as u32;
693 // if double click is made without alt, open the corresponding excerp
694 editor.open_excerpts_common(
695 Some(JumpData::MultiBufferRow {
696 row: MultiBufferRow(multi_buffer_row),
697 line_offset_from_top,
698 }),
699 false,
700 window,
701 cx,
702 );
703 return;
704 }
705 }
706 }
707 }
708
709 let position = point_for_position.previous_valid;
710 if let Some(mode) = Editor::columnar_selection_mode(&modifiers, cx) {
711 editor.select(
712 SelectPhase::BeginColumnar {
713 position,
714 reset: match mode {
715 ColumnarMode::FromMouse => true,
716 ColumnarMode::FromSelection => false,
717 },
718 mode: mode,
719 goal_column: point_for_position.exact_unclipped.column(),
720 },
721 window,
722 cx,
723 );
724 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
725 {
726 editor.select(
727 SelectPhase::Extend {
728 position,
729 click_count,
730 },
731 window,
732 cx,
733 );
734 } else {
735 editor.select(
736 SelectPhase::Begin {
737 position,
738 add: Editor::multi_cursor_modifier(true, &modifiers, cx),
739 click_count,
740 },
741 window,
742 cx,
743 );
744 }
745 cx.stop_propagation();
746
747 if !is_singleton {
748 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
749 + position_map.scroll_pixel_position.y)
750 / position_map.line_height) as u32;
751 let multi_buffer_row = position_map
752 .snapshot
753 .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
754 .row;
755 if line_numbers
756 .get(&MultiBufferRow(multi_buffer_row))
757 .and_then(|line_number| line_number.hitbox.as_ref())
758 .is_some_and(|hitbox| hitbox.contains(&event.position))
759 {
760 let scroll_position_row =
761 position_map.scroll_pixel_position.y / position_map.line_height;
762 let line_offset_from_top = display_row - scroll_position_row as u32;
763
764 editor.open_excerpts_common(
765 Some(JumpData::MultiBufferRow {
766 row: MultiBufferRow(multi_buffer_row),
767 line_offset_from_top,
768 }),
769 modifiers.alt,
770 window,
771 cx,
772 );
773 cx.stop_propagation();
774 }
775 }
776 }
777
778 fn mouse_right_down(
779 editor: &mut Editor,
780 event: &MouseDownEvent,
781 position_map: &PositionMap,
782 window: &mut Window,
783 cx: &mut Context<Editor>,
784 ) {
785 if position_map.gutter_hitbox.is_hovered(window) {
786 let gutter_right_padding = editor.gutter_dimensions.right_padding;
787 let hitbox = &position_map.gutter_hitbox;
788
789 if event.position.x <= hitbox.bounds.right() - gutter_right_padding {
790 let point_for_position = position_map.point_for_position(event.position);
791 editor.set_breakpoint_context_menu(
792 point_for_position.previous_valid.row(),
793 None,
794 event.position,
795 window,
796 cx,
797 );
798 }
799 return;
800 }
801
802 if !position_map.text_hitbox.is_hovered(window) {
803 return;
804 }
805
806 let point_for_position = position_map.point_for_position(event.position);
807 mouse_context_menu::deploy_context_menu(
808 editor,
809 Some(event.position),
810 point_for_position.previous_valid,
811 window,
812 cx,
813 );
814 cx.stop_propagation();
815 }
816
817 fn mouse_middle_down(
818 editor: &mut Editor,
819 event: &MouseDownEvent,
820 position_map: &PositionMap,
821 window: &mut Window,
822 cx: &mut Context<Editor>,
823 ) {
824 if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
825 return;
826 }
827
828 let point_for_position = position_map.point_for_position(event.position);
829 let position = point_for_position.previous_valid;
830
831 editor.select(
832 SelectPhase::BeginColumnar {
833 position,
834 reset: true,
835 mode: ColumnarMode::FromMouse,
836 goal_column: point_for_position.exact_unclipped.column(),
837 },
838 window,
839 cx,
840 );
841 }
842
843 fn mouse_up(
844 editor: &mut Editor,
845 event: &MouseUpEvent,
846 position_map: &PositionMap,
847 window: &mut Window,
848 cx: &mut Context<Editor>,
849 ) {
850 let text_hitbox = &position_map.text_hitbox;
851 let end_selection = editor.has_pending_selection();
852 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
853 let point_for_position = position_map.point_for_position(event.position);
854
855 match editor.selection_drag_state {
856 SelectionDragState::ReadyToDrag {
857 selection: _,
858 ref click_position,
859 mouse_down_time: _,
860 } => {
861 if event.position == *click_position {
862 editor.select(
863 SelectPhase::Begin {
864 position: point_for_position.previous_valid,
865 add: false,
866 click_count: 1, // ready to drag state only occurs on click count 1
867 },
868 window,
869 cx,
870 );
871 editor.selection_drag_state = SelectionDragState::None;
872 cx.stop_propagation();
873 return;
874 } else {
875 debug_panic!("drag state can never be in ready state after drag")
876 }
877 }
878 SelectionDragState::Dragging { ref selection, .. } => {
879 let snapshot = editor.snapshot(window, cx);
880 let selection_display = selection.map(|anchor| anchor.to_display_point(&snapshot));
881 if !point_for_position.intersects_selection(&selection_display)
882 && text_hitbox.is_hovered(window)
883 {
884 let is_cut = !(cfg!(target_os = "macos") && event.modifiers.alt
885 || cfg!(not(target_os = "macos")) && event.modifiers.control);
886 editor.move_selection_on_drop(
887 &selection.clone(),
888 point_for_position.previous_valid,
889 is_cut,
890 window,
891 cx,
892 );
893 }
894 editor.selection_drag_state = SelectionDragState::None;
895 cx.stop_propagation();
896 cx.notify();
897 return;
898 }
899 _ => {}
900 }
901
902 if end_selection {
903 editor.select(SelectPhase::End, window, cx);
904 }
905
906 if end_selection && pending_nonempty_selections {
907 cx.stop_propagation();
908 } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
909 && event.button == MouseButton::Middle
910 {
911 if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
912 return;
913 }
914
915 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
916 if EditorSettings::get_global(cx).middle_click_paste {
917 if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
918 let point_for_position = position_map.point_for_position(event.position);
919 let position = point_for_position.previous_valid;
920
921 editor.select(
922 SelectPhase::Begin {
923 position,
924 add: false,
925 click_count: 1,
926 },
927 window,
928 cx,
929 );
930 editor.insert(&text, window, cx);
931 }
932 cx.stop_propagation()
933 }
934 }
935 }
936
937 fn click(
938 editor: &mut Editor,
939 event: &ClickEvent,
940 position_map: &PositionMap,
941 window: &mut Window,
942 cx: &mut Context<Editor>,
943 ) {
944 let text_hitbox = &position_map.text_hitbox;
945 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
946
947 let hovered_link_modifier = Editor::multi_cursor_modifier(false, &event.modifiers(), cx);
948
949 if !pending_nonempty_selections && hovered_link_modifier && text_hitbox.is_hovered(window) {
950 let point = position_map.point_for_position(event.up.position);
951 editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
952
953 cx.stop_propagation();
954 }
955 }
956
957 fn mouse_dragged(
958 editor: &mut Editor,
959 event: &MouseMoveEvent,
960 position_map: &PositionMap,
961 window: &mut Window,
962 cx: &mut Context<Editor>,
963 ) {
964 if !editor.has_pending_selection()
965 && matches!(editor.selection_drag_state, SelectionDragState::None)
966 {
967 return;
968 }
969
970 let point_for_position = position_map.point_for_position(event.position);
971 let text_hitbox = &position_map.text_hitbox;
972
973 let scroll_delta = {
974 let text_bounds = text_hitbox.bounds;
975 let mut scroll_delta = gpui::Point::<f32>::default();
976 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
977 let top = text_bounds.origin.y + vertical_margin;
978 let bottom = text_bounds.bottom_left().y - vertical_margin;
979 if event.position.y < top {
980 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
981 }
982 if event.position.y > bottom {
983 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
984 }
985
986 // We need horizontal width of text
987 let style = editor.style.clone().unwrap_or_default();
988 let font_id = window.text_system().resolve_font(&style.text.font());
989 let font_size = style.text.font_size.to_pixels(window.rem_size());
990 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
991
992 let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
993
994 let scroll_space: Pixels = scroll_margin_x * em_width;
995
996 let left = text_bounds.origin.x + scroll_space;
997 let right = text_bounds.top_right().x - scroll_space;
998
999 if event.position.x < left {
1000 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
1001 }
1002 if event.position.x > right {
1003 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
1004 }
1005 scroll_delta
1006 };
1007
1008 if !editor.has_pending_selection() {
1009 let drop_anchor = position_map
1010 .snapshot
1011 .display_point_to_anchor(point_for_position.previous_valid, Bias::Left);
1012 match editor.selection_drag_state {
1013 SelectionDragState::Dragging {
1014 ref mut drop_cursor,
1015 ref mut hide_drop_cursor,
1016 ..
1017 } => {
1018 drop_cursor.start = drop_anchor;
1019 drop_cursor.end = drop_anchor;
1020 *hide_drop_cursor = !text_hitbox.is_hovered(window);
1021 editor.apply_scroll_delta(scroll_delta, window, cx);
1022 cx.notify();
1023 }
1024 SelectionDragState::ReadyToDrag {
1025 ref selection,
1026 ref click_position,
1027 ref mouse_down_time,
1028 } => {
1029 let drag_and_drop_delay = Duration::from_millis(
1030 EditorSettings::get_global(cx).drag_and_drop_selection.delay,
1031 );
1032 if mouse_down_time.elapsed() >= drag_and_drop_delay {
1033 let drop_cursor = Selection {
1034 id: post_inc(&mut editor.selections.next_selection_id),
1035 start: drop_anchor,
1036 end: drop_anchor,
1037 reversed: false,
1038 goal: SelectionGoal::None,
1039 };
1040 editor.selection_drag_state = SelectionDragState::Dragging {
1041 selection: selection.clone(),
1042 drop_cursor,
1043 hide_drop_cursor: false,
1044 };
1045 editor.apply_scroll_delta(scroll_delta, window, cx);
1046 cx.notify();
1047 } else {
1048 let click_point = position_map.point_for_position(*click_position);
1049 editor.selection_drag_state = SelectionDragState::None;
1050 editor.select(
1051 SelectPhase::Begin {
1052 position: click_point.previous_valid,
1053 add: false,
1054 click_count: 1,
1055 },
1056 window,
1057 cx,
1058 );
1059 editor.select(
1060 SelectPhase::Update {
1061 position: point_for_position.previous_valid,
1062 goal_column: point_for_position.exact_unclipped.column(),
1063 scroll_delta,
1064 },
1065 window,
1066 cx,
1067 );
1068 }
1069 }
1070 _ => {}
1071 }
1072 } else {
1073 editor.select(
1074 SelectPhase::Update {
1075 position: point_for_position.previous_valid,
1076 goal_column: point_for_position.exact_unclipped.column(),
1077 scroll_delta,
1078 },
1079 window,
1080 cx,
1081 );
1082 }
1083 }
1084
1085 fn mouse_moved(
1086 editor: &mut Editor,
1087 event: &MouseMoveEvent,
1088 position_map: &PositionMap,
1089 window: &mut Window,
1090 cx: &mut Context<Editor>,
1091 ) {
1092 let text_hitbox = &position_map.text_hitbox;
1093 let gutter_hitbox = &position_map.gutter_hitbox;
1094 let modifiers = event.modifiers;
1095 let text_hovered = text_hitbox.is_hovered(window);
1096 let gutter_hovered = gutter_hitbox.is_hovered(window);
1097 editor.set_gutter_hovered(gutter_hovered, cx);
1098 editor.show_mouse_cursor(cx);
1099
1100 let point_for_position = position_map.point_for_position(event.position);
1101 let valid_point = point_for_position.previous_valid;
1102
1103 let hovered_diff_control = position_map
1104 .diff_hunk_control_bounds
1105 .iter()
1106 .find(|(_, bounds)| bounds.contains(&event.position))
1107 .map(|(row, _)| *row);
1108
1109 let hovered_diff_hunk_row = if let Some(control_row) = hovered_diff_control {
1110 Some(control_row)
1111 } else {
1112 if text_hovered {
1113 let current_row = valid_point.row();
1114 position_map.display_hunks.iter().find_map(|(hunk, _)| {
1115 if let DisplayDiffHunk::Unfolded {
1116 display_row_range, ..
1117 } = hunk
1118 {
1119 if display_row_range.contains(¤t_row) {
1120 Some(display_row_range.start)
1121 } else {
1122 None
1123 }
1124 } else {
1125 None
1126 }
1127 })
1128 } else {
1129 None
1130 }
1131 };
1132
1133 if hovered_diff_hunk_row != editor.hovered_diff_hunk_row {
1134 editor.hovered_diff_hunk_row = hovered_diff_hunk_row;
1135 cx.notify();
1136 }
1137
1138 if let Some((bounds, blame_entry)) = &position_map.inline_blame_bounds {
1139 let mouse_over_inline_blame = bounds.contains(&event.position);
1140 let mouse_over_popover = editor
1141 .inline_blame_popover
1142 .as_ref()
1143 .and_then(|state| state.popover_bounds)
1144 .map_or(false, |bounds| bounds.contains(&event.position));
1145
1146 if mouse_over_inline_blame || mouse_over_popover {
1147 editor.show_blame_popover(&blame_entry, event.position, cx);
1148 } else {
1149 editor.hide_blame_popover(cx);
1150 }
1151 } else {
1152 editor.hide_blame_popover(cx);
1153 }
1154
1155 let breakpoint_indicator = if gutter_hovered {
1156 let buffer_anchor = position_map
1157 .snapshot
1158 .display_point_to_anchor(valid_point, Bias::Left);
1159
1160 if let Some((buffer_snapshot, file)) = position_map
1161 .snapshot
1162 .buffer_snapshot
1163 .buffer_for_excerpt(buffer_anchor.excerpt_id)
1164 .and_then(|buffer| buffer.file().map(|file| (buffer, file)))
1165 {
1166 let as_point = text::ToPoint::to_point(&buffer_anchor.text_anchor, buffer_snapshot);
1167
1168 let is_visible = editor
1169 .gutter_breakpoint_indicator
1170 .0
1171 .map_or(false, |indicator| indicator.is_active);
1172
1173 let has_existing_breakpoint =
1174 editor.breakpoint_store.as_ref().map_or(false, |store| {
1175 let Some(project) = &editor.project else {
1176 return false;
1177 };
1178 let Some(abs_path) = project.read(cx).absolute_path(
1179 &ProjectPath {
1180 path: file.path().clone(),
1181 worktree_id: file.worktree_id(cx),
1182 },
1183 cx,
1184 ) else {
1185 return false;
1186 };
1187 store
1188 .read(cx)
1189 .breakpoint_at_row(&abs_path, as_point.row, cx)
1190 .is_some()
1191 });
1192
1193 if !is_visible {
1194 editor.gutter_breakpoint_indicator.1.get_or_insert_with(|| {
1195 cx.spawn(async move |this, cx| {
1196 cx.background_executor()
1197 .timer(Duration::from_millis(200))
1198 .await;
1199
1200 this.update(cx, |this, cx| {
1201 if let Some(indicator) = this.gutter_breakpoint_indicator.0.as_mut()
1202 {
1203 indicator.is_active = true;
1204 cx.notify();
1205 }
1206 })
1207 .ok();
1208 })
1209 });
1210 }
1211
1212 Some(PhantomBreakpointIndicator {
1213 display_row: valid_point.row(),
1214 is_active: is_visible,
1215 collides_with_existing_breakpoint: has_existing_breakpoint,
1216 })
1217 } else {
1218 editor.gutter_breakpoint_indicator.1 = None;
1219 None
1220 }
1221 } else {
1222 editor.gutter_breakpoint_indicator.1 = None;
1223 None
1224 };
1225
1226 if &breakpoint_indicator != &editor.gutter_breakpoint_indicator.0 {
1227 editor.gutter_breakpoint_indicator.0 = breakpoint_indicator;
1228 cx.notify();
1229 }
1230
1231 // Don't trigger hover popover if mouse is hovering over context menu
1232 if text_hovered {
1233 editor.update_hovered_link(
1234 point_for_position,
1235 &position_map.snapshot,
1236 modifiers,
1237 window,
1238 cx,
1239 );
1240
1241 if let Some(point) = point_for_position.as_valid() {
1242 let anchor = position_map
1243 .snapshot
1244 .buffer_snapshot
1245 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
1246 hover_at(editor, Some(anchor), window, cx);
1247 Self::update_visible_cursor(editor, point, position_map, window, cx);
1248 } else {
1249 hover_at(editor, None, window, cx);
1250 }
1251 } else {
1252 editor.hide_hovered_link(cx);
1253 hover_at(editor, None, window, cx);
1254 }
1255 }
1256
1257 fn update_visible_cursor(
1258 editor: &mut Editor,
1259 point: DisplayPoint,
1260 position_map: &PositionMap,
1261 window: &mut Window,
1262 cx: &mut Context<Editor>,
1263 ) {
1264 let snapshot = &position_map.snapshot;
1265 let Some(hub) = editor.collaboration_hub() else {
1266 return;
1267 };
1268 let start = snapshot.display_snapshot.clip_point(
1269 DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
1270 Bias::Left,
1271 );
1272 let end = snapshot.display_snapshot.clip_point(
1273 DisplayPoint::new(
1274 point.row(),
1275 (point.column() + 1).min(snapshot.line_len(point.row())),
1276 ),
1277 Bias::Right,
1278 );
1279
1280 let range = snapshot
1281 .buffer_snapshot
1282 .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
1283 ..snapshot
1284 .buffer_snapshot
1285 .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
1286
1287 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
1288 return;
1289 };
1290 let key = crate::HoveredCursor {
1291 replica_id: selection.replica_id,
1292 selection_id: selection.selection.id,
1293 };
1294 editor.hovered_cursors.insert(
1295 key.clone(),
1296 cx.spawn_in(window, async move |editor, cx| {
1297 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
1298 editor
1299 .update(cx, |editor, cx| {
1300 editor.hovered_cursors.remove(&key);
1301 cx.notify();
1302 })
1303 .ok();
1304 }),
1305 );
1306 cx.notify()
1307 }
1308
1309 fn layout_selections(
1310 &self,
1311 start_anchor: Anchor,
1312 end_anchor: Anchor,
1313 local_selections: &[Selection<Point>],
1314 snapshot: &EditorSnapshot,
1315 start_row: DisplayRow,
1316 end_row: DisplayRow,
1317 window: &mut Window,
1318 cx: &mut App,
1319 ) -> (
1320 Vec<(PlayerColor, Vec<SelectionLayout>)>,
1321 BTreeMap<DisplayRow, LineHighlightSpec>,
1322 Option<DisplayPoint>,
1323 ) {
1324 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1325 let mut active_rows = BTreeMap::new();
1326 let mut newest_selection_head = None;
1327
1328 let Some(editor_with_selections) = self.editor_with_selections(cx) else {
1329 return (selections, active_rows, newest_selection_head);
1330 };
1331
1332 editor_with_selections.update(cx, |editor, cx| {
1333 if editor.show_local_selections {
1334 let mut layouts = Vec::new();
1335 let newest = editor.selections.newest(cx);
1336 for selection in local_selections.iter().cloned() {
1337 let is_empty = selection.start == selection.end;
1338 let is_newest = selection == newest;
1339
1340 let layout = SelectionLayout::new(
1341 selection,
1342 editor.selections.line_mode,
1343 editor.cursor_shape,
1344 &snapshot.display_snapshot,
1345 is_newest,
1346 editor.leader_id.is_none(),
1347 None,
1348 );
1349 if is_newest {
1350 newest_selection_head = Some(layout.head);
1351 }
1352
1353 for row in cmp::max(layout.active_rows.start.0, start_row.0)
1354 ..=cmp::min(layout.active_rows.end.0, end_row.0)
1355 {
1356 let contains_non_empty_selection = active_rows
1357 .entry(DisplayRow(row))
1358 .or_insert_with(LineHighlightSpec::default);
1359 contains_non_empty_selection.selection |= !is_empty;
1360 }
1361 layouts.push(layout);
1362 }
1363
1364 let player = editor.current_user_player_color(cx);
1365 selections.push((player, layouts));
1366
1367 if let SelectionDragState::Dragging {
1368 ref selection,
1369 ref drop_cursor,
1370 ref hide_drop_cursor,
1371 } = editor.selection_drag_state
1372 {
1373 if !hide_drop_cursor
1374 && (drop_cursor
1375 .start
1376 .cmp(&selection.start, &snapshot.buffer_snapshot)
1377 .eq(&Ordering::Less)
1378 || drop_cursor
1379 .end
1380 .cmp(&selection.end, &snapshot.buffer_snapshot)
1381 .eq(&Ordering::Greater))
1382 {
1383 let drag_cursor_layout = SelectionLayout::new(
1384 drop_cursor.clone(),
1385 false,
1386 CursorShape::Bar,
1387 &snapshot.display_snapshot,
1388 false,
1389 false,
1390 None,
1391 );
1392 let absent_color = cx.theme().players().absent();
1393 selections.push((absent_color, vec![drag_cursor_layout]));
1394 }
1395 }
1396 }
1397
1398 if let Some(collaboration_hub) = &editor.collaboration_hub {
1399 // When following someone, render the local selections in their color.
1400 if let Some(leader_id) = editor.leader_id {
1401 match leader_id {
1402 CollaboratorId::PeerId(peer_id) => {
1403 if let Some(collaborator) =
1404 collaboration_hub.collaborators(cx).get(&peer_id)
1405 {
1406 if let Some(participant_index) = collaboration_hub
1407 .user_participant_indices(cx)
1408 .get(&collaborator.user_id)
1409 {
1410 if let Some((local_selection_style, _)) = selections.first_mut()
1411 {
1412 *local_selection_style = cx
1413 .theme()
1414 .players()
1415 .color_for_participant(participant_index.0);
1416 }
1417 }
1418 }
1419 }
1420 CollaboratorId::Agent => {
1421 if let Some((local_selection_style, _)) = selections.first_mut() {
1422 *local_selection_style = cx.theme().players().agent();
1423 }
1424 }
1425 }
1426 }
1427
1428 let mut remote_selections = HashMap::default();
1429 for selection in snapshot.remote_selections_in_range(
1430 &(start_anchor..end_anchor),
1431 collaboration_hub.as_ref(),
1432 cx,
1433 ) {
1434 // Don't re-render the leader's selections, since the local selections
1435 // match theirs.
1436 if Some(selection.collaborator_id) == editor.leader_id {
1437 continue;
1438 }
1439 let key = HoveredCursor {
1440 replica_id: selection.replica_id,
1441 selection_id: selection.selection.id,
1442 };
1443
1444 let is_shown =
1445 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
1446
1447 remote_selections
1448 .entry(selection.replica_id)
1449 .or_insert((selection.color, Vec::new()))
1450 .1
1451 .push(SelectionLayout::new(
1452 selection.selection,
1453 selection.line_mode,
1454 selection.cursor_shape,
1455 &snapshot.display_snapshot,
1456 false,
1457 false,
1458 if is_shown { selection.user_name } else { None },
1459 ));
1460 }
1461
1462 selections.extend(remote_selections.into_values());
1463 } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
1464 let layouts = snapshot
1465 .buffer_snapshot
1466 .selections_in_range(&(start_anchor..end_anchor), true)
1467 .map(move |(_, line_mode, cursor_shape, selection)| {
1468 SelectionLayout::new(
1469 selection,
1470 line_mode,
1471 cursor_shape,
1472 &snapshot.display_snapshot,
1473 false,
1474 false,
1475 None,
1476 )
1477 })
1478 .collect::<Vec<_>>();
1479 let player = editor.current_user_player_color(cx);
1480 selections.push((player, layouts));
1481 }
1482 });
1483 (selections, active_rows, newest_selection_head)
1484 }
1485
1486 fn collect_cursors(
1487 &self,
1488 snapshot: &EditorSnapshot,
1489 cx: &mut App,
1490 ) -> Vec<(DisplayPoint, Hsla)> {
1491 let editor = self.editor.read(cx);
1492 let mut cursors = Vec::new();
1493 let mut skip_local = false;
1494 let mut add_cursor = |anchor: Anchor, color| {
1495 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
1496 };
1497 // Remote cursors
1498 if let Some(collaboration_hub) = &editor.collaboration_hub {
1499 for remote_selection in snapshot.remote_selections_in_range(
1500 &(Anchor::min()..Anchor::max()),
1501 collaboration_hub.deref(),
1502 cx,
1503 ) {
1504 add_cursor(
1505 remote_selection.selection.head(),
1506 remote_selection.color.cursor,
1507 );
1508 if Some(remote_selection.collaborator_id) == editor.leader_id {
1509 skip_local = true;
1510 }
1511 }
1512 }
1513 // Local cursors
1514 if !skip_local {
1515 let color = cx.theme().players().local().cursor;
1516 editor.selections.disjoint.iter().for_each(|selection| {
1517 add_cursor(selection.head(), color);
1518 });
1519 if let Some(ref selection) = editor.selections.pending_anchor() {
1520 add_cursor(selection.head(), color);
1521 }
1522 }
1523 cursors
1524 }
1525
1526 fn layout_visible_cursors(
1527 &self,
1528 snapshot: &EditorSnapshot,
1529 selections: &[(PlayerColor, Vec<SelectionLayout>)],
1530 row_block_types: &HashMap<DisplayRow, bool>,
1531 visible_display_row_range: Range<DisplayRow>,
1532 line_layouts: &[LineWithInvisibles],
1533 text_hitbox: &Hitbox,
1534 content_origin: gpui::Point<Pixels>,
1535 scroll_position: gpui::Point<f32>,
1536 scroll_pixel_position: gpui::Point<Pixels>,
1537 line_height: Pixels,
1538 em_width: Pixels,
1539 em_advance: Pixels,
1540 autoscroll_containing_element: bool,
1541 window: &mut Window,
1542 cx: &mut App,
1543 ) -> Vec<CursorLayout> {
1544 let mut autoscroll_bounds = None;
1545 let cursor_layouts = self.editor.update(cx, |editor, cx| {
1546 let mut cursors = Vec::new();
1547
1548 let show_local_cursors = editor.show_local_cursors(window, cx);
1549
1550 for (player_color, selections) in selections {
1551 for selection in selections {
1552 let cursor_position = selection.head;
1553
1554 let in_range = visible_display_row_range.contains(&cursor_position.row());
1555 if (selection.is_local && !show_local_cursors)
1556 || !in_range
1557 || row_block_types.get(&cursor_position.row()) == Some(&true)
1558 {
1559 continue;
1560 }
1561
1562 let cursor_row_layout = &line_layouts
1563 [cursor_position.row().minus(visible_display_row_range.start) as usize];
1564 let cursor_column = cursor_position.column() as usize;
1565
1566 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
1567 let mut block_width =
1568 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
1569 if block_width == Pixels::ZERO {
1570 block_width = em_advance;
1571 }
1572 let block_text = if let CursorShape::Block = selection.cursor_shape {
1573 snapshot
1574 .grapheme_at(cursor_position)
1575 .or_else(|| {
1576 if snapshot.is_empty() {
1577 snapshot.placeholder_text().and_then(|s| {
1578 s.graphemes(true).next().map(|s| s.to_string().into())
1579 })
1580 } else {
1581 None
1582 }
1583 })
1584 .map(|text| {
1585 let len = text.len();
1586
1587 let font = cursor_row_layout
1588 .font_id_for_index(cursor_column)
1589 .and_then(|cursor_font_id| {
1590 window.text_system().get_font_for_id(cursor_font_id)
1591 })
1592 .unwrap_or(self.style.text.font());
1593
1594 // Invert the text color for the block cursor. Ensure that the text
1595 // color is opaque enough to be visible against the background color.
1596 //
1597 // 0.75 is an arbitrary threshold to determine if the background color is
1598 // opaque enough to use as a text color.
1599 //
1600 // TODO: In the future we should ensure themes have a `text_inverse` color.
1601 let color = if cx.theme().colors().editor_background.a < 0.75 {
1602 match cx.theme().appearance {
1603 Appearance::Dark => Hsla::black(),
1604 Appearance::Light => Hsla::white(),
1605 }
1606 } else {
1607 cx.theme().colors().editor_background
1608 };
1609
1610 window.text_system().shape_line(
1611 text,
1612 cursor_row_layout.font_size,
1613 &[TextRun {
1614 len,
1615 font,
1616 color,
1617 background_color: None,
1618 strikethrough: None,
1619 underline: None,
1620 }],
1621 None,
1622 )
1623 })
1624 } else {
1625 None
1626 };
1627
1628 let x = cursor_character_x - scroll_pixel_position.x;
1629 let y = (cursor_position.row().as_f32()
1630 - scroll_pixel_position.y / line_height)
1631 * line_height;
1632 if selection.is_newest {
1633 editor.pixel_position_of_newest_cursor = Some(point(
1634 text_hitbox.origin.x + x + block_width / 2.,
1635 text_hitbox.origin.y + y + line_height / 2.,
1636 ));
1637
1638 if autoscroll_containing_element {
1639 let top = text_hitbox.origin.y
1640 + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1641 * line_height;
1642 let left = text_hitbox.origin.x
1643 + (cursor_position.column() as f32 - scroll_position.x - 3.)
1644 .max(0.)
1645 * em_width;
1646
1647 let bottom = text_hitbox.origin.y
1648 + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1649 * line_height;
1650 let right = text_hitbox.origin.x
1651 + (cursor_position.column() as f32 - scroll_position.x + 4.)
1652 * em_width;
1653
1654 autoscroll_bounds =
1655 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1656 }
1657 }
1658
1659 let mut cursor = CursorLayout {
1660 color: player_color.cursor,
1661 block_width,
1662 origin: point(x, y),
1663 line_height,
1664 shape: selection.cursor_shape,
1665 block_text,
1666 cursor_name: None,
1667 };
1668 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1669 string: name,
1670 color: self.style.background,
1671 is_top_row: cursor_position.row().0 == 0,
1672 });
1673 cursor.layout(content_origin, cursor_name, window, cx);
1674 cursors.push(cursor);
1675 }
1676 }
1677
1678 cursors
1679 });
1680
1681 if let Some(bounds) = autoscroll_bounds {
1682 window.request_autoscroll(bounds);
1683 }
1684
1685 cursor_layouts
1686 }
1687
1688 fn layout_scrollbars(
1689 &self,
1690 snapshot: &EditorSnapshot,
1691 scrollbar_layout_information: &ScrollbarLayoutInformation,
1692 content_offset: gpui::Point<Pixels>,
1693 scroll_position: gpui::Point<f32>,
1694 non_visible_cursors: bool,
1695 right_margin: Pixels,
1696 editor_width: Pixels,
1697 window: &mut Window,
1698 cx: &mut App,
1699 ) -> Option<EditorScrollbars> {
1700 let show_scrollbars = self.editor.read(cx).show_scrollbars;
1701 if (!show_scrollbars.horizontal && !show_scrollbars.vertical)
1702 || self.style.scrollbar_width.is_zero()
1703 {
1704 return None;
1705 }
1706
1707 // If a drag took place after we started dragging the scrollbar,
1708 // cancel the scrollbar drag.
1709 if cx.has_active_drag() {
1710 self.editor.update(cx, |editor, cx| {
1711 editor.scroll_manager.reset_scrollbar_state(cx)
1712 });
1713 }
1714
1715 let editor_settings = EditorSettings::get_global(cx);
1716 let scrollbar_settings = editor_settings.scrollbar;
1717 let show_scrollbars = match scrollbar_settings.show {
1718 ShowScrollbar::Auto => {
1719 let editor = self.editor.read(cx);
1720 let is_singleton = editor.is_singleton(cx);
1721 // Git
1722 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_diff_hunks())
1723 ||
1724 // Buffer Search Results
1725 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1726 ||
1727 // Selected Text Occurrences
1728 (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights::<SelectedTextHighlight>())
1729 ||
1730 // Selected Symbol Occurrences
1731 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1732 ||
1733 // Diagnostics
1734 (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot.has_diagnostics())
1735 ||
1736 // Cursors out of sight
1737 non_visible_cursors
1738 ||
1739 // Scrollmanager
1740 editor.scroll_manager.scrollbars_visible()
1741 }
1742 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1743 ShowScrollbar::Always => true,
1744 ShowScrollbar::Never => return None,
1745 };
1746
1747 // The horizontal scrollbar is usually slightly offset to align nicely with
1748 // indent guides. However, this offset is not needed if indent guides are
1749 // disabled for the current editor.
1750 let content_offset = self
1751 .editor
1752 .read(cx)
1753 .show_indent_guides
1754 .is_none_or(|should_show| should_show)
1755 .then_some(content_offset)
1756 .unwrap_or_default();
1757
1758 Some(EditorScrollbars::from_scrollbar_axes(
1759 ScrollbarAxes {
1760 horizontal: scrollbar_settings.axes.horizontal
1761 && self.editor.read(cx).show_scrollbars.horizontal,
1762 vertical: scrollbar_settings.axes.vertical
1763 && self.editor.read(cx).show_scrollbars.vertical,
1764 },
1765 scrollbar_layout_information,
1766 content_offset,
1767 scroll_position,
1768 self.style.scrollbar_width,
1769 right_margin,
1770 editor_width,
1771 show_scrollbars,
1772 self.editor.read(cx).scroll_manager.active_scrollbar_state(),
1773 window,
1774 ))
1775 }
1776
1777 fn layout_minimap(
1778 &self,
1779 snapshot: &EditorSnapshot,
1780 minimap_width: Pixels,
1781 scroll_position: gpui::Point<f32>,
1782 scrollbar_layout_information: &ScrollbarLayoutInformation,
1783 scrollbar_layout: Option<&EditorScrollbars>,
1784 window: &mut Window,
1785 cx: &mut App,
1786 ) -> Option<MinimapLayout> {
1787 let minimap_editor = self.editor.read(cx).minimap().cloned()?;
1788
1789 let minimap_settings = EditorSettings::get_global(cx).minimap;
1790
1791 if minimap_settings.on_active_editor() {
1792 let active_editor = self.editor.read(cx).workspace().and_then(|ws| {
1793 ws.read(cx)
1794 .active_pane()
1795 .read(cx)
1796 .active_item()
1797 .and_then(|i| i.act_as::<Editor>(cx))
1798 });
1799 if active_editor.is_some_and(|e| e != self.editor) {
1800 return None;
1801 }
1802 }
1803
1804 if !snapshot.mode.is_full()
1805 || minimap_width.is_zero()
1806 || matches!(
1807 minimap_settings.show,
1808 ShowMinimap::Auto if scrollbar_layout.is_none_or(|layout| !layout.visible)
1809 )
1810 {
1811 return None;
1812 }
1813
1814 const MINIMAP_AXIS: ScrollbarAxis = ScrollbarAxis::Vertical;
1815
1816 let ScrollbarLayoutInformation {
1817 editor_bounds,
1818 scroll_range,
1819 glyph_grid_cell,
1820 } = scrollbar_layout_information;
1821
1822 let line_height = glyph_grid_cell.height;
1823 let scroll_position = scroll_position.along(MINIMAP_AXIS);
1824
1825 let top_right_anchor = scrollbar_layout
1826 .and_then(|layout| layout.vertical.as_ref())
1827 .map(|vertical_scrollbar| vertical_scrollbar.hitbox.origin)
1828 .unwrap_or_else(|| editor_bounds.top_right());
1829
1830 let thumb_state = self
1831 .editor
1832 .read_with(cx, |editor, _| editor.scroll_manager.minimap_thumb_state());
1833
1834 let show_thumb = match minimap_settings.thumb {
1835 MinimapThumb::Always => true,
1836 MinimapThumb::Hover => thumb_state.is_some(),
1837 };
1838
1839 let minimap_bounds = Bounds::from_corner_and_size(
1840 Corner::TopRight,
1841 top_right_anchor,
1842 size(minimap_width, editor_bounds.size.height),
1843 );
1844 let minimap_line_height = self.get_minimap_line_height(
1845 minimap_editor
1846 .read(cx)
1847 .text_style_refinement
1848 .as_ref()
1849 .and_then(|refinement| refinement.font_size)
1850 .unwrap_or(MINIMAP_FONT_SIZE),
1851 window,
1852 cx,
1853 );
1854 let minimap_height = minimap_bounds.size.height;
1855
1856 let visible_editor_lines = editor_bounds.size.height / line_height;
1857 let total_editor_lines = scroll_range.height / line_height;
1858 let minimap_lines = minimap_height / minimap_line_height;
1859
1860 let minimap_scroll_top = MinimapLayout::calculate_minimap_top_offset(
1861 total_editor_lines,
1862 visible_editor_lines,
1863 minimap_lines,
1864 scroll_position,
1865 );
1866
1867 let layout = ScrollbarLayout::for_minimap(
1868 window.insert_hitbox(minimap_bounds, HitboxBehavior::Normal),
1869 visible_editor_lines,
1870 total_editor_lines,
1871 minimap_line_height,
1872 scroll_position,
1873 minimap_scroll_top,
1874 show_thumb,
1875 )
1876 .with_thumb_state(thumb_state);
1877
1878 minimap_editor.update(cx, |editor, cx| {
1879 editor.set_scroll_position(point(0., minimap_scroll_top), window, cx)
1880 });
1881
1882 // Required for the drop shadow to be visible
1883 const PADDING_OFFSET: Pixels = px(4.);
1884
1885 let mut minimap = div()
1886 .size_full()
1887 .shadow_xs()
1888 .px(PADDING_OFFSET)
1889 .child(minimap_editor)
1890 .into_any_element();
1891
1892 let extended_bounds = minimap_bounds.extend(Edges {
1893 right: PADDING_OFFSET,
1894 left: PADDING_OFFSET,
1895 ..Default::default()
1896 });
1897 minimap.layout_as_root(extended_bounds.size.into(), window, cx);
1898 window.with_absolute_element_offset(extended_bounds.origin, |window| {
1899 minimap.prepaint(window, cx)
1900 });
1901
1902 Some(MinimapLayout {
1903 minimap,
1904 thumb_layout: layout,
1905 thumb_border_style: minimap_settings.thumb_border,
1906 minimap_line_height,
1907 minimap_scroll_top,
1908 max_scroll_top: total_editor_lines,
1909 })
1910 }
1911
1912 fn get_minimap_line_height(
1913 &self,
1914 font_size: AbsoluteLength,
1915 window: &mut Window,
1916 cx: &mut App,
1917 ) -> Pixels {
1918 let rem_size = self.rem_size(cx).unwrap_or(window.rem_size());
1919 let mut text_style = self.style.text.clone();
1920 text_style.font_size = font_size;
1921 text_style.line_height_in_pixels(rem_size)
1922 }
1923
1924 fn get_minimap_width(
1925 &self,
1926 minimap_settings: &Minimap,
1927 scrollbars_shown: bool,
1928 text_width: Pixels,
1929 em_width: Pixels,
1930 font_size: Pixels,
1931 rem_size: Pixels,
1932 cx: &App,
1933 ) -> Option<Pixels> {
1934 if minimap_settings.show == ShowMinimap::Auto && !scrollbars_shown {
1935 return None;
1936 }
1937
1938 let minimap_font_size = self.editor.read_with(cx, |editor, cx| {
1939 editor.minimap().map(|minimap_editor| {
1940 minimap_editor
1941 .read(cx)
1942 .text_style_refinement
1943 .as_ref()
1944 .and_then(|refinement| refinement.font_size)
1945 .unwrap_or(MINIMAP_FONT_SIZE)
1946 })
1947 })?;
1948
1949 let minimap_em_width = em_width * (minimap_font_size.to_pixels(rem_size) / font_size);
1950
1951 let minimap_width = (text_width * MinimapLayout::MINIMAP_WIDTH_PCT)
1952 .min(minimap_em_width * minimap_settings.max_width_columns.get() as f32);
1953
1954 (minimap_width >= minimap_em_width * MinimapLayout::MINIMAP_MIN_WIDTH_COLUMNS)
1955 .then_some(minimap_width)
1956 }
1957
1958 fn prepaint_crease_toggles(
1959 &self,
1960 crease_toggles: &mut [Option<AnyElement>],
1961 line_height: Pixels,
1962 gutter_dimensions: &GutterDimensions,
1963 gutter_settings: crate::editor_settings::Gutter,
1964 scroll_pixel_position: gpui::Point<Pixels>,
1965 gutter_hitbox: &Hitbox,
1966 window: &mut Window,
1967 cx: &mut App,
1968 ) {
1969 for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
1970 if let Some(crease_toggle) = crease_toggle {
1971 debug_assert!(gutter_settings.folds);
1972 let available_space = size(
1973 AvailableSpace::MinContent,
1974 AvailableSpace::Definite(line_height * 0.55),
1975 );
1976 let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
1977
1978 let position = point(
1979 gutter_dimensions.width - gutter_dimensions.right_padding,
1980 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1981 );
1982 let centering_offset = point(
1983 (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
1984 (line_height - crease_toggle_size.height) / 2.,
1985 );
1986 let origin = gutter_hitbox.origin + position + centering_offset;
1987 crease_toggle.prepaint_as_root(origin, available_space, window, cx);
1988 }
1989 }
1990 }
1991
1992 fn prepaint_expand_toggles(
1993 &self,
1994 expand_toggles: &mut [Option<(AnyElement, gpui::Point<Pixels>)>],
1995 window: &mut Window,
1996 cx: &mut App,
1997 ) {
1998 for (expand_toggle, origin) in expand_toggles.iter_mut().flatten() {
1999 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2000 expand_toggle.layout_as_root(available_space, window, cx);
2001 expand_toggle.prepaint_as_root(*origin, available_space, window, cx);
2002 }
2003 }
2004
2005 fn prepaint_crease_trailers(
2006 &self,
2007 trailers: Vec<Option<AnyElement>>,
2008 lines: &[LineWithInvisibles],
2009 line_height: Pixels,
2010 content_origin: gpui::Point<Pixels>,
2011 scroll_pixel_position: gpui::Point<Pixels>,
2012 em_width: Pixels,
2013 window: &mut Window,
2014 cx: &mut App,
2015 ) -> Vec<Option<CreaseTrailerLayout>> {
2016 trailers
2017 .into_iter()
2018 .enumerate()
2019 .map(|(ix, element)| {
2020 let mut element = element?;
2021 let available_space = size(
2022 AvailableSpace::MinContent,
2023 AvailableSpace::Definite(line_height),
2024 );
2025 let size = element.layout_as_root(available_space, window, cx);
2026
2027 let line = &lines[ix];
2028 let padding = if line.width == Pixels::ZERO {
2029 Pixels::ZERO
2030 } else {
2031 4. * em_width
2032 };
2033 let position = point(
2034 scroll_pixel_position.x + line.width + padding,
2035 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
2036 );
2037 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
2038 let origin = content_origin + position + centering_offset;
2039 element.prepaint_as_root(origin, available_space, window, cx);
2040 Some(CreaseTrailerLayout {
2041 element,
2042 bounds: Bounds::new(origin, size),
2043 })
2044 })
2045 .collect()
2046 }
2047
2048 // Folds contained in a hunk are ignored apart from shrinking visual size
2049 // If a fold contains any hunks then that fold line is marked as modified
2050 fn layout_gutter_diff_hunks(
2051 &self,
2052 line_height: Pixels,
2053 gutter_hitbox: &Hitbox,
2054 display_rows: Range<DisplayRow>,
2055 snapshot: &EditorSnapshot,
2056 window: &mut Window,
2057 cx: &mut App,
2058 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
2059 let folded_buffers = self.editor.read(cx).folded_buffers(cx);
2060 let mut display_hunks = snapshot
2061 .display_diff_hunks_for_rows(display_rows, folded_buffers)
2062 .map(|hunk| (hunk, None))
2063 .collect::<Vec<_>>();
2064 let git_gutter_setting = ProjectSettings::get_global(cx)
2065 .git
2066 .git_gutter
2067 .unwrap_or_default();
2068 if let GitGutterSetting::TrackedFiles = git_gutter_setting {
2069 for (hunk, hitbox) in &mut display_hunks {
2070 if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
2071 let hunk_bounds =
2072 Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
2073 *hitbox = Some(window.insert_hitbox(hunk_bounds, HitboxBehavior::BlockMouse));
2074 }
2075 }
2076 }
2077
2078 display_hunks
2079 }
2080
2081 fn layout_inline_diagnostics(
2082 &self,
2083 line_layouts: &[LineWithInvisibles],
2084 crease_trailers: &[Option<CreaseTrailerLayout>],
2085 row_block_types: &HashMap<DisplayRow, bool>,
2086 content_origin: gpui::Point<Pixels>,
2087 scroll_pixel_position: gpui::Point<Pixels>,
2088 inline_completion_popover_origin: Option<gpui::Point<Pixels>>,
2089 start_row: DisplayRow,
2090 end_row: DisplayRow,
2091 line_height: Pixels,
2092 em_width: Pixels,
2093 style: &EditorStyle,
2094 window: &mut Window,
2095 cx: &mut App,
2096 ) -> HashMap<DisplayRow, AnyElement> {
2097 if self.editor.read(cx).mode().is_minimap() {
2098 return HashMap::default();
2099 }
2100
2101 let max_severity = match ProjectSettings::get_global(cx)
2102 .diagnostics
2103 .inline
2104 .max_severity
2105 .unwrap_or_else(|| self.editor.read(cx).diagnostics_max_severity)
2106 .into_lsp()
2107 {
2108 Some(max_severity) => max_severity,
2109 None => return HashMap::default(),
2110 };
2111
2112 let active_diagnostics_group =
2113 if let ActiveDiagnostic::Group(group) = &self.editor.read(cx).active_diagnostics {
2114 Some(group.group_id)
2115 } else {
2116 None
2117 };
2118
2119 let diagnostics_by_rows = self.editor.update(cx, |editor, cx| {
2120 let snapshot = editor.snapshot(window, cx);
2121 editor
2122 .inline_diagnostics
2123 .iter()
2124 .filter(|(_, diagnostic)| diagnostic.severity <= max_severity)
2125 .filter(|(_, diagnostic)| match active_diagnostics_group {
2126 Some(active_diagnostics_group) => {
2127 // Active diagnostics are all shown in the editor already, no need to display them inline
2128 diagnostic.group_id != active_diagnostics_group
2129 }
2130 None => true,
2131 })
2132 .map(|(point, diag)| (point.to_display_point(&snapshot), diag.clone()))
2133 .skip_while(|(point, _)| point.row() < start_row)
2134 .take_while(|(point, _)| point.row() < end_row)
2135 .filter(|(point, _)| !row_block_types.contains_key(&point.row()))
2136 .fold(HashMap::default(), |mut acc, (point, diagnostic)| {
2137 acc.entry(point.row())
2138 .or_insert_with(Vec::new)
2139 .push(diagnostic);
2140 acc
2141 })
2142 });
2143
2144 if diagnostics_by_rows.is_empty() {
2145 return HashMap::default();
2146 }
2147
2148 let severity_to_color = |sev: &lsp::DiagnosticSeverity| match sev {
2149 &lsp::DiagnosticSeverity::ERROR => Color::Error,
2150 &lsp::DiagnosticSeverity::WARNING => Color::Warning,
2151 &lsp::DiagnosticSeverity::INFORMATION => Color::Info,
2152 &lsp::DiagnosticSeverity::HINT => Color::Hint,
2153 _ => Color::Error,
2154 };
2155
2156 let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
2157 let min_x = ProjectSettings::get_global(cx)
2158 .diagnostics
2159 .inline
2160 .min_column as f32
2161 * em_width;
2162
2163 let mut elements = HashMap::default();
2164 for (row, mut diagnostics) in diagnostics_by_rows {
2165 diagnostics.sort_by_key(|diagnostic| {
2166 (
2167 diagnostic.severity,
2168 std::cmp::Reverse(diagnostic.is_primary),
2169 diagnostic.start.row,
2170 diagnostic.start.column,
2171 )
2172 });
2173
2174 let Some(diagnostic_to_render) = diagnostics
2175 .iter()
2176 .find(|diagnostic| diagnostic.is_primary)
2177 .or_else(|| diagnostics.first())
2178 else {
2179 continue;
2180 };
2181
2182 let pos_y = content_origin.y
2183 + line_height * (row.0 as f32 - scroll_pixel_position.y / line_height);
2184
2185 let window_ix = row.0.saturating_sub(start_row.0) as usize;
2186 let pos_x = {
2187 let crease_trailer_layout = &crease_trailers[window_ix];
2188 let line_layout = &line_layouts[window_ix];
2189
2190 let line_end = if let Some(crease_trailer) = crease_trailer_layout {
2191 crease_trailer.bounds.right()
2192 } else {
2193 content_origin.x - scroll_pixel_position.x + line_layout.width
2194 };
2195
2196 let padded_line = line_end + padding;
2197 let min_start = content_origin.x - scroll_pixel_position.x + min_x;
2198
2199 cmp::max(padded_line, min_start)
2200 };
2201
2202 let behind_inline_completion_popover = inline_completion_popover_origin
2203 .as_ref()
2204 .map_or(false, |inline_completion_popover_origin| {
2205 (pos_y..pos_y + line_height).contains(&inline_completion_popover_origin.y)
2206 });
2207 let opacity = if behind_inline_completion_popover {
2208 0.5
2209 } else {
2210 1.0
2211 };
2212
2213 let mut element = h_flex()
2214 .id(("diagnostic", row.0))
2215 .h(line_height)
2216 .w_full()
2217 .px_1()
2218 .rounded_xs()
2219 .opacity(opacity)
2220 .bg(severity_to_color(&diagnostic_to_render.severity)
2221 .color(cx)
2222 .opacity(0.05))
2223 .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
2224 .text_sm()
2225 .font_family(style.text.font().family)
2226 .child(diagnostic_to_render.message.clone())
2227 .into_any();
2228
2229 element.prepaint_as_root(point(pos_x, pos_y), AvailableSpace::min_size(), window, cx);
2230
2231 elements.insert(row, element);
2232 }
2233
2234 elements
2235 }
2236
2237 fn layout_inline_code_actions(
2238 &self,
2239 display_point: DisplayPoint,
2240 content_origin: gpui::Point<Pixels>,
2241 scroll_pixel_position: gpui::Point<Pixels>,
2242 line_height: Pixels,
2243 snapshot: &EditorSnapshot,
2244 window: &mut Window,
2245 cx: &mut App,
2246 ) -> Option<AnyElement> {
2247 if !snapshot
2248 .show_code_actions
2249 .unwrap_or(EditorSettings::get_global(cx).inline_code_actions)
2250 {
2251 return None;
2252 }
2253
2254 let icon_size = ui::IconSize::XSmall;
2255 let mut button = self.editor.update(cx, |editor, cx| {
2256 editor.available_code_actions.as_ref()?;
2257 let active = editor
2258 .context_menu
2259 .borrow()
2260 .as_ref()
2261 .and_then(|menu| {
2262 if let crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2263 deployed_from,
2264 ..
2265 }) = menu
2266 {
2267 deployed_from.as_ref()
2268 } else {
2269 None
2270 }
2271 })
2272 .map_or(false, |source| {
2273 matches!(source, CodeActionSource::Indicator(..))
2274 });
2275 Some(editor.render_inline_code_actions(icon_size, display_point.row(), active, cx))
2276 })?;
2277
2278 let buffer_point = display_point.to_point(&snapshot.display_snapshot);
2279
2280 // do not show code action for folded line
2281 if snapshot.is_line_folded(MultiBufferRow(buffer_point.row)) {
2282 return None;
2283 }
2284
2285 // do not show code action for blank line with cursor
2286 let line_indent = snapshot
2287 .display_snapshot
2288 .buffer_snapshot
2289 .line_indent_for_row(MultiBufferRow(buffer_point.row));
2290 if line_indent.is_line_blank() {
2291 return None;
2292 }
2293
2294 const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
2295 const MAX_ALTERNATE_DISTANCE: u32 = 8;
2296
2297 let excerpt_id = snapshot
2298 .display_snapshot
2299 .buffer_snapshot
2300 .excerpt_containing(buffer_point..buffer_point)
2301 .map(|excerpt| excerpt.id());
2302
2303 let is_valid_row = |row_candidate: u32| -> bool {
2304 // move to other row if folded row
2305 if snapshot.is_line_folded(MultiBufferRow(row_candidate)) {
2306 return false;
2307 }
2308 if buffer_point.row == row_candidate {
2309 // move to other row if cursor is in slot
2310 if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
2311 return false;
2312 }
2313 } else {
2314 let candidate_point = MultiBufferPoint {
2315 row: row_candidate,
2316 column: 0,
2317 };
2318 let candidate_excerpt_id = snapshot
2319 .display_snapshot
2320 .buffer_snapshot
2321 .excerpt_containing(candidate_point..candidate_point)
2322 .map(|excerpt| excerpt.id());
2323 // move to other row if different excerpt
2324 if excerpt_id != candidate_excerpt_id {
2325 return false;
2326 }
2327 }
2328 let line_indent = snapshot
2329 .display_snapshot
2330 .buffer_snapshot
2331 .line_indent_for_row(MultiBufferRow(row_candidate));
2332 // use this row if it's blank
2333 if line_indent.is_line_blank() {
2334 true
2335 } else {
2336 // use this row if code starts after slot
2337 let indent_size = snapshot
2338 .display_snapshot
2339 .buffer_snapshot
2340 .indent_size_for_line(MultiBufferRow(row_candidate));
2341 indent_size.len >= INLINE_SLOT_CHAR_LIMIT
2342 }
2343 };
2344
2345 let new_buffer_row = if is_valid_row(buffer_point.row) {
2346 Some(buffer_point.row)
2347 } else {
2348 let max_row = snapshot.display_snapshot.buffer_snapshot.max_point().row;
2349 (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
2350 let row_above = buffer_point.row.saturating_sub(offset);
2351 let row_below = buffer_point.row + offset;
2352 if row_above != buffer_point.row && is_valid_row(row_above) {
2353 Some(row_above)
2354 } else if row_below <= max_row && is_valid_row(row_below) {
2355 Some(row_below)
2356 } else {
2357 None
2358 }
2359 })
2360 }?;
2361
2362 let new_display_row = snapshot
2363 .display_snapshot
2364 .point_to_display_point(
2365 Point {
2366 row: new_buffer_row,
2367 column: buffer_point.column,
2368 },
2369 text::Bias::Left,
2370 )
2371 .row();
2372
2373 let start_y = content_origin.y
2374 + ((new_display_row.as_f32() - (scroll_pixel_position.y / line_height)) * line_height)
2375 + (line_height / 2.0)
2376 - (icon_size.square(window, cx) / 2.);
2377 let start_x = content_origin.x - scroll_pixel_position.x + (window.rem_size() * 0.1);
2378
2379 let absolute_offset = gpui::point(start_x, start_y);
2380 button.layout_as_root(gpui::AvailableSpace::min_size(), window, cx);
2381 button.prepaint_as_root(
2382 absolute_offset,
2383 gpui::AvailableSpace::min_size(),
2384 window,
2385 cx,
2386 );
2387 Some(button)
2388 }
2389
2390 fn layout_inline_blame(
2391 &self,
2392 display_row: DisplayRow,
2393 row_info: &RowInfo,
2394 line_layout: &LineWithInvisibles,
2395 crease_trailer: Option<&CreaseTrailerLayout>,
2396 em_width: Pixels,
2397 content_origin: gpui::Point<Pixels>,
2398 scroll_pixel_position: gpui::Point<Pixels>,
2399 line_height: Pixels,
2400 text_hitbox: &Hitbox,
2401 window: &mut Window,
2402 cx: &mut App,
2403 ) -> Option<InlineBlameLayout> {
2404 if !self
2405 .editor
2406 .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
2407 {
2408 return None;
2409 }
2410
2411 let editor = self.editor.read(cx);
2412 let blame = editor.blame.clone()?;
2413 let padding = {
2414 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
2415 const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
2416
2417 let mut padding = INLINE_BLAME_PADDING_EM_WIDTHS;
2418
2419 if let Some(inline_completion) = editor.active_inline_completion.as_ref() {
2420 match &inline_completion.completion {
2421 InlineCompletion::Edit {
2422 display_mode: EditDisplayMode::TabAccept,
2423 ..
2424 } => padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS,
2425 _ => {}
2426 }
2427 }
2428
2429 padding * em_width
2430 };
2431
2432 let entry = blame
2433 .update(cx, |blame, cx| {
2434 blame.blame_for_rows(&[*row_info], cx).next()
2435 })
2436 .flatten()?;
2437
2438 let mut element = render_inline_blame_entry(entry.clone(), &self.style, cx)?;
2439
2440 let start_y = content_origin.y
2441 + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
2442
2443 let start_x = {
2444 let line_end = if let Some(crease_trailer) = crease_trailer {
2445 crease_trailer.bounds.right()
2446 } else {
2447 content_origin.x - scroll_pixel_position.x + line_layout.width
2448 };
2449
2450 let padded_line_end = line_end + padding;
2451
2452 let min_column_in_pixels = ProjectSettings::get_global(cx)
2453 .git
2454 .inline_blame
2455 .and_then(|settings| settings.min_column)
2456 .map(|col| self.column_pixels(col as usize, window))
2457 .unwrap_or(px(0.));
2458 let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
2459
2460 cmp::max(padded_line_end, min_start)
2461 };
2462
2463 let absolute_offset = point(start_x, start_y);
2464 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
2465 let bounds = Bounds::new(absolute_offset, size);
2466
2467 self.layout_blame_entry_popover(entry.clone(), blame, line_height, text_hitbox, window, cx);
2468
2469 element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
2470
2471 Some(InlineBlameLayout {
2472 element,
2473 bounds,
2474 entry,
2475 })
2476 }
2477
2478 fn layout_blame_entry_popover(
2479 &self,
2480 blame_entry: BlameEntry,
2481 blame: Entity<GitBlame>,
2482 line_height: Pixels,
2483 text_hitbox: &Hitbox,
2484 window: &mut Window,
2485 cx: &mut App,
2486 ) {
2487 let Some((popover_state, target_point)) = self.editor.read_with(cx, |editor, _| {
2488 editor
2489 .inline_blame_popover
2490 .as_ref()
2491 .map(|state| (state.popover_state.clone(), state.position))
2492 }) else {
2493 return;
2494 };
2495
2496 let workspace = self
2497 .editor
2498 .read_with(cx, |editor, _| editor.workspace().map(|w| w.downgrade()));
2499
2500 let maybe_element = workspace.and_then(|workspace| {
2501 render_blame_entry_popover(
2502 blame_entry,
2503 popover_state.scroll_handle,
2504 popover_state.commit_message,
2505 popover_state.markdown,
2506 workspace,
2507 &blame,
2508 window,
2509 cx,
2510 )
2511 });
2512
2513 if let Some(mut element) = maybe_element {
2514 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
2515 let overall_height = size.height + HOVER_POPOVER_GAP;
2516 let popover_origin = if target_point.y > overall_height {
2517 point(target_point.x, target_point.y - size.height)
2518 } else {
2519 point(
2520 target_point.x,
2521 target_point.y + line_height + HOVER_POPOVER_GAP,
2522 )
2523 };
2524
2525 let horizontal_offset = (text_hitbox.top_right().x
2526 - POPOVER_RIGHT_OFFSET
2527 - (popover_origin.x + size.width))
2528 .min(Pixels::ZERO);
2529
2530 let origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
2531 let popover_bounds = Bounds::new(origin, size);
2532
2533 self.editor.update(cx, |editor, _| {
2534 if let Some(state) = &mut editor.inline_blame_popover {
2535 state.popover_bounds = Some(popover_bounds);
2536 }
2537 });
2538
2539 window.defer_draw(element, origin, 2);
2540 }
2541 }
2542
2543 fn layout_blame_entries(
2544 &self,
2545 buffer_rows: &[RowInfo],
2546 em_width: Pixels,
2547 scroll_position: gpui::Point<f32>,
2548 line_height: Pixels,
2549 gutter_hitbox: &Hitbox,
2550 max_width: Option<Pixels>,
2551 window: &mut Window,
2552 cx: &mut App,
2553 ) -> Option<Vec<AnyElement>> {
2554 if !self
2555 .editor
2556 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
2557 {
2558 return None;
2559 }
2560
2561 let blame = self.editor.read(cx).blame.clone()?;
2562 let workspace = self.editor.read(cx).workspace()?;
2563 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
2564 blame.blame_for_rows(buffer_rows, cx).collect()
2565 });
2566
2567 let width = if let Some(max_width) = max_width {
2568 AvailableSpace::Definite(max_width)
2569 } else {
2570 AvailableSpace::MaxContent
2571 };
2572 let scroll_top = scroll_position.y * line_height;
2573 let start_x = em_width;
2574
2575 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
2576 let blame_renderer = cx.global::<GlobalBlameRenderer>().0.clone();
2577
2578 let shaped_lines = blamed_rows
2579 .into_iter()
2580 .enumerate()
2581 .flat_map(|(ix, blame_entry)| {
2582 let mut element = render_blame_entry(
2583 ix,
2584 &blame,
2585 blame_entry?,
2586 &self.style,
2587 &mut last_used_color,
2588 self.editor.clone(),
2589 workspace.clone(),
2590 blame_renderer.clone(),
2591 cx,
2592 )?;
2593
2594 let start_y = ix as f32 * line_height - (scroll_top % line_height);
2595 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
2596
2597 element.prepaint_as_root(
2598 absolute_offset,
2599 size(width, AvailableSpace::MinContent),
2600 window,
2601 cx,
2602 );
2603
2604 Some(element)
2605 })
2606 .collect();
2607
2608 Some(shaped_lines)
2609 }
2610
2611 fn layout_indent_guides(
2612 &self,
2613 content_origin: gpui::Point<Pixels>,
2614 text_origin: gpui::Point<Pixels>,
2615 visible_buffer_range: Range<MultiBufferRow>,
2616 scroll_pixel_position: gpui::Point<Pixels>,
2617 line_height: Pixels,
2618 snapshot: &DisplaySnapshot,
2619 window: &mut Window,
2620 cx: &mut App,
2621 ) -> Option<Vec<IndentGuideLayout>> {
2622 if self.editor.read(cx).mode().is_minimap() {
2623 return None;
2624 }
2625 let indent_guides = self.editor.update(cx, |editor, cx| {
2626 editor.indent_guides(visible_buffer_range, snapshot, cx)
2627 })?;
2628
2629 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
2630 editor
2631 .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
2632 .unwrap_or_default()
2633 });
2634
2635 Some(
2636 indent_guides
2637 .into_iter()
2638 .enumerate()
2639 .filter_map(|(i, indent_guide)| {
2640 let single_indent_width =
2641 self.column_pixels(indent_guide.tab_size as usize, window);
2642 let total_width = single_indent_width * indent_guide.depth as f32;
2643 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
2644 if start_x >= text_origin.x {
2645 let (offset_y, length) = Self::calculate_indent_guide_bounds(
2646 indent_guide.start_row..indent_guide.end_row,
2647 line_height,
2648 snapshot,
2649 );
2650
2651 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
2652
2653 Some(IndentGuideLayout {
2654 origin: point(start_x, start_y),
2655 length,
2656 single_indent_width,
2657 depth: indent_guide.depth,
2658 active: active_indent_guide_indices.contains(&i),
2659 settings: indent_guide.settings,
2660 })
2661 } else {
2662 None
2663 }
2664 })
2665 .collect(),
2666 )
2667 }
2668
2669 fn layout_wrap_guides(
2670 &self,
2671 em_advance: Pixels,
2672 scroll_position: gpui::Point<f32>,
2673 content_origin: gpui::Point<Pixels>,
2674 scrollbar_layout: Option<&EditorScrollbars>,
2675 vertical_scrollbar_width: Pixels,
2676 hitbox: &Hitbox,
2677 window: &Window,
2678 cx: &App,
2679 ) -> SmallVec<[(Pixels, bool); 2]> {
2680 let scroll_left = scroll_position.x * em_advance;
2681 let content_origin = content_origin.x;
2682 let horizontal_offset = content_origin - scroll_left;
2683 let vertical_scrollbar_width = scrollbar_layout
2684 .and_then(|layout| layout.visible.then_some(vertical_scrollbar_width))
2685 .unwrap_or_default();
2686
2687 self.editor
2688 .read(cx)
2689 .wrap_guides(cx)
2690 .into_iter()
2691 .flat_map(|(guide, active)| {
2692 let wrap_position = self.column_pixels(guide, window);
2693 let wrap_guide_x = wrap_position + horizontal_offset;
2694 let display_wrap_guide = wrap_guide_x >= content_origin
2695 && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
2696
2697 display_wrap_guide.then_some((wrap_guide_x, active))
2698 })
2699 .collect()
2700 }
2701
2702 fn calculate_indent_guide_bounds(
2703 row_range: Range<MultiBufferRow>,
2704 line_height: Pixels,
2705 snapshot: &DisplaySnapshot,
2706 ) -> (gpui::Pixels, gpui::Pixels) {
2707 let start_point = Point::new(row_range.start.0, 0);
2708 let end_point = Point::new(row_range.end.0, 0);
2709
2710 let row_range = start_point.to_display_point(snapshot).row()
2711 ..end_point.to_display_point(snapshot).row();
2712
2713 let mut prev_line = start_point;
2714 prev_line.row = prev_line.row.saturating_sub(1);
2715 let prev_line = prev_line.to_display_point(snapshot).row();
2716
2717 let mut cons_line = end_point;
2718 cons_line.row += 1;
2719 let cons_line = cons_line.to_display_point(snapshot).row();
2720
2721 let mut offset_y = row_range.start.0 as f32 * line_height;
2722 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
2723
2724 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
2725 if row_range.end == cons_line {
2726 length += line_height;
2727 }
2728
2729 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
2730 // we want to extend the indent guide to the start of the block.
2731 let mut block_height = 0;
2732 let mut block_offset = 0;
2733 let mut found_excerpt_header = false;
2734 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
2735 if matches!(block, Block::ExcerptBoundary { .. }) {
2736 found_excerpt_header = true;
2737 break;
2738 }
2739 block_offset += block.height();
2740 block_height += block.height();
2741 }
2742 if !found_excerpt_header {
2743 offset_y -= block_offset as f32 * line_height;
2744 length += block_height as f32 * line_height;
2745 }
2746
2747 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
2748 // we want to ensure that the indent guide stops before the excerpt header.
2749 let mut block_height = 0;
2750 let mut found_excerpt_header = false;
2751 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
2752 if matches!(block, Block::ExcerptBoundary { .. }) {
2753 found_excerpt_header = true;
2754 }
2755 block_height += block.height();
2756 }
2757 if found_excerpt_header {
2758 length -= block_height as f32 * line_height;
2759 }
2760
2761 (offset_y, length)
2762 }
2763
2764 fn layout_breakpoints(
2765 &self,
2766 line_height: Pixels,
2767 range: Range<DisplayRow>,
2768 scroll_pixel_position: gpui::Point<Pixels>,
2769 gutter_dimensions: &GutterDimensions,
2770 gutter_hitbox: &Hitbox,
2771 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2772 snapshot: &EditorSnapshot,
2773 breakpoints: HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
2774 row_infos: &[RowInfo],
2775 window: &mut Window,
2776 cx: &mut App,
2777 ) -> Vec<AnyElement> {
2778 self.editor.update(cx, |editor, cx| {
2779 breakpoints
2780 .into_iter()
2781 .filter_map(|(display_row, (text_anchor, bp, state))| {
2782 if row_infos
2783 .get((display_row.0.saturating_sub(range.start.0)) as usize)
2784 .is_some_and(|row_info| {
2785 row_info.expand_info.is_some()
2786 || row_info
2787 .diff_status
2788 .is_some_and(|status| status.is_deleted())
2789 })
2790 {
2791 return None;
2792 }
2793
2794 if range.start > display_row || range.end < display_row {
2795 return None;
2796 }
2797
2798 let row =
2799 MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(&snapshot).row);
2800 if snapshot.is_line_folded(row) {
2801 return None;
2802 }
2803
2804 let button = editor.render_breakpoint(text_anchor, display_row, &bp, state, cx);
2805
2806 let button = prepaint_gutter_button(
2807 button,
2808 display_row,
2809 line_height,
2810 gutter_dimensions,
2811 scroll_pixel_position,
2812 gutter_hitbox,
2813 display_hunks,
2814 window,
2815 cx,
2816 );
2817 Some(button)
2818 })
2819 .collect_vec()
2820 })
2821 }
2822
2823 #[allow(clippy::too_many_arguments)]
2824 fn layout_run_indicators(
2825 &self,
2826 line_height: Pixels,
2827 range: Range<DisplayRow>,
2828 row_infos: &[RowInfo],
2829 scroll_pixel_position: gpui::Point<Pixels>,
2830 gutter_dimensions: &GutterDimensions,
2831 gutter_hitbox: &Hitbox,
2832 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2833 snapshot: &EditorSnapshot,
2834 breakpoints: &mut HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
2835 window: &mut Window,
2836 cx: &mut App,
2837 ) -> Vec<AnyElement> {
2838 self.editor.update(cx, |editor, cx| {
2839 let active_task_indicator_row =
2840 // TODO: add edit button on the right side of each row in the context menu
2841 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2842 deployed_from,
2843 actions,
2844 ..
2845 })) = editor.context_menu.borrow().as_ref()
2846 {
2847 actions
2848 .tasks()
2849 .map(|tasks| tasks.position.to_display_point(snapshot).row())
2850 .or_else(|| match deployed_from {
2851 Some(CodeActionSource::Indicator(row)) => Some(*row),
2852 _ => None,
2853 })
2854 } else {
2855 None
2856 };
2857
2858 let offset_range_start =
2859 snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left);
2860
2861 let offset_range_end =
2862 snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
2863
2864 editor
2865 .tasks
2866 .iter()
2867 .filter_map(|(_, tasks)| {
2868 let multibuffer_point = tasks.offset.to_point(&snapshot.buffer_snapshot);
2869 if multibuffer_point < offset_range_start
2870 || multibuffer_point > offset_range_end
2871 {
2872 return None;
2873 }
2874 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
2875 let buffer_folded = snapshot
2876 .buffer_snapshot
2877 .buffer_line_for_row(multibuffer_row)
2878 .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
2879 .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
2880 .unwrap_or(false);
2881 if buffer_folded {
2882 return None;
2883 }
2884
2885 if snapshot.is_line_folded(multibuffer_row) {
2886 // Skip folded indicators, unless it's the starting line of a fold.
2887 if multibuffer_row
2888 .0
2889 .checked_sub(1)
2890 .map_or(false, |previous_row| {
2891 snapshot.is_line_folded(MultiBufferRow(previous_row))
2892 })
2893 {
2894 return None;
2895 }
2896 }
2897
2898 let display_row = multibuffer_point.to_display_point(snapshot).row();
2899 if !range.contains(&display_row) {
2900 return None;
2901 }
2902 if row_infos
2903 .get((display_row - range.start).0 as usize)
2904 .is_some_and(|row_info| row_info.expand_info.is_some())
2905 {
2906 return None;
2907 }
2908
2909 let button = editor.render_run_indicator(
2910 &self.style,
2911 Some(display_row) == active_task_indicator_row,
2912 display_row,
2913 breakpoints.remove(&display_row),
2914 cx,
2915 );
2916
2917 let button = prepaint_gutter_button(
2918 button,
2919 display_row,
2920 line_height,
2921 gutter_dimensions,
2922 scroll_pixel_position,
2923 gutter_hitbox,
2924 display_hunks,
2925 window,
2926 cx,
2927 );
2928 Some(button)
2929 })
2930 .collect_vec()
2931 })
2932 }
2933
2934 fn layout_expand_toggles(
2935 &self,
2936 gutter_hitbox: &Hitbox,
2937 gutter_dimensions: GutterDimensions,
2938 em_width: Pixels,
2939 line_height: Pixels,
2940 scroll_position: gpui::Point<f32>,
2941 buffer_rows: &[RowInfo],
2942 window: &mut Window,
2943 cx: &mut App,
2944 ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
2945 if self.editor.read(cx).disable_expand_excerpt_buttons {
2946 return vec![];
2947 }
2948
2949 let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
2950
2951 let scroll_top = scroll_position.y * line_height;
2952
2953 let max_line_number_length = self
2954 .editor
2955 .read(cx)
2956 .buffer()
2957 .read(cx)
2958 .snapshot(cx)
2959 .widest_line_number()
2960 .ilog10()
2961 + 1;
2962
2963 let elements = buffer_rows
2964 .into_iter()
2965 .enumerate()
2966 .map(|(ix, row_info)| {
2967 let ExpandInfo {
2968 excerpt_id,
2969 direction,
2970 } = row_info.expand_info?;
2971
2972 let icon_name = match direction {
2973 ExpandExcerptDirection::Up => IconName::ExpandUp,
2974 ExpandExcerptDirection::Down => IconName::ExpandDown,
2975 ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
2976 };
2977
2978 let git_gutter_width = Self::gutter_strip_width(line_height);
2979 let available_width = gutter_dimensions.left_padding - git_gutter_width;
2980
2981 let editor = self.editor.clone();
2982 let is_wide = max_line_number_length
2983 >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
2984 && row_info
2985 .buffer_row
2986 .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
2987 || gutter_dimensions.right_padding == px(0.);
2988
2989 let width = if is_wide {
2990 available_width - px(2.)
2991 } else {
2992 available_width + em_width - px(2.)
2993 };
2994
2995 let toggle = IconButton::new(("expand", ix), icon_name)
2996 .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
2997 .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
2998 .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
2999 .width(width.into())
3000 .on_click(move |_, window, cx| {
3001 editor.update(cx, |editor, cx| {
3002 editor.expand_excerpt(excerpt_id, direction, window, cx);
3003 });
3004 })
3005 .tooltip(Tooltip::for_action_title(
3006 "Expand Excerpt",
3007 &crate::actions::ExpandExcerpts::default(),
3008 ))
3009 .into_any_element();
3010
3011 let position = point(
3012 git_gutter_width + px(1.),
3013 ix as f32 * line_height - (scroll_top % line_height) + px(1.),
3014 );
3015 let origin = gutter_hitbox.origin + position;
3016
3017 Some((toggle, origin))
3018 })
3019 .collect();
3020
3021 elements
3022 }
3023
3024 fn calculate_relative_line_numbers(
3025 &self,
3026 snapshot: &EditorSnapshot,
3027 rows: &Range<DisplayRow>,
3028 relative_to: Option<DisplayRow>,
3029 ) -> HashMap<DisplayRow, DisplayRowDelta> {
3030 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
3031 let Some(relative_to) = relative_to else {
3032 return relative_rows;
3033 };
3034
3035 let start = rows.start.min(relative_to);
3036 let end = rows.end.max(relative_to);
3037
3038 let buffer_rows = snapshot
3039 .row_infos(start)
3040 .take(1 + end.minus(start) as usize)
3041 .collect::<Vec<_>>();
3042
3043 let head_idx = relative_to.minus(start);
3044 let mut delta = 1;
3045 let mut i = head_idx + 1;
3046 while i < buffer_rows.len() as u32 {
3047 if buffer_rows[i as usize].buffer_row.is_some() {
3048 if rows.contains(&DisplayRow(i + start.0)) {
3049 relative_rows.insert(DisplayRow(i + start.0), delta);
3050 }
3051 delta += 1;
3052 }
3053 i += 1;
3054 }
3055 delta = 1;
3056 i = head_idx.min(buffer_rows.len() as u32 - 1);
3057 while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
3058 i -= 1;
3059 }
3060
3061 while i > 0 {
3062 i -= 1;
3063 if buffer_rows[i as usize].buffer_row.is_some() {
3064 if rows.contains(&DisplayRow(i + start.0)) {
3065 relative_rows.insert(DisplayRow(i + start.0), delta);
3066 }
3067 delta += 1;
3068 }
3069 }
3070
3071 relative_rows
3072 }
3073
3074 fn layout_line_numbers(
3075 &self,
3076 gutter_hitbox: Option<&Hitbox>,
3077 gutter_dimensions: GutterDimensions,
3078 line_height: Pixels,
3079 scroll_position: gpui::Point<f32>,
3080 rows: Range<DisplayRow>,
3081 buffer_rows: &[RowInfo],
3082 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3083 newest_selection_head: Option<DisplayPoint>,
3084 snapshot: &EditorSnapshot,
3085 window: &mut Window,
3086 cx: &mut App,
3087 ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
3088 let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
3089 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode.is_full()
3090 });
3091 if !include_line_numbers {
3092 return Arc::default();
3093 }
3094
3095 let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
3096 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
3097 let newest = editor.selections.newest::<Point>(cx);
3098 SelectionLayout::new(
3099 newest,
3100 editor.selections.line_mode,
3101 editor.cursor_shape,
3102 &snapshot.display_snapshot,
3103 true,
3104 true,
3105 None,
3106 )
3107 .head
3108 });
3109 let is_relative = editor.should_use_relative_line_numbers(cx);
3110 (newest_selection_head, is_relative)
3111 });
3112
3113 let relative_to = if is_relative {
3114 Some(newest_selection_head.row())
3115 } else {
3116 None
3117 };
3118 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
3119 let mut line_number = String::new();
3120 let line_numbers = buffer_rows
3121 .into_iter()
3122 .enumerate()
3123 .flat_map(|(ix, row_info)| {
3124 let display_row = DisplayRow(rows.start.0 + ix as u32);
3125 line_number.clear();
3126 let non_relative_number = row_info.buffer_row? + 1;
3127 let number = relative_rows
3128 .get(&display_row)
3129 .unwrap_or(&non_relative_number);
3130 write!(&mut line_number, "{number}").unwrap();
3131 if row_info
3132 .diff_status
3133 .is_some_and(|status| status.is_deleted())
3134 {
3135 return None;
3136 }
3137
3138 let color = active_rows
3139 .get(&display_row)
3140 .map(|spec| {
3141 if spec.breakpoint {
3142 cx.theme().colors().debugger_accent
3143 } else {
3144 cx.theme().colors().editor_active_line_number
3145 }
3146 })
3147 .unwrap_or_else(|| cx.theme().colors().editor_line_number);
3148 let shaped_line =
3149 self.shape_line_number(SharedString::from(&line_number), color, window);
3150 let scroll_top = scroll_position.y * line_height;
3151 let line_origin = gutter_hitbox.map(|hitbox| {
3152 hitbox.origin
3153 + point(
3154 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
3155 ix as f32 * line_height - (scroll_top % line_height),
3156 )
3157 });
3158
3159 #[cfg(not(test))]
3160 let hitbox = line_origin.map(|line_origin| {
3161 window.insert_hitbox(
3162 Bounds::new(line_origin, size(shaped_line.width, line_height)),
3163 HitboxBehavior::Normal,
3164 )
3165 });
3166 #[cfg(test)]
3167 let hitbox = {
3168 let _ = line_origin;
3169 None
3170 };
3171
3172 let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
3173 let multi_buffer_row = MultiBufferRow(multi_buffer_row);
3174 let line_number = LineNumberLayout {
3175 shaped_line,
3176 hitbox,
3177 };
3178 Some((multi_buffer_row, line_number))
3179 })
3180 .collect();
3181 Arc::new(line_numbers)
3182 }
3183
3184 fn layout_crease_toggles(
3185 &self,
3186 rows: Range<DisplayRow>,
3187 row_infos: &[RowInfo],
3188 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3189 snapshot: &EditorSnapshot,
3190 window: &mut Window,
3191 cx: &mut App,
3192 ) -> Vec<Option<AnyElement>> {
3193 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
3194 && snapshot.mode.is_full()
3195 && self.editor.read(cx).is_singleton(cx);
3196 if include_fold_statuses {
3197 row_infos
3198 .into_iter()
3199 .enumerate()
3200 .map(|(ix, info)| {
3201 if info.expand_info.is_some() {
3202 return None;
3203 }
3204 let row = info.multibuffer_row?;
3205 let display_row = DisplayRow(rows.start.0 + ix as u32);
3206 let active = active_rows.contains_key(&display_row);
3207
3208 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
3209 })
3210 .collect()
3211 } else {
3212 Vec::new()
3213 }
3214 }
3215
3216 fn layout_crease_trailers(
3217 &self,
3218 buffer_rows: impl IntoIterator<Item = RowInfo>,
3219 snapshot: &EditorSnapshot,
3220 window: &mut Window,
3221 cx: &mut App,
3222 ) -> Vec<Option<AnyElement>> {
3223 buffer_rows
3224 .into_iter()
3225 .map(|row_info| {
3226 if row_info.expand_info.is_some() {
3227 return None;
3228 }
3229 if let Some(row) = row_info.multibuffer_row {
3230 snapshot.render_crease_trailer(row, window, cx)
3231 } else {
3232 None
3233 }
3234 })
3235 .collect()
3236 }
3237
3238 fn layout_lines(
3239 rows: Range<DisplayRow>,
3240 snapshot: &EditorSnapshot,
3241 style: &EditorStyle,
3242 editor_width: Pixels,
3243 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3244 window: &mut Window,
3245 cx: &mut App,
3246 ) -> Vec<LineWithInvisibles> {
3247 if rows.start >= rows.end {
3248 return Vec::new();
3249 }
3250
3251 // Show the placeholder when the editor is empty
3252 if snapshot.is_empty() {
3253 let font_size = style.text.font_size.to_pixels(window.rem_size());
3254 let placeholder_color = cx.theme().colors().text_placeholder;
3255 let placeholder_text = snapshot.placeholder_text();
3256
3257 let placeholder_lines = placeholder_text
3258 .as_ref()
3259 .map_or("", AsRef::as_ref)
3260 .split('\n')
3261 .skip(rows.start.0 as usize)
3262 .chain(iter::repeat(""))
3263 .take(rows.len());
3264 placeholder_lines
3265 .map(move |line| {
3266 let run = TextRun {
3267 len: line.len(),
3268 font: style.text.font(),
3269 color: placeholder_color,
3270 background_color: None,
3271 underline: None,
3272 strikethrough: None,
3273 };
3274 let line = window.text_system().shape_line(
3275 line.to_string().into(),
3276 font_size,
3277 &[run],
3278 None,
3279 );
3280 LineWithInvisibles {
3281 width: line.width,
3282 len: line.len,
3283 fragments: smallvec![LineFragment::Text(line)],
3284 invisibles: Vec::new(),
3285 font_size,
3286 }
3287 })
3288 .collect()
3289 } else {
3290 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
3291 LineWithInvisibles::from_chunks(
3292 chunks,
3293 &style,
3294 MAX_LINE_LEN,
3295 rows.len(),
3296 &snapshot.mode,
3297 editor_width,
3298 is_row_soft_wrapped,
3299 window,
3300 cx,
3301 )
3302 }
3303 }
3304
3305 fn prepaint_lines(
3306 &self,
3307 start_row: DisplayRow,
3308 line_layouts: &mut [LineWithInvisibles],
3309 line_height: Pixels,
3310 scroll_pixel_position: gpui::Point<Pixels>,
3311 content_origin: gpui::Point<Pixels>,
3312 window: &mut Window,
3313 cx: &mut App,
3314 ) -> SmallVec<[AnyElement; 1]> {
3315 let mut line_elements = SmallVec::new();
3316 for (ix, line) in line_layouts.iter_mut().enumerate() {
3317 let row = start_row + DisplayRow(ix as u32);
3318 line.prepaint(
3319 line_height,
3320 scroll_pixel_position,
3321 row,
3322 content_origin,
3323 &mut line_elements,
3324 window,
3325 cx,
3326 );
3327 }
3328 line_elements
3329 }
3330
3331 fn render_block(
3332 &self,
3333 block: &Block,
3334 available_width: AvailableSpace,
3335 block_id: BlockId,
3336 block_row_start: DisplayRow,
3337 snapshot: &EditorSnapshot,
3338 text_x: Pixels,
3339 rows: &Range<DisplayRow>,
3340 line_layouts: &[LineWithInvisibles],
3341 editor_margins: &EditorMargins,
3342 line_height: Pixels,
3343 em_width: Pixels,
3344 text_hitbox: &Hitbox,
3345 editor_width: Pixels,
3346 scroll_width: &mut Pixels,
3347 resized_blocks: &mut HashMap<CustomBlockId, u32>,
3348 row_block_types: &mut HashMap<DisplayRow, bool>,
3349 selections: &[Selection<Point>],
3350 selected_buffer_ids: &Vec<BufferId>,
3351 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3352 sticky_header_excerpt_id: Option<ExcerptId>,
3353 window: &mut Window,
3354 cx: &mut App,
3355 ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
3356 let mut x_position = None;
3357 let mut element = match block {
3358 Block::Custom(custom) => {
3359 let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
3360 let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
3361 if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
3362 return None;
3363 }
3364 let align_to = block_start.to_display_point(snapshot);
3365 let x_and_width = |layout: &LineWithInvisibles| {
3366 Some((
3367 text_x + layout.x_for_index(align_to.column() as usize),
3368 text_x + layout.width,
3369 ))
3370 };
3371 let line_ix = align_to.row().0.checked_sub(rows.start.0);
3372 x_position =
3373 if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
3374 x_and_width(&layout)
3375 } else {
3376 x_and_width(&layout_line(
3377 align_to.row(),
3378 snapshot,
3379 &self.style,
3380 editor_width,
3381 is_row_soft_wrapped,
3382 window,
3383 cx,
3384 ))
3385 };
3386
3387 let anchor_x = x_position.unwrap().0;
3388
3389 let selected = selections
3390 .binary_search_by(|selection| {
3391 if selection.end <= block_start {
3392 Ordering::Less
3393 } else if selection.start >= block_end {
3394 Ordering::Greater
3395 } else {
3396 Ordering::Equal
3397 }
3398 })
3399 .is_ok();
3400
3401 div()
3402 .size_full()
3403 .children(
3404 (!snapshot.mode.is_minimap() || custom.render_in_minimap).then(|| {
3405 custom.render(&mut BlockContext {
3406 window,
3407 app: cx,
3408 anchor_x,
3409 margins: editor_margins,
3410 line_height,
3411 em_width,
3412 block_id,
3413 selected,
3414 max_width: text_hitbox.size.width.max(*scroll_width),
3415 editor_style: &self.style,
3416 })
3417 }),
3418 )
3419 .into_any()
3420 }
3421
3422 Block::FoldedBuffer {
3423 first_excerpt,
3424 height,
3425 ..
3426 } => {
3427 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
3428 let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
3429
3430 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
3431 result
3432 .child(self.render_buffer_header(
3433 first_excerpt,
3434 true,
3435 selected,
3436 false,
3437 jump_data,
3438 window,
3439 cx,
3440 ))
3441 .into_any_element()
3442 }
3443
3444 Block::ExcerptBoundary {
3445 excerpt,
3446 height,
3447 starts_new_buffer,
3448 ..
3449 } => {
3450 let color = cx.theme().colors().clone();
3451 let mut result = v_flex().id(block_id).w_full();
3452
3453 let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
3454
3455 if *starts_new_buffer {
3456 if sticky_header_excerpt_id != Some(excerpt.id) {
3457 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3458
3459 result = result.child(div().pr(editor_margins.right).child(
3460 self.render_buffer_header(
3461 excerpt, false, selected, false, jump_data, window, cx,
3462 ),
3463 ));
3464 } else {
3465 result =
3466 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3467 }
3468 } else {
3469 result = result.child(
3470 h_flex().relative().child(
3471 div()
3472 .top(line_height / 2.)
3473 .absolute()
3474 .w_full()
3475 .h_px()
3476 .bg(color.border_variant),
3477 ),
3478 );
3479 };
3480
3481 result.into_any()
3482 }
3483 };
3484
3485 // Discover the element's content height, then round up to the nearest multiple of line height.
3486 let preliminary_size = element.layout_as_root(
3487 size(available_width, AvailableSpace::MinContent),
3488 window,
3489 cx,
3490 );
3491 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
3492 let final_size = if preliminary_size.height == quantized_height {
3493 preliminary_size
3494 } else {
3495 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
3496 };
3497 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
3498
3499 let mut row = block_row_start;
3500 let mut x_offset = px(0.);
3501 let mut is_block = true;
3502
3503 if let BlockId::Custom(custom_block_id) = block_id {
3504 if block.has_height() {
3505 if block.place_near() {
3506 if let Some((x_target, line_width)) = x_position {
3507 let margin = em_width * 2;
3508 if line_width + final_size.width + margin
3509 < editor_width + editor_margins.gutter.full_width()
3510 && !row_block_types.contains_key(&(row - 1))
3511 && element_height_in_lines == 1
3512 {
3513 x_offset = line_width + margin;
3514 row = row - 1;
3515 is_block = false;
3516 element_height_in_lines = 0;
3517 row_block_types.insert(row, is_block);
3518 } else {
3519 let max_offset = editor_width + editor_margins.gutter.full_width()
3520 - final_size.width;
3521 let min_offset = (x_target + em_width - final_size.width)
3522 .max(editor_margins.gutter.full_width());
3523 x_offset = x_target.min(max_offset).max(min_offset);
3524 }
3525 }
3526 };
3527 if element_height_in_lines != block.height() {
3528 resized_blocks.insert(custom_block_id, element_height_in_lines);
3529 }
3530 }
3531 }
3532 for i in 0..element_height_in_lines {
3533 row_block_types.insert(row + i, is_block);
3534 }
3535
3536 Some((element, final_size, row, x_offset))
3537 }
3538
3539 fn render_buffer_header(
3540 &self,
3541 for_excerpt: &ExcerptInfo,
3542 is_folded: bool,
3543 is_selected: bool,
3544 is_sticky: bool,
3545 jump_data: JumpData,
3546 window: &mut Window,
3547 cx: &mut App,
3548 ) -> Div {
3549 let editor = self.editor.read(cx);
3550 let file_status = editor
3551 .buffer
3552 .read(cx)
3553 .all_diff_hunks_expanded()
3554 .then(|| {
3555 editor
3556 .project
3557 .as_ref()?
3558 .read(cx)
3559 .status_for_buffer_id(for_excerpt.buffer_id, cx)
3560 })
3561 .flatten();
3562
3563 let include_root = editor
3564 .project
3565 .as_ref()
3566 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
3567 .unwrap_or_default();
3568 let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
3569 let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
3570 let filename = path
3571 .as_ref()
3572 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
3573 let parent_path = path.as_ref().and_then(|path| {
3574 Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
3575 });
3576 let focus_handle = editor.focus_handle(cx);
3577 let colors = cx.theme().colors();
3578
3579 div()
3580 .p_1()
3581 .w_full()
3582 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3583 .child(
3584 h_flex()
3585 .size_full()
3586 .gap_2()
3587 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3588 .pl_0p5()
3589 .pr_5()
3590 .rounded_sm()
3591 .when(is_sticky, |el| el.shadow_md())
3592 .border_1()
3593 .map(|div| {
3594 let border_color = if is_selected
3595 && is_folded
3596 && focus_handle.contains_focused(window, cx)
3597 {
3598 colors.border_focused
3599 } else {
3600 colors.border
3601 };
3602 div.border_color(border_color)
3603 })
3604 .bg(colors.editor_subheader_background)
3605 .hover(|style| style.bg(colors.element_hover))
3606 .map(|header| {
3607 let editor = self.editor.clone();
3608 let buffer_id = for_excerpt.buffer_id;
3609 let toggle_chevron_icon =
3610 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3611 header.child(
3612 div()
3613 .hover(|style| style.bg(colors.element_selected))
3614 .rounded_xs()
3615 .child(
3616 ButtonLike::new("toggle-buffer-fold")
3617 .style(ui::ButtonStyle::Transparent)
3618 .height(px(28.).into())
3619 .width(px(28.).into())
3620 .children(toggle_chevron_icon)
3621 .tooltip({
3622 let focus_handle = focus_handle.clone();
3623 move |window, cx| {
3624 Tooltip::with_meta_in(
3625 "Toggle Excerpt Fold",
3626 Some(&ToggleFold),
3627 "Alt+click to toggle all",
3628 &focus_handle,
3629 window,
3630 cx,
3631 )
3632 }
3633 })
3634 .on_click(move |event, window, cx| {
3635 if event.modifiers().alt {
3636 // Alt+click toggles all buffers
3637 editor.update(cx, |editor, cx| {
3638 editor.toggle_fold_all(
3639 &ToggleFoldAll,
3640 window,
3641 cx,
3642 );
3643 });
3644 } else {
3645 // Regular click toggles single buffer
3646 if is_folded {
3647 editor.update(cx, |editor, cx| {
3648 editor.unfold_buffer(buffer_id, cx);
3649 });
3650 } else {
3651 editor.update(cx, |editor, cx| {
3652 editor.fold_buffer(buffer_id, cx);
3653 });
3654 }
3655 }
3656 }),
3657 ),
3658 )
3659 })
3660 .children(
3661 editor
3662 .addons
3663 .values()
3664 .filter_map(|addon| {
3665 addon.render_buffer_header_controls(for_excerpt, window, cx)
3666 })
3667 .take(1),
3668 )
3669 .child(
3670 h_flex()
3671 .cursor_pointer()
3672 .id("path header block")
3673 .size_full()
3674 .justify_between()
3675 .child(
3676 h_flex()
3677 .gap_2()
3678 .child(
3679 Label::new(
3680 filename
3681 .map(SharedString::from)
3682 .unwrap_or_else(|| "untitled".into()),
3683 )
3684 .single_line()
3685 .when_some(
3686 file_status,
3687 |el, status| {
3688 el.color(if status.is_conflicted() {
3689 Color::Conflict
3690 } else if status.is_modified() {
3691 Color::Modified
3692 } else if status.is_deleted() {
3693 Color::Disabled
3694 } else {
3695 Color::Created
3696 })
3697 .when(status.is_deleted(), |el| el.strikethrough())
3698 },
3699 ),
3700 )
3701 .when_some(parent_path, |then, path| {
3702 then.child(div().child(path).text_color(
3703 if file_status.is_some_and(FileStatus::is_deleted) {
3704 colors.text_disabled
3705 } else {
3706 colors.text_muted
3707 },
3708 ))
3709 }),
3710 )
3711 .when(can_open_excerpts && is_selected && path.is_some(), |el| {
3712 el.child(
3713 h_flex()
3714 .id("jump-to-file-button")
3715 .gap_2p5()
3716 .child(Label::new("Jump To File"))
3717 .children(
3718 KeyBinding::for_action_in(
3719 &OpenExcerpts,
3720 &focus_handle,
3721 window,
3722 cx,
3723 )
3724 .map(|binding| binding.into_any_element()),
3725 ),
3726 )
3727 })
3728 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
3729 .on_click(window.listener_for(&self.editor, {
3730 move |editor, e: &ClickEvent, window, cx| {
3731 editor.open_excerpts_common(
3732 Some(jump_data.clone()),
3733 e.down.modifiers.secondary(),
3734 window,
3735 cx,
3736 );
3737 }
3738 })),
3739 ),
3740 )
3741 }
3742
3743 fn render_blocks(
3744 &self,
3745 rows: Range<DisplayRow>,
3746 snapshot: &EditorSnapshot,
3747 hitbox: &Hitbox,
3748 text_hitbox: &Hitbox,
3749 editor_width: Pixels,
3750 scroll_width: &mut Pixels,
3751 editor_margins: &EditorMargins,
3752 em_width: Pixels,
3753 text_x: Pixels,
3754 line_height: Pixels,
3755 line_layouts: &mut [LineWithInvisibles],
3756 selections: &[Selection<Point>],
3757 selected_buffer_ids: &Vec<BufferId>,
3758 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3759 sticky_header_excerpt_id: Option<ExcerptId>,
3760 window: &mut Window,
3761 cx: &mut App,
3762 ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
3763 let (fixed_blocks, non_fixed_blocks) = snapshot
3764 .blocks_in_range(rows.clone())
3765 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
3766
3767 let mut focused_block = self
3768 .editor
3769 .update(cx, |editor, _| editor.take_focused_block());
3770 let mut fixed_block_max_width = Pixels::ZERO;
3771 let mut blocks = Vec::new();
3772 let mut resized_blocks = HashMap::default();
3773 let mut row_block_types = HashMap::default();
3774
3775 for (row, block) in fixed_blocks {
3776 let block_id = block.id();
3777
3778 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3779 focused_block = None;
3780 }
3781
3782 if let Some((element, element_size, row, x_offset)) = self.render_block(
3783 block,
3784 AvailableSpace::MinContent,
3785 block_id,
3786 row,
3787 snapshot,
3788 text_x,
3789 &rows,
3790 line_layouts,
3791 editor_margins,
3792 line_height,
3793 em_width,
3794 text_hitbox,
3795 editor_width,
3796 scroll_width,
3797 &mut resized_blocks,
3798 &mut row_block_types,
3799 selections,
3800 selected_buffer_ids,
3801 is_row_soft_wrapped,
3802 sticky_header_excerpt_id,
3803 window,
3804 cx,
3805 ) {
3806 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
3807 blocks.push(BlockLayout {
3808 id: block_id,
3809 x_offset,
3810 row: Some(row),
3811 element,
3812 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
3813 style: BlockStyle::Fixed,
3814 overlaps_gutter: true,
3815 is_buffer_header: block.is_buffer_header(),
3816 });
3817 }
3818 }
3819
3820 for (row, block) in non_fixed_blocks {
3821 let style = block.style();
3822 let width = match (style, block.place_near()) {
3823 (_, true) => AvailableSpace::MinContent,
3824 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
3825 (BlockStyle::Flex, _) => hitbox
3826 .size
3827 .width
3828 .max(fixed_block_max_width)
3829 .max(editor_margins.gutter.width + *scroll_width)
3830 .into(),
3831 (BlockStyle::Fixed, _) => unreachable!(),
3832 };
3833 let block_id = block.id();
3834
3835 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3836 focused_block = None;
3837 }
3838
3839 if let Some((element, element_size, row, x_offset)) = self.render_block(
3840 block,
3841 width,
3842 block_id,
3843 row,
3844 snapshot,
3845 text_x,
3846 &rows,
3847 line_layouts,
3848 editor_margins,
3849 line_height,
3850 em_width,
3851 text_hitbox,
3852 editor_width,
3853 scroll_width,
3854 &mut resized_blocks,
3855 &mut row_block_types,
3856 selections,
3857 selected_buffer_ids,
3858 is_row_soft_wrapped,
3859 sticky_header_excerpt_id,
3860 window,
3861 cx,
3862 ) {
3863 blocks.push(BlockLayout {
3864 id: block_id,
3865 x_offset,
3866 row: Some(row),
3867 element,
3868 available_space: size(width, element_size.height.into()),
3869 style,
3870 overlaps_gutter: !block.place_near(),
3871 is_buffer_header: block.is_buffer_header(),
3872 });
3873 }
3874 }
3875
3876 if let Some(focused_block) = focused_block {
3877 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
3878 if focus_handle.is_focused(window) {
3879 if let Some(block) = snapshot.block_for_id(focused_block.id) {
3880 let style = block.style();
3881 let width = match style {
3882 BlockStyle::Fixed => AvailableSpace::MinContent,
3883 BlockStyle::Flex => AvailableSpace::Definite(
3884 hitbox
3885 .size
3886 .width
3887 .max(fixed_block_max_width)
3888 .max(editor_margins.gutter.width + *scroll_width),
3889 ),
3890 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
3891 };
3892
3893 if let Some((element, element_size, _, x_offset)) = self.render_block(
3894 &block,
3895 width,
3896 focused_block.id,
3897 rows.end,
3898 snapshot,
3899 text_x,
3900 &rows,
3901 line_layouts,
3902 editor_margins,
3903 line_height,
3904 em_width,
3905 text_hitbox,
3906 editor_width,
3907 scroll_width,
3908 &mut resized_blocks,
3909 &mut row_block_types,
3910 selections,
3911 selected_buffer_ids,
3912 is_row_soft_wrapped,
3913 sticky_header_excerpt_id,
3914 window,
3915 cx,
3916 ) {
3917 blocks.push(BlockLayout {
3918 id: block.id(),
3919 x_offset,
3920 row: None,
3921 element,
3922 available_space: size(width, element_size.height.into()),
3923 style,
3924 overlaps_gutter: true,
3925 is_buffer_header: block.is_buffer_header(),
3926 });
3927 }
3928 }
3929 }
3930 }
3931 }
3932
3933 if resized_blocks.is_empty() {
3934 *scroll_width =
3935 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
3936 Ok((blocks, row_block_types))
3937 } else {
3938 Err(resized_blocks)
3939 }
3940 }
3941
3942 fn layout_blocks(
3943 &self,
3944 blocks: &mut Vec<BlockLayout>,
3945 hitbox: &Hitbox,
3946 line_height: Pixels,
3947 scroll_pixel_position: gpui::Point<Pixels>,
3948 window: &mut Window,
3949 cx: &mut App,
3950 ) {
3951 for block in blocks {
3952 let mut origin = if let Some(row) = block.row {
3953 hitbox.origin
3954 + point(
3955 block.x_offset,
3956 row.as_f32() * line_height - scroll_pixel_position.y,
3957 )
3958 } else {
3959 // Position the block outside the visible area
3960 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
3961 };
3962
3963 if !matches!(block.style, BlockStyle::Sticky) {
3964 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
3965 }
3966
3967 let focus_handle =
3968 block
3969 .element
3970 .prepaint_as_root(origin, block.available_space, window, cx);
3971
3972 if let Some(focus_handle) = focus_handle {
3973 self.editor.update(cx, |editor, _cx| {
3974 editor.set_focused_block(FocusedBlock {
3975 id: block.id,
3976 focus_handle: focus_handle.downgrade(),
3977 });
3978 });
3979 }
3980 }
3981 }
3982
3983 fn layout_sticky_buffer_header(
3984 &self,
3985 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
3986 scroll_position: f32,
3987 line_height: Pixels,
3988 right_margin: Pixels,
3989 snapshot: &EditorSnapshot,
3990 hitbox: &Hitbox,
3991 selected_buffer_ids: &Vec<BufferId>,
3992 blocks: &[BlockLayout],
3993 window: &mut Window,
3994 cx: &mut App,
3995 ) -> AnyElement {
3996 let jump_data = header_jump_data(
3997 snapshot,
3998 DisplayRow(scroll_position as u32),
3999 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4000 excerpt,
4001 );
4002
4003 let editor_bg_color = cx.theme().colors().editor_background;
4004
4005 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4006
4007 let available_width = hitbox.bounds.size.width - right_margin;
4008
4009 let mut header = v_flex()
4010 .relative()
4011 .child(
4012 div()
4013 .w(available_width)
4014 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4015 .bg(linear_gradient(
4016 0.,
4017 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4018 linear_color_stop(editor_bg_color, 0.6),
4019 ))
4020 .absolute()
4021 .top_0(),
4022 )
4023 .child(
4024 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4025 .into_any_element(),
4026 )
4027 .into_any_element();
4028
4029 let mut origin = hitbox.origin;
4030 // Move floating header up to avoid colliding with the next buffer header.
4031 for block in blocks.iter() {
4032 if !block.is_buffer_header {
4033 continue;
4034 }
4035
4036 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
4037 continue;
4038 };
4039
4040 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4041 let offset = scroll_position - max_row as f32;
4042
4043 if offset > 0.0 {
4044 origin.y -= offset * line_height;
4045 }
4046 break;
4047 }
4048
4049 let size = size(
4050 AvailableSpace::Definite(available_width),
4051 AvailableSpace::MinContent,
4052 );
4053
4054 header.prepaint_as_root(origin, size, window, cx);
4055
4056 header
4057 }
4058
4059 fn layout_cursor_popovers(
4060 &self,
4061 line_height: Pixels,
4062 text_hitbox: &Hitbox,
4063 content_origin: gpui::Point<Pixels>,
4064 right_margin: Pixels,
4065 start_row: DisplayRow,
4066 scroll_pixel_position: gpui::Point<Pixels>,
4067 line_layouts: &[LineWithInvisibles],
4068 cursor: DisplayPoint,
4069 cursor_point: Point,
4070 style: &EditorStyle,
4071 window: &mut Window,
4072 cx: &mut App,
4073 ) -> Option<ContextMenuLayout> {
4074 let mut min_menu_height = Pixels::ZERO;
4075 let mut max_menu_height = Pixels::ZERO;
4076 let mut height_above_menu = Pixels::ZERO;
4077 let height_below_menu = Pixels::ZERO;
4078 let mut edit_prediction_popover_visible = false;
4079 let mut context_menu_visible = false;
4080 let context_menu_placement;
4081
4082 {
4083 let editor = self.editor.read(cx);
4084 if editor
4085 .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
4086 {
4087 height_above_menu +=
4088 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4089 edit_prediction_popover_visible = true;
4090 }
4091
4092 if editor.context_menu_visible() {
4093 if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
4094 let (min_height_in_lines, max_height_in_lines) = editor
4095 .context_menu_options
4096 .as_ref()
4097 .map_or((3, 12), |options| {
4098 (options.min_entries_visible, options.max_entries_visible)
4099 });
4100
4101 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4102 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4103 context_menu_visible = true;
4104 }
4105 }
4106 context_menu_placement = editor
4107 .context_menu_options
4108 .as_ref()
4109 .and_then(|options| options.placement.clone());
4110 }
4111
4112 let visible = edit_prediction_popover_visible || context_menu_visible;
4113 if !visible {
4114 return None;
4115 }
4116
4117 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4118 let target_position = content_origin
4119 + gpui::Point {
4120 x: cmp::max(
4121 px(0.),
4122 cursor_row_layout.x_for_index(cursor.column() as usize)
4123 - scroll_pixel_position.x,
4124 ),
4125 y: cmp::max(
4126 px(0.),
4127 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
4128 ),
4129 };
4130
4131 let viewport_bounds =
4132 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4133 right: -right_margin - MENU_GAP,
4134 ..Default::default()
4135 });
4136
4137 let min_height = height_above_menu + min_menu_height + height_below_menu;
4138 let max_height = height_above_menu + max_menu_height + height_below_menu;
4139 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4140 target_position,
4141 line_height,
4142 min_height,
4143 max_height,
4144 context_menu_placement,
4145 text_hitbox,
4146 viewport_bounds,
4147 window,
4148 cx,
4149 |height, max_width_for_stable_x, y_flipped, window, cx| {
4150 // First layout the menu to get its size - others can be at least this wide.
4151 let context_menu = if context_menu_visible {
4152 let menu_height = if y_flipped {
4153 height - height_below_menu
4154 } else {
4155 height - height_above_menu
4156 };
4157 let mut element = self
4158 .render_context_menu(line_height, menu_height, window, cx)
4159 .expect("Visible context menu should always render.");
4160 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4161 Some((CursorPopoverType::CodeContextMenu, element, size))
4162 } else {
4163 None
4164 };
4165 let min_width = context_menu
4166 .as_ref()
4167 .map_or(px(0.), |(_, _, size)| size.width);
4168 let max_width = max_width_for_stable_x.max(
4169 context_menu
4170 .as_ref()
4171 .map_or(px(0.), |(_, _, size)| size.width),
4172 );
4173
4174 let edit_prediction = if edit_prediction_popover_visible {
4175 self.editor.update(cx, move |editor, cx| {
4176 let accept_binding =
4177 editor.accept_edit_prediction_keybind(false, window, cx);
4178 let mut element = editor.render_edit_prediction_cursor_popover(
4179 min_width,
4180 max_width,
4181 cursor_point,
4182 style,
4183 accept_binding.keystroke(),
4184 window,
4185 cx,
4186 )?;
4187 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4188 Some((CursorPopoverType::EditPrediction, element, size))
4189 })
4190 } else {
4191 None
4192 };
4193 vec![edit_prediction, context_menu]
4194 .into_iter()
4195 .flatten()
4196 .collect::<Vec<_>>()
4197 },
4198 )?;
4199
4200 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4201 .iter()
4202 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4203 let last_ix = laid_out_popovers.len() - 1;
4204 let menu_is_last = menu_ix == last_ix;
4205 let first_popover_bounds = laid_out_popovers[0].1;
4206 let last_popover_bounds = laid_out_popovers[last_ix].1;
4207
4208 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4209 // right, and otherwise it goes below or to the right.
4210 let mut target_bounds = Bounds::from_corners(
4211 first_popover_bounds.origin,
4212 last_popover_bounds.bottom_right(),
4213 );
4214 target_bounds.size.width = menu_bounds.size.width;
4215
4216 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4217 // based on this is preferred for layout stability.
4218 let mut max_target_bounds = target_bounds;
4219 max_target_bounds.size.height = max_height;
4220 if y_flipped {
4221 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4222 }
4223
4224 // Add spacing around `target_bounds` and `max_target_bounds`.
4225 let mut extend_amount = Edges::all(MENU_GAP);
4226 if y_flipped {
4227 extend_amount.bottom = line_height;
4228 } else {
4229 extend_amount.top = line_height;
4230 }
4231 let target_bounds = target_bounds.extend(extend_amount);
4232 let max_target_bounds = max_target_bounds.extend(extend_amount);
4233
4234 let must_place_above_or_below =
4235 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4236 laid_out_popovers[menu_ix + 1..]
4237 .iter()
4238 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4239 } else {
4240 false
4241 };
4242
4243 let aside_bounds = self.layout_context_menu_aside(
4244 y_flipped,
4245 *menu_bounds,
4246 target_bounds,
4247 max_target_bounds,
4248 max_menu_height,
4249 must_place_above_or_below,
4250 text_hitbox,
4251 viewport_bounds,
4252 window,
4253 cx,
4254 );
4255
4256 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4257 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4258 Some(*bounds)
4259 } else {
4260 None
4261 }
4262 }) {
4263 let bounds = if let Some(aside_bounds) = aside_bounds {
4264 menu_bounds.union(&aside_bounds)
4265 } else {
4266 menu_bounds
4267 };
4268 return Some(ContextMenuLayout { y_flipped, bounds });
4269 }
4270
4271 None
4272 }
4273
4274 fn layout_gutter_menu(
4275 &self,
4276 line_height: Pixels,
4277 text_hitbox: &Hitbox,
4278 content_origin: gpui::Point<Pixels>,
4279 right_margin: Pixels,
4280 scroll_pixel_position: gpui::Point<Pixels>,
4281 gutter_overshoot: Pixels,
4282 window: &mut Window,
4283 cx: &mut App,
4284 ) {
4285 let editor = self.editor.read(cx);
4286 if !editor.context_menu_visible() {
4287 return;
4288 }
4289 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4290 editor.context_menu_origin()
4291 else {
4292 return;
4293 };
4294 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4295 // indicator than just a plain first column of the text field.
4296 let target_position = content_origin
4297 + gpui::Point {
4298 x: -gutter_overshoot,
4299 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
4300 };
4301
4302 let (min_height_in_lines, max_height_in_lines) = editor
4303 .context_menu_options
4304 .as_ref()
4305 .map_or((3, 12), |options| {
4306 (options.min_entries_visible, options.max_entries_visible)
4307 });
4308
4309 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4310 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4311 let viewport_bounds =
4312 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4313 right: -right_margin - MENU_GAP,
4314 ..Default::default()
4315 });
4316 self.layout_popovers_above_or_below_line(
4317 target_position,
4318 line_height,
4319 min_height,
4320 max_height,
4321 editor
4322 .context_menu_options
4323 .as_ref()
4324 .and_then(|options| options.placement.clone()),
4325 text_hitbox,
4326 viewport_bounds,
4327 window,
4328 cx,
4329 move |height, _max_width_for_stable_x, _, window, cx| {
4330 let mut element = self
4331 .render_context_menu(line_height, height, window, cx)
4332 .expect("Visible context menu should always render.");
4333 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4334 vec![(CursorPopoverType::CodeContextMenu, element, size)]
4335 },
4336 );
4337 }
4338
4339 fn layout_popovers_above_or_below_line(
4340 &self,
4341 target_position: gpui::Point<Pixels>,
4342 line_height: Pixels,
4343 min_height: Pixels,
4344 max_height: Pixels,
4345 placement: Option<ContextMenuPlacement>,
4346 text_hitbox: &Hitbox,
4347 viewport_bounds: Bounds<Pixels>,
4348 window: &mut Window,
4349 cx: &mut App,
4350 make_sized_popovers: impl FnOnce(
4351 Pixels,
4352 Pixels,
4353 bool,
4354 &mut Window,
4355 &mut App,
4356 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
4357 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
4358 let text_style = TextStyleRefinement {
4359 line_height: Some(DefiniteLength::Fraction(
4360 BufferLineHeight::Comfortable.value(),
4361 )),
4362 ..Default::default()
4363 };
4364 window.with_text_style(Some(text_style), |window| {
4365 // If the max height won't fit below and there is more space above, put it above the line.
4366 let bottom_y_when_flipped = target_position.y - line_height;
4367 let available_above = bottom_y_when_flipped - text_hitbox.top();
4368 let available_below = text_hitbox.bottom() - target_position.y;
4369 let y_overflows_below = max_height > available_below;
4370 let mut y_flipped = match placement {
4371 Some(ContextMenuPlacement::Above) => true,
4372 Some(ContextMenuPlacement::Below) => false,
4373 None => y_overflows_below && available_above > available_below,
4374 };
4375 let mut height = cmp::min(
4376 max_height,
4377 if y_flipped {
4378 available_above
4379 } else {
4380 available_below
4381 },
4382 );
4383
4384 // If the min height doesn't fit within text bounds, instead fit within the window.
4385 if height < min_height {
4386 let available_above = bottom_y_when_flipped;
4387 let available_below = viewport_bounds.bottom() - target_position.y;
4388 let (y_flipped_override, height_override) = match placement {
4389 Some(ContextMenuPlacement::Above) => {
4390 (true, cmp::min(available_above, min_height))
4391 }
4392 Some(ContextMenuPlacement::Below) => {
4393 (false, cmp::min(available_below, min_height))
4394 }
4395 None => {
4396 if available_below > min_height {
4397 (false, min_height)
4398 } else if available_above > min_height {
4399 (true, min_height)
4400 } else if available_above > available_below {
4401 (true, available_above)
4402 } else {
4403 (false, available_below)
4404 }
4405 }
4406 };
4407 y_flipped = y_flipped_override;
4408 height = height_override;
4409 }
4410
4411 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
4412
4413 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
4414 // for very narrow windows.
4415 let popovers =
4416 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
4417 if popovers.is_empty() {
4418 return None;
4419 }
4420
4421 let max_width = popovers
4422 .iter()
4423 .map(|(_, _, size)| size.width)
4424 .max()
4425 .unwrap_or_default();
4426
4427 let mut current_position = gpui::Point {
4428 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
4429 // overflow. Include space for the scrollbar.
4430 x: target_position
4431 .x
4432 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
4433 y: if y_flipped {
4434 bottom_y_when_flipped
4435 } else {
4436 target_position.y
4437 },
4438 };
4439
4440 let mut laid_out_popovers = popovers
4441 .into_iter()
4442 .map(|(popover_type, element, size)| {
4443 if y_flipped {
4444 current_position.y -= size.height;
4445 }
4446 let position = current_position;
4447 window.defer_draw(element, current_position, 1);
4448 if !y_flipped {
4449 current_position.y += size.height + MENU_GAP;
4450 } else {
4451 current_position.y -= MENU_GAP;
4452 }
4453 (popover_type, Bounds::new(position, size))
4454 })
4455 .collect::<Vec<_>>();
4456
4457 if y_flipped {
4458 laid_out_popovers.reverse();
4459 }
4460
4461 Some((laid_out_popovers, y_flipped))
4462 })
4463 }
4464
4465 fn layout_context_menu_aside(
4466 &self,
4467 y_flipped: bool,
4468 menu_bounds: Bounds<Pixels>,
4469 target_bounds: Bounds<Pixels>,
4470 max_target_bounds: Bounds<Pixels>,
4471 max_height: Pixels,
4472 must_place_above_or_below: bool,
4473 text_hitbox: &Hitbox,
4474 viewport_bounds: Bounds<Pixels>,
4475 window: &mut Window,
4476 cx: &mut App,
4477 ) -> Option<Bounds<Pixels>> {
4478 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
4479 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
4480 && !must_place_above_or_below
4481 {
4482 let max_width = cmp::min(
4483 available_within_viewport.right - px(1.),
4484 MENU_ASIDE_MAX_WIDTH,
4485 );
4486 let mut aside = self.render_context_menu_aside(
4487 size(max_width, max_height - POPOVER_Y_PADDING),
4488 window,
4489 cx,
4490 )?;
4491 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4492 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
4493 Some((aside, right_position, size))
4494 } else {
4495 let max_size = size(
4496 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
4497 // won't be needed here.
4498 cmp::min(
4499 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
4500 viewport_bounds.right(),
4501 ),
4502 cmp::min(
4503 max_height,
4504 cmp::max(
4505 available_within_viewport.top,
4506 available_within_viewport.bottom,
4507 ),
4508 ) - POPOVER_Y_PADDING,
4509 );
4510 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
4511 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4512
4513 let top_position = point(
4514 menu_bounds.origin.x,
4515 target_bounds.top() - actual_size.height,
4516 );
4517 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
4518
4519 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
4520 // Prefer to fit on the same side of the line as the menu, then on the other side of
4521 // the line.
4522 if !y_flipped && wanted.height < available.bottom {
4523 Some(bottom_position)
4524 } else if !y_flipped && wanted.height < available.top {
4525 Some(top_position)
4526 } else if y_flipped && wanted.height < available.top {
4527 Some(top_position)
4528 } else if y_flipped && wanted.height < available.bottom {
4529 Some(bottom_position)
4530 } else {
4531 None
4532 }
4533 };
4534
4535 // Prefer choosing a direction using max sizes rather than actual size for stability.
4536 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
4537 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
4538 let aside_position = fit_within(available_within_text, wanted)
4539 // Fallback: fit max size in window.
4540 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
4541 // Fallback: fit actual size in window.
4542 .or_else(|| fit_within(available_within_viewport, actual_size));
4543
4544 aside_position.map(|position| (aside, position, actual_size))
4545 };
4546
4547 // Skip drawing if it doesn't fit anywhere.
4548 if let Some((aside, position, size)) = positioned_aside {
4549 let aside_bounds = Bounds::new(position, size);
4550 window.defer_draw(aside, position, 2);
4551 return Some(aside_bounds);
4552 }
4553
4554 None
4555 }
4556
4557 fn render_context_menu(
4558 &self,
4559 line_height: Pixels,
4560 height: Pixels,
4561 window: &mut Window,
4562 cx: &mut App,
4563 ) -> Option<AnyElement> {
4564 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
4565 self.editor.update(cx, |editor, cx| {
4566 editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
4567 })
4568 }
4569
4570 fn render_context_menu_aside(
4571 &self,
4572 max_size: Size<Pixels>,
4573 window: &mut Window,
4574 cx: &mut App,
4575 ) -> Option<AnyElement> {
4576 if max_size.width < px(100.) || max_size.height < px(12.) {
4577 None
4578 } else {
4579 self.editor.update(cx, |editor, cx| {
4580 editor.render_context_menu_aside(max_size, window, cx)
4581 })
4582 }
4583 }
4584
4585 fn layout_mouse_context_menu(
4586 &self,
4587 editor_snapshot: &EditorSnapshot,
4588 visible_range: Range<DisplayRow>,
4589 content_origin: gpui::Point<Pixels>,
4590 window: &mut Window,
4591 cx: &mut App,
4592 ) -> Option<AnyElement> {
4593 let position = self.editor.update(cx, |editor, _cx| {
4594 let visible_start_point = editor.display_to_pixel_point(
4595 DisplayPoint::new(visible_range.start, 0),
4596 editor_snapshot,
4597 window,
4598 )?;
4599 let visible_end_point = editor.display_to_pixel_point(
4600 DisplayPoint::new(visible_range.end, 0),
4601 editor_snapshot,
4602 window,
4603 )?;
4604
4605 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4606 let (source_display_point, position) = match mouse_context_menu.position {
4607 MenuPosition::PinnedToScreen(point) => (None, point),
4608 MenuPosition::PinnedToEditor { source, offset } => {
4609 let source_display_point = source.to_display_point(editor_snapshot);
4610 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
4611 let position = content_origin + source_point + offset;
4612 (Some(source_display_point), position)
4613 }
4614 };
4615
4616 let source_included = source_display_point.map_or(true, |source_display_point| {
4617 visible_range
4618 .to_inclusive()
4619 .contains(&source_display_point.row())
4620 });
4621 let position_included =
4622 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
4623 if !source_included && !position_included {
4624 None
4625 } else {
4626 Some(position)
4627 }
4628 })?;
4629
4630 let text_style = TextStyleRefinement {
4631 line_height: Some(DefiniteLength::Fraction(
4632 BufferLineHeight::Comfortable.value(),
4633 )),
4634 ..Default::default()
4635 };
4636 window.with_text_style(Some(text_style), |window| {
4637 let mut element = self.editor.read_with(cx, |editor, _| {
4638 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4639 let context_menu = mouse_context_menu.context_menu.clone();
4640
4641 Some(
4642 deferred(
4643 anchored()
4644 .position(position)
4645 .child(context_menu)
4646 .anchor(Corner::TopLeft)
4647 .snap_to_window_with_margin(px(8.)),
4648 )
4649 .with_priority(1)
4650 .into_any(),
4651 )
4652 })?;
4653
4654 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
4655 Some(element)
4656 })
4657 }
4658
4659 fn layout_hover_popovers(
4660 &self,
4661 snapshot: &EditorSnapshot,
4662 hitbox: &Hitbox,
4663 visible_display_row_range: Range<DisplayRow>,
4664 content_origin: gpui::Point<Pixels>,
4665 scroll_pixel_position: gpui::Point<Pixels>,
4666 line_layouts: &[LineWithInvisibles],
4667 line_height: Pixels,
4668 em_width: Pixels,
4669 context_menu_layout: Option<ContextMenuLayout>,
4670 window: &mut Window,
4671 cx: &mut App,
4672 ) {
4673 struct MeasuredHoverPopover {
4674 element: AnyElement,
4675 size: Size<Pixels>,
4676 horizontal_offset: Pixels,
4677 }
4678
4679 let max_size = size(
4680 (120. * em_width) // Default size
4681 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4682 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4683 (16. * line_height) // Default size
4684 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4685 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4686 );
4687
4688 let hover_popovers = self.editor.update(cx, |editor, cx| {
4689 editor.hover_state.render(
4690 snapshot,
4691 visible_display_row_range.clone(),
4692 max_size,
4693 window,
4694 cx,
4695 )
4696 });
4697 let Some((position, hover_popovers)) = hover_popovers else {
4698 return;
4699 };
4700
4701 // This is safe because we check on layout whether the required row is available
4702 let hovered_row_layout =
4703 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
4704
4705 // Compute Hovered Point
4706 let x =
4707 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
4708 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
4709 let hovered_point = content_origin + point(x, y);
4710
4711 let mut overall_height = Pixels::ZERO;
4712 let mut measured_hover_popovers = Vec::new();
4713 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
4714 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
4715 let horizontal_offset =
4716 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
4717 .min(Pixels::ZERO);
4718 match position {
4719 itertools::Position::Middle | itertools::Position::Last => {
4720 overall_height += HOVER_POPOVER_GAP
4721 }
4722 _ => {}
4723 }
4724 overall_height += size.height;
4725 measured_hover_popovers.push(MeasuredHoverPopover {
4726 element: hover_popover,
4727 size,
4728 horizontal_offset,
4729 });
4730 }
4731
4732 fn draw_occluder(
4733 width: Pixels,
4734 origin: gpui::Point<Pixels>,
4735 window: &mut Window,
4736 cx: &mut App,
4737 ) {
4738 let mut occlusion = div()
4739 .size_full()
4740 .occlude()
4741 .on_mouse_move(|_, _, cx| cx.stop_propagation())
4742 .into_any_element();
4743 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4744 window.defer_draw(occlusion, origin, 2);
4745 }
4746
4747 fn place_popovers_above(
4748 hovered_point: gpui::Point<Pixels>,
4749 measured_hover_popovers: Vec<MeasuredHoverPopover>,
4750 window: &mut Window,
4751 cx: &mut App,
4752 ) {
4753 let mut current_y = hovered_point.y;
4754 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4755 let size = popover.size;
4756 let popover_origin = point(
4757 hovered_point.x + popover.horizontal_offset,
4758 current_y - size.height,
4759 );
4760
4761 window.defer_draw(popover.element, popover_origin, 2);
4762 if position != itertools::Position::Last {
4763 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4764 draw_occluder(size.width, origin, window, cx);
4765 }
4766
4767 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4768 }
4769 }
4770
4771 fn place_popovers_below(
4772 hovered_point: gpui::Point<Pixels>,
4773 measured_hover_popovers: Vec<MeasuredHoverPopover>,
4774 line_height: Pixels,
4775 window: &mut Window,
4776 cx: &mut App,
4777 ) {
4778 let mut current_y = hovered_point.y + line_height;
4779 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4780 let size = popover.size;
4781 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4782
4783 window.defer_draw(popover.element, popover_origin, 2);
4784 if position != itertools::Position::Last {
4785 let origin = point(popover_origin.x, popover_origin.y + size.height);
4786 draw_occluder(size.width, origin, window, cx);
4787 }
4788
4789 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4790 }
4791 }
4792
4793 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
4794 context_menu_layout
4795 .as_ref()
4796 .map_or(false, |menu| bounds.intersects(&menu.bounds))
4797 };
4798
4799 let can_place_above = {
4800 let mut bounds_above = Vec::new();
4801 let mut current_y = hovered_point.y;
4802 for popover in &measured_hover_popovers {
4803 let size = popover.size;
4804 let popover_origin = point(
4805 hovered_point.x + popover.horizontal_offset,
4806 current_y - size.height,
4807 );
4808 bounds_above.push(Bounds::new(popover_origin, size));
4809 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4810 }
4811 bounds_above
4812 .iter()
4813 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
4814 };
4815
4816 let can_place_below = || {
4817 let mut bounds_below = Vec::new();
4818 let mut current_y = hovered_point.y + line_height;
4819 for popover in &measured_hover_popovers {
4820 let size = popover.size;
4821 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4822 bounds_below.push(Bounds::new(popover_origin, size));
4823 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4824 }
4825 bounds_below
4826 .iter()
4827 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
4828 };
4829
4830 if can_place_above {
4831 // try placing above hovered point
4832 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
4833 } else if can_place_below() {
4834 // try placing below hovered point
4835 place_popovers_below(
4836 hovered_point,
4837 measured_hover_popovers,
4838 line_height,
4839 window,
4840 cx,
4841 );
4842 } else {
4843 // try to place popovers around the context menu
4844 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
4845 let total_width = measured_hover_popovers
4846 .iter()
4847 .map(|p| p.size.width)
4848 .max()
4849 .unwrap_or(Pixels::ZERO);
4850 let y_for_horizontal_positioning = if menu.y_flipped {
4851 menu.bounds.bottom() - overall_height
4852 } else {
4853 menu.bounds.top()
4854 };
4855 let possible_origins = vec![
4856 // left of context menu
4857 point(
4858 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
4859 y_for_horizontal_positioning,
4860 ),
4861 // right of context menu
4862 point(
4863 menu.bounds.right() + HOVER_POPOVER_GAP,
4864 y_for_horizontal_positioning,
4865 ),
4866 // top of context menu
4867 point(
4868 menu.bounds.left(),
4869 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
4870 ),
4871 // bottom of context menu
4872 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
4873 ];
4874 possible_origins.into_iter().find(|&origin| {
4875 Bounds::new(origin, size(total_width, overall_height))
4876 .is_contained_within(hitbox)
4877 })
4878 });
4879 if let Some(origin) = origin_surrounding_menu {
4880 let mut current_y = origin.y;
4881 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4882 let size = popover.size;
4883 let popover_origin = point(origin.x, current_y);
4884
4885 window.defer_draw(popover.element, popover_origin, 2);
4886 if position != itertools::Position::Last {
4887 let origin = point(popover_origin.x, popover_origin.y + size.height);
4888 draw_occluder(size.width, origin, window, cx);
4889 }
4890
4891 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4892 }
4893 } else {
4894 // fallback to existing above/below cursor logic
4895 // this might overlap menu or overflow in rare case
4896 if can_place_above {
4897 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
4898 } else {
4899 place_popovers_below(
4900 hovered_point,
4901 measured_hover_popovers,
4902 line_height,
4903 window,
4904 cx,
4905 );
4906 }
4907 }
4908 }
4909 }
4910
4911 fn layout_diff_hunk_controls(
4912 &self,
4913 row_range: Range<DisplayRow>,
4914 row_infos: &[RowInfo],
4915 text_hitbox: &Hitbox,
4916 newest_cursor_position: Option<DisplayPoint>,
4917 line_height: Pixels,
4918 right_margin: Pixels,
4919 scroll_pixel_position: gpui::Point<Pixels>,
4920 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4921 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
4922 editor: Entity<Editor>,
4923 window: &mut Window,
4924 cx: &mut App,
4925 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
4926 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
4927 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
4928
4929 let mut controls = vec![];
4930 let mut control_bounds = vec![];
4931
4932 let active_positions = [
4933 hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
4934 newest_cursor_position,
4935 ];
4936
4937 for (hunk, _) in display_hunks {
4938 if let DisplayDiffHunk::Unfolded {
4939 display_row_range,
4940 multi_buffer_range,
4941 status,
4942 is_created_file,
4943 ..
4944 } = &hunk
4945 {
4946 if display_row_range.start < row_range.start
4947 || display_row_range.start >= row_range.end
4948 {
4949 continue;
4950 }
4951 if highlighted_rows
4952 .get(&display_row_range.start)
4953 .and_then(|highlight| highlight.type_id)
4954 .is_some_and(|type_id| {
4955 [
4956 TypeId::of::<ConflictsOuter>(),
4957 TypeId::of::<ConflictsOursMarker>(),
4958 TypeId::of::<ConflictsOurs>(),
4959 TypeId::of::<ConflictsTheirs>(),
4960 TypeId::of::<ConflictsTheirsMarker>(),
4961 ]
4962 .contains(&type_id)
4963 })
4964 {
4965 continue;
4966 }
4967 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4968 if row_infos[row_ix].diff_status.is_none() {
4969 continue;
4970 }
4971 if row_infos[row_ix]
4972 .diff_status
4973 .is_some_and(|status| status.is_added())
4974 && !status.is_added()
4975 {
4976 continue;
4977 }
4978
4979 if active_positions
4980 .iter()
4981 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4982 {
4983 let y = display_row_range.start.as_f32() * line_height
4984 + text_hitbox.bounds.top()
4985 - scroll_pixel_position.y;
4986
4987 let mut element = render_diff_hunk_controls(
4988 display_row_range.start.0,
4989 status,
4990 multi_buffer_range.clone(),
4991 *is_created_file,
4992 line_height,
4993 &editor,
4994 window,
4995 cx,
4996 );
4997 let size =
4998 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
4999
5000 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5001
5002 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5003 control_bounds.push((display_row_range.start, bounds));
5004
5005 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5006 element.prepaint(window, cx)
5007 });
5008 controls.push(element);
5009 }
5010 }
5011 }
5012
5013 (controls, control_bounds)
5014 }
5015
5016 fn layout_signature_help(
5017 &self,
5018 hitbox: &Hitbox,
5019 content_origin: gpui::Point<Pixels>,
5020 scroll_pixel_position: gpui::Point<Pixels>,
5021 newest_selection_head: Option<DisplayPoint>,
5022 start_row: DisplayRow,
5023 line_layouts: &[LineWithInvisibles],
5024 line_height: Pixels,
5025 em_width: Pixels,
5026 context_menu_layout: Option<ContextMenuLayout>,
5027 window: &mut Window,
5028 cx: &mut App,
5029 ) {
5030 if !self.editor.focus_handle(cx).is_focused(window) {
5031 return;
5032 }
5033 let Some(newest_selection_head) = newest_selection_head else {
5034 return;
5035 };
5036
5037 let max_size = size(
5038 (120. * em_width) // Default size
5039 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5040 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5041 (16. * line_height) // Default size
5042 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5043 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5044 );
5045
5046 let maybe_element = self.editor.update(cx, |editor, cx| {
5047 if let Some(popover) = editor.signature_help_state.popover_mut() {
5048 let element = popover.render(max_size, window, cx);
5049 Some(element)
5050 } else {
5051 None
5052 }
5053 });
5054 let Some(mut element) = maybe_element else {
5055 return;
5056 };
5057
5058 let selection_row = newest_selection_head.row();
5059 let Some(cursor_row_layout) = (selection_row >= start_row)
5060 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5061 .flatten()
5062 else {
5063 return;
5064 };
5065
5066 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5067 - scroll_pixel_position.x;
5068 let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
5069 let target_point = content_origin + point(target_x, target_y);
5070
5071 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5072
5073 let (popover_bounds_above, popover_bounds_below) = {
5074 let horizontal_offset = (hitbox.top_right().x
5075 - POPOVER_RIGHT_OFFSET
5076 - (target_point.x + actual_size.width))
5077 .min(Pixels::ZERO);
5078 let initial_x = target_point.x + horizontal_offset;
5079 (
5080 Bounds::new(
5081 point(initial_x, target_point.y - actual_size.height),
5082 actual_size,
5083 ),
5084 Bounds::new(
5085 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5086 actual_size,
5087 ),
5088 )
5089 };
5090
5091 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5092 context_menu_layout
5093 .as_ref()
5094 .map_or(false, |menu| bounds.intersects(&menu.bounds))
5095 };
5096
5097 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5098 && !intersects_menu(popover_bounds_above)
5099 {
5100 // try placing above cursor
5101 popover_bounds_above.origin
5102 } else if popover_bounds_below.is_contained_within(hitbox)
5103 && !intersects_menu(popover_bounds_below)
5104 {
5105 // try placing below cursor
5106 popover_bounds_below.origin
5107 } else {
5108 // try surrounding context menu if exists
5109 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5110 let y_for_horizontal_positioning = if menu.y_flipped {
5111 menu.bounds.bottom() - actual_size.height
5112 } else {
5113 menu.bounds.top()
5114 };
5115 let possible_origins = vec![
5116 // left of context menu
5117 point(
5118 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5119 y_for_horizontal_positioning,
5120 ),
5121 // right of context menu
5122 point(
5123 menu.bounds.right() + HOVER_POPOVER_GAP,
5124 y_for_horizontal_positioning,
5125 ),
5126 // top of context menu
5127 point(
5128 menu.bounds.left(),
5129 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5130 ),
5131 // bottom of context menu
5132 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5133 ];
5134 possible_origins
5135 .into_iter()
5136 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5137 });
5138 origin_surrounding_menu.unwrap_or_else(|| {
5139 // fallback to existing above/below cursor logic
5140 // this might overlap menu or overflow in rare case
5141 if popover_bounds_above.is_contained_within(hitbox) {
5142 popover_bounds_above.origin
5143 } else {
5144 popover_bounds_below.origin
5145 }
5146 })
5147 };
5148
5149 window.defer_draw(element, final_origin, 2);
5150 }
5151
5152 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5153 window.paint_layer(layout.hitbox.bounds, |window| {
5154 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5155 let gutter_bg = cx.theme().colors().editor_gutter_background;
5156 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5157 window.paint_quad(fill(
5158 layout.position_map.text_hitbox.bounds,
5159 self.style.background,
5160 ));
5161
5162 if matches!(
5163 layout.mode,
5164 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5165 ) {
5166 let show_active_line_background = match layout.mode {
5167 EditorMode::Full {
5168 show_active_line_background,
5169 ..
5170 } => show_active_line_background,
5171 EditorMode::Minimap { .. } => true,
5172 _ => false,
5173 };
5174 let mut active_rows = layout.active_rows.iter().peekable();
5175 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5176 let mut end_row = start_row.0;
5177 while active_rows
5178 .peek()
5179 .map_or(false, |(active_row, has_selection)| {
5180 active_row.0 == end_row + 1
5181 && has_selection.selection == contains_non_empty_selection.selection
5182 })
5183 {
5184 active_rows.next().unwrap();
5185 end_row += 1;
5186 }
5187
5188 if show_active_line_background && !contains_non_empty_selection.selection {
5189 let highlight_h_range =
5190 match layout.position_map.snapshot.current_line_highlight {
5191 CurrentLineHighlight::Gutter => Some(Range {
5192 start: layout.hitbox.left(),
5193 end: layout.gutter_hitbox.right(),
5194 }),
5195 CurrentLineHighlight::Line => Some(Range {
5196 start: layout.position_map.text_hitbox.bounds.left(),
5197 end: layout.position_map.text_hitbox.bounds.right(),
5198 }),
5199 CurrentLineHighlight::All => Some(Range {
5200 start: layout.hitbox.left(),
5201 end: layout.hitbox.right(),
5202 }),
5203 CurrentLineHighlight::None => None,
5204 };
5205 if let Some(range) = highlight_h_range {
5206 let active_line_bg = cx.theme().colors().editor_active_line_background;
5207 let bounds = Bounds {
5208 origin: point(
5209 range.start,
5210 layout.hitbox.origin.y
5211 + (start_row.as_f32() - scroll_top)
5212 * layout.position_map.line_height,
5213 ),
5214 size: size(
5215 range.end - range.start,
5216 layout.position_map.line_height
5217 * (end_row - start_row.0 + 1) as f32,
5218 ),
5219 };
5220 window.paint_quad(fill(bounds, active_line_bg));
5221 }
5222 }
5223 }
5224
5225 let mut paint_highlight = |highlight_row_start: DisplayRow,
5226 highlight_row_end: DisplayRow,
5227 highlight: crate::LineHighlight,
5228 edges| {
5229 let mut origin_x = layout.hitbox.left();
5230 let mut width = layout.hitbox.size.width;
5231 if !highlight.include_gutter {
5232 origin_x += layout.gutter_hitbox.size.width;
5233 width -= layout.gutter_hitbox.size.width;
5234 }
5235
5236 let origin = point(
5237 origin_x,
5238 layout.hitbox.origin.y
5239 + (highlight_row_start.as_f32() - scroll_top)
5240 * layout.position_map.line_height,
5241 );
5242 let size = size(
5243 width,
5244 layout.position_map.line_height
5245 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5246 );
5247 let mut quad = fill(Bounds { origin, size }, highlight.background);
5248 if let Some(border_color) = highlight.border {
5249 quad.border_color = border_color;
5250 quad.border_widths = edges
5251 }
5252 window.paint_quad(quad);
5253 };
5254
5255 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5256 None;
5257 for (&new_row, &new_background) in &layout.highlighted_rows {
5258 match &mut current_paint {
5259 &mut Some((current_background, ref mut current_range, mut edges)) => {
5260 let new_range_started = current_background != new_background
5261 || current_range.end.next_row() != new_row;
5262 if new_range_started {
5263 if current_range.end.next_row() == new_row {
5264 edges.bottom = px(0.);
5265 };
5266 paint_highlight(
5267 current_range.start,
5268 current_range.end,
5269 current_background,
5270 edges,
5271 );
5272 let edges = Edges {
5273 top: if current_range.end.next_row() != new_row {
5274 px(1.)
5275 } else {
5276 px(0.)
5277 },
5278 bottom: px(1.),
5279 ..Default::default()
5280 };
5281 current_paint = Some((new_background, new_row..new_row, edges));
5282 continue;
5283 } else {
5284 current_range.end = current_range.end.next_row();
5285 }
5286 }
5287 None => {
5288 let edges = Edges {
5289 top: px(1.),
5290 bottom: px(1.),
5291 ..Default::default()
5292 };
5293 current_paint = Some((new_background, new_row..new_row, edges))
5294 }
5295 };
5296 }
5297 if let Some((color, range, edges)) = current_paint {
5298 paint_highlight(range.start, range.end, color, edges);
5299 }
5300
5301 for (guide_x, active) in layout.wrap_guides.iter() {
5302 let color = if *active {
5303 cx.theme().colors().editor_active_wrap_guide
5304 } else {
5305 cx.theme().colors().editor_wrap_guide
5306 };
5307 window.paint_quad(fill(
5308 Bounds {
5309 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5310 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5311 },
5312 color,
5313 ));
5314 }
5315 }
5316 })
5317 }
5318
5319 fn paint_indent_guides(
5320 &mut self,
5321 layout: &mut EditorLayout,
5322 window: &mut Window,
5323 cx: &mut App,
5324 ) {
5325 let Some(indent_guides) = &layout.indent_guides else {
5326 return;
5327 };
5328
5329 let faded_color = |color: Hsla, alpha: f32| {
5330 let mut faded = color;
5331 faded.a = alpha;
5332 faded
5333 };
5334
5335 for indent_guide in indent_guides {
5336 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
5337 let settings = indent_guide.settings;
5338
5339 // TODO fixed for now, expose them through themes later
5340 const INDENT_AWARE_ALPHA: f32 = 0.2;
5341 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
5342 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
5343 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
5344
5345 let line_color = match (settings.coloring, indent_guide.active) {
5346 (IndentGuideColoring::Disabled, _) => None,
5347 (IndentGuideColoring::Fixed, false) => {
5348 Some(cx.theme().colors().editor_indent_guide)
5349 }
5350 (IndentGuideColoring::Fixed, true) => {
5351 Some(cx.theme().colors().editor_indent_guide_active)
5352 }
5353 (IndentGuideColoring::IndentAware, false) => {
5354 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
5355 }
5356 (IndentGuideColoring::IndentAware, true) => {
5357 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
5358 }
5359 };
5360
5361 let background_color = match (settings.background_coloring, indent_guide.active) {
5362 (IndentGuideBackgroundColoring::Disabled, _) => None,
5363 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
5364 indent_accent_colors,
5365 INDENT_AWARE_BACKGROUND_ALPHA,
5366 )),
5367 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
5368 indent_accent_colors,
5369 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
5370 )),
5371 };
5372
5373 let requested_line_width = if indent_guide.active {
5374 settings.active_line_width
5375 } else {
5376 settings.line_width
5377 }
5378 .clamp(1, 10);
5379 let mut line_indicator_width = 0.;
5380 if let Some(color) = line_color {
5381 window.paint_quad(fill(
5382 Bounds {
5383 origin: indent_guide.origin,
5384 size: size(px(requested_line_width as f32), indent_guide.length),
5385 },
5386 color,
5387 ));
5388 line_indicator_width = requested_line_width as f32;
5389 }
5390
5391 if let Some(color) = background_color {
5392 let width = indent_guide.single_indent_width - px(line_indicator_width);
5393 window.paint_quad(fill(
5394 Bounds {
5395 origin: point(
5396 indent_guide.origin.x + px(line_indicator_width),
5397 indent_guide.origin.y,
5398 ),
5399 size: size(width, indent_guide.length),
5400 },
5401 color,
5402 ));
5403 }
5404 }
5405 }
5406
5407 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5408 let is_singleton = self.editor.read(cx).is_singleton(cx);
5409
5410 let line_height = layout.position_map.line_height;
5411 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
5412
5413 for LineNumberLayout {
5414 shaped_line,
5415 hitbox,
5416 } in layout.line_numbers.values()
5417 {
5418 let Some(hitbox) = hitbox else {
5419 continue;
5420 };
5421
5422 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
5423 let color = cx.theme().colors().editor_hover_line_number;
5424
5425 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
5426 line.paint(hitbox.origin, line_height, window, cx).log_err()
5427 } else {
5428 shaped_line
5429 .paint(hitbox.origin, line_height, window, cx)
5430 .log_err()
5431 }) else {
5432 continue;
5433 };
5434
5435 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
5436 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
5437 if is_singleton {
5438 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
5439 } else {
5440 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
5441 }
5442 }
5443 }
5444
5445 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5446 if layout.display_hunks.is_empty() {
5447 return;
5448 }
5449
5450 let line_height = layout.position_map.line_height;
5451 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5452 for (hunk, hitbox) in &layout.display_hunks {
5453 let hunk_to_paint = match hunk {
5454 DisplayDiffHunk::Folded { .. } => {
5455 let hunk_bounds = Self::diff_hunk_bounds(
5456 &layout.position_map.snapshot,
5457 line_height,
5458 layout.gutter_hitbox.bounds,
5459 &hunk,
5460 );
5461 Some((
5462 hunk_bounds,
5463 cx.theme().colors().version_control_modified,
5464 Corners::all(px(0.)),
5465 DiffHunkStatus::modified_none(),
5466 ))
5467 }
5468 DisplayDiffHunk::Unfolded {
5469 status,
5470 display_row_range,
5471 ..
5472 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
5473 DiffHunkStatusKind::Added => (
5474 hunk_hitbox.bounds,
5475 cx.theme().colors().version_control_added,
5476 Corners::all(px(0.)),
5477 *status,
5478 ),
5479 DiffHunkStatusKind::Modified => (
5480 hunk_hitbox.bounds,
5481 cx.theme().colors().version_control_modified,
5482 Corners::all(px(0.)),
5483 *status,
5484 ),
5485 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
5486 hunk_hitbox.bounds,
5487 cx.theme().colors().version_control_deleted,
5488 Corners::all(px(0.)),
5489 *status,
5490 ),
5491 DiffHunkStatusKind::Deleted => (
5492 Bounds::new(
5493 point(
5494 hunk_hitbox.origin.x - hunk_hitbox.size.width,
5495 hunk_hitbox.origin.y,
5496 ),
5497 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
5498 ),
5499 cx.theme().colors().version_control_deleted,
5500 Corners::all(1. * line_height),
5501 *status,
5502 ),
5503 }),
5504 };
5505
5506 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
5507 // Flatten the background color with the editor color to prevent
5508 // elements below transparent hunks from showing through
5509 let flattened_background_color = cx
5510 .theme()
5511 .colors()
5512 .editor_background
5513 .blend(background_color);
5514
5515 if !Self::diff_hunk_hollow(status, cx) {
5516 window.paint_quad(quad(
5517 hunk_bounds,
5518 corner_radii,
5519 flattened_background_color,
5520 Edges::default(),
5521 transparent_black(),
5522 BorderStyle::default(),
5523 ));
5524 } else {
5525 let flattened_unstaged_background_color = cx
5526 .theme()
5527 .colors()
5528 .editor_background
5529 .blend(background_color.opacity(0.3));
5530
5531 window.paint_quad(quad(
5532 hunk_bounds,
5533 corner_radii,
5534 flattened_unstaged_background_color,
5535 Edges::all(Pixels(1.0)),
5536 flattened_background_color,
5537 BorderStyle::Solid,
5538 ));
5539 }
5540 }
5541 }
5542 });
5543 }
5544
5545 fn gutter_strip_width(line_height: Pixels) -> Pixels {
5546 (0.275 * line_height).floor()
5547 }
5548
5549 fn diff_hunk_bounds(
5550 snapshot: &EditorSnapshot,
5551 line_height: Pixels,
5552 gutter_bounds: Bounds<Pixels>,
5553 hunk: &DisplayDiffHunk,
5554 ) -> Bounds<Pixels> {
5555 let scroll_position = snapshot.scroll_position();
5556 let scroll_top = scroll_position.y * line_height;
5557 let gutter_strip_width = Self::gutter_strip_width(line_height);
5558
5559 match hunk {
5560 DisplayDiffHunk::Folded { display_row, .. } => {
5561 let start_y = display_row.as_f32() * line_height - scroll_top;
5562 let end_y = start_y + line_height;
5563 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5564 let highlight_size = size(gutter_strip_width, end_y - start_y);
5565 Bounds::new(highlight_origin, highlight_size)
5566 }
5567 DisplayDiffHunk::Unfolded {
5568 display_row_range,
5569 status,
5570 ..
5571 } => {
5572 if status.is_deleted() && display_row_range.is_empty() {
5573 let row = display_row_range.start;
5574
5575 let offset = line_height / 2.;
5576 let start_y = row.as_f32() * line_height - offset - scroll_top;
5577 let end_y = start_y + line_height;
5578
5579 let width = (0.35 * line_height).floor();
5580 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5581 let highlight_size = size(width, end_y - start_y);
5582 Bounds::new(highlight_origin, highlight_size)
5583 } else {
5584 let start_row = display_row_range.start;
5585 let end_row = display_row_range.end;
5586 // If we're in a multibuffer, row range span might include an
5587 // excerpt header, so if we were to draw the marker straight away,
5588 // the hunk might include the rows of that header.
5589 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
5590 // Instead, we simply check whether the range we're dealing with includes
5591 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
5592 let end_row_in_current_excerpt = snapshot
5593 .blocks_in_range(start_row..end_row)
5594 .find_map(|(start_row, block)| {
5595 if matches!(block, Block::ExcerptBoundary { .. }) {
5596 Some(start_row)
5597 } else {
5598 None
5599 }
5600 })
5601 .unwrap_or(end_row);
5602
5603 let start_y = start_row.as_f32() * line_height - scroll_top;
5604 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
5605
5606 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5607 let highlight_size = size(gutter_strip_width, end_y - start_y);
5608 Bounds::new(highlight_origin, highlight_size)
5609 }
5610 }
5611 }
5612 }
5613
5614 fn paint_gutter_indicators(
5615 &self,
5616 layout: &mut EditorLayout,
5617 window: &mut Window,
5618 cx: &mut App,
5619 ) {
5620 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5621 window.with_element_namespace("crease_toggles", |window| {
5622 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
5623 crease_toggle.paint(window, cx);
5624 }
5625 });
5626
5627 window.with_element_namespace("expand_toggles", |window| {
5628 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
5629 expand_toggle.paint(window, cx);
5630 }
5631 });
5632
5633 for breakpoint in layout.breakpoints.iter_mut() {
5634 breakpoint.paint(window, cx);
5635 }
5636
5637 for test_indicator in layout.test_indicators.iter_mut() {
5638 test_indicator.paint(window, cx);
5639 }
5640 });
5641 }
5642
5643 fn paint_gutter_highlights(
5644 &self,
5645 layout: &mut EditorLayout,
5646 window: &mut Window,
5647 cx: &mut App,
5648 ) {
5649 for (_, hunk_hitbox) in &layout.display_hunks {
5650 if let Some(hunk_hitbox) = hunk_hitbox {
5651 if !self
5652 .editor
5653 .read(cx)
5654 .buffer()
5655 .read(cx)
5656 .all_diff_hunks_expanded()
5657 {
5658 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
5659 }
5660 }
5661 }
5662
5663 let show_git_gutter = layout
5664 .position_map
5665 .snapshot
5666 .show_git_diff_gutter
5667 .unwrap_or_else(|| {
5668 matches!(
5669 ProjectSettings::get_global(cx).git.git_gutter,
5670 Some(GitGutterSetting::TrackedFiles)
5671 )
5672 });
5673 if show_git_gutter {
5674 Self::paint_gutter_diff_hunks(layout, window, cx)
5675 }
5676
5677 let highlight_width = 0.275 * layout.position_map.line_height;
5678 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
5679 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5680 for (range, color) in &layout.highlighted_gutter_ranges {
5681 let start_row = if range.start.row() < layout.visible_display_row_range.start {
5682 layout.visible_display_row_range.start - DisplayRow(1)
5683 } else {
5684 range.start.row()
5685 };
5686 let end_row = if range.end.row() > layout.visible_display_row_range.end {
5687 layout.visible_display_row_range.end + DisplayRow(1)
5688 } else {
5689 range.end.row()
5690 };
5691
5692 let start_y = layout.gutter_hitbox.top()
5693 + start_row.0 as f32 * layout.position_map.line_height
5694 - layout.position_map.scroll_pixel_position.y;
5695 let end_y = layout.gutter_hitbox.top()
5696 + (end_row.0 + 1) as f32 * layout.position_map.line_height
5697 - layout.position_map.scroll_pixel_position.y;
5698 let bounds = Bounds::from_corners(
5699 point(layout.gutter_hitbox.left(), start_y),
5700 point(layout.gutter_hitbox.left() + highlight_width, end_y),
5701 );
5702 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
5703 }
5704 });
5705 }
5706
5707 fn paint_blamed_display_rows(
5708 &self,
5709 layout: &mut EditorLayout,
5710 window: &mut Window,
5711 cx: &mut App,
5712 ) {
5713 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
5714 return;
5715 };
5716
5717 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5718 for mut blame_element in blamed_display_rows.into_iter() {
5719 blame_element.paint(window, cx);
5720 }
5721 })
5722 }
5723
5724 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5725 window.with_content_mask(
5726 Some(ContentMask {
5727 bounds: layout.position_map.text_hitbox.bounds,
5728 }),
5729 |window| {
5730 let editor = self.editor.read(cx);
5731 if editor.mouse_cursor_hidden {
5732 window.set_window_cursor_style(CursorStyle::None);
5733 } else if let SelectionDragState::ReadyToDrag {
5734 mouse_down_time, ..
5735 } = &editor.selection_drag_state
5736 {
5737 let drag_and_drop_delay = Duration::from_millis(
5738 EditorSettings::get_global(cx).drag_and_drop_selection.delay,
5739 );
5740 if mouse_down_time.elapsed() >= drag_and_drop_delay {
5741 window.set_cursor_style(
5742 CursorStyle::DragCopy,
5743 &layout.position_map.text_hitbox,
5744 );
5745 }
5746 } else if matches!(
5747 editor.selection_drag_state,
5748 SelectionDragState::Dragging { .. }
5749 ) {
5750 window
5751 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
5752 } else if editor
5753 .hovered_link_state
5754 .as_ref()
5755 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
5756 {
5757 window.set_cursor_style(
5758 CursorStyle::PointingHand,
5759 &layout.position_map.text_hitbox,
5760 );
5761 } else {
5762 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
5763 };
5764
5765 self.paint_lines_background(layout, window, cx);
5766 let invisible_display_ranges = self.paint_highlights(layout, window);
5767 self.paint_document_colors(layout, window);
5768 self.paint_lines(&invisible_display_ranges, layout, window, cx);
5769 self.paint_redactions(layout, window);
5770 self.paint_cursors(layout, window, cx);
5771 self.paint_inline_diagnostics(layout, window, cx);
5772 self.paint_inline_blame(layout, window, cx);
5773 self.paint_inline_code_actions(layout, window, cx);
5774 self.paint_diff_hunk_controls(layout, window, cx);
5775 window.with_element_namespace("crease_trailers", |window| {
5776 for trailer in layout.crease_trailers.iter_mut().flatten() {
5777 trailer.element.paint(window, cx);
5778 }
5779 });
5780 },
5781 )
5782 }
5783
5784 fn paint_highlights(
5785 &mut self,
5786 layout: &mut EditorLayout,
5787 window: &mut Window,
5788 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
5789 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5790 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
5791 let line_end_overshoot = 0.15 * layout.position_map.line_height;
5792 for (range, color) in &layout.highlighted_ranges {
5793 self.paint_highlighted_range(
5794 range.clone(),
5795 true,
5796 *color,
5797 Pixels::ZERO,
5798 line_end_overshoot,
5799 layout,
5800 window,
5801 );
5802 }
5803
5804 let corner_radius = 0.15 * layout.position_map.line_height;
5805
5806 for (player_color, selections) in &layout.selections {
5807 for selection in selections.iter() {
5808 self.paint_highlighted_range(
5809 selection.range.clone(),
5810 true,
5811 player_color.selection,
5812 corner_radius,
5813 corner_radius * 2.,
5814 layout,
5815 window,
5816 );
5817
5818 if selection.is_local && !selection.range.is_empty() {
5819 invisible_display_ranges.push(selection.range.clone());
5820 }
5821 }
5822 }
5823 invisible_display_ranges
5824 })
5825 }
5826
5827 fn paint_lines(
5828 &mut self,
5829 invisible_display_ranges: &[Range<DisplayPoint>],
5830 layout: &mut EditorLayout,
5831 window: &mut Window,
5832 cx: &mut App,
5833 ) {
5834 let whitespace_setting = self
5835 .editor
5836 .read(cx)
5837 .buffer
5838 .read(cx)
5839 .language_settings(cx)
5840 .show_whitespaces;
5841
5842 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5843 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5844 line_with_invisibles.draw(
5845 layout,
5846 row,
5847 layout.content_origin,
5848 whitespace_setting,
5849 invisible_display_ranges,
5850 window,
5851 cx,
5852 )
5853 }
5854
5855 for line_element in &mut layout.line_elements {
5856 line_element.paint(window, cx);
5857 }
5858 }
5859
5860 fn paint_lines_background(
5861 &mut self,
5862 layout: &mut EditorLayout,
5863 window: &mut Window,
5864 cx: &mut App,
5865 ) {
5866 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5867 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5868 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
5869 }
5870 }
5871
5872 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
5873 if layout.redacted_ranges.is_empty() {
5874 return;
5875 }
5876
5877 let line_end_overshoot = layout.line_end_overshoot();
5878
5879 // A softer than perfect black
5880 let redaction_color = gpui::rgb(0x0e1111);
5881
5882 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5883 for range in layout.redacted_ranges.iter() {
5884 self.paint_highlighted_range(
5885 range.clone(),
5886 true,
5887 redaction_color.into(),
5888 Pixels::ZERO,
5889 line_end_overshoot,
5890 layout,
5891 window,
5892 );
5893 }
5894 });
5895 }
5896
5897 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
5898 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
5899 return;
5900 };
5901 if image_colors.is_empty()
5902 || colors_render_mode == &DocumentColorsRenderMode::None
5903 || colors_render_mode == &DocumentColorsRenderMode::Inlay
5904 {
5905 return;
5906 }
5907
5908 let line_end_overshoot = layout.line_end_overshoot();
5909
5910 for (range, color) in image_colors {
5911 match colors_render_mode {
5912 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
5913 DocumentColorsRenderMode::Background => {
5914 self.paint_highlighted_range(
5915 range.clone(),
5916 true,
5917 *color,
5918 Pixels::ZERO,
5919 line_end_overshoot,
5920 layout,
5921 window,
5922 );
5923 }
5924 DocumentColorsRenderMode::Border => {
5925 self.paint_highlighted_range(
5926 range.clone(),
5927 false,
5928 *color,
5929 Pixels::ZERO,
5930 line_end_overshoot,
5931 layout,
5932 window,
5933 );
5934 }
5935 }
5936 }
5937 }
5938
5939 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5940 for cursor in &mut layout.visible_cursors {
5941 cursor.paint(layout.content_origin, window, cx);
5942 }
5943 }
5944
5945 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5946 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
5947 return;
5948 };
5949 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
5950
5951 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
5952 let hitbox = &scrollbar_layout.hitbox;
5953 if scrollbars_layout.visible {
5954 let scrollbar_edges = match axis {
5955 ScrollbarAxis::Horizontal => Edges {
5956 top: Pixels::ZERO,
5957 right: Pixels::ZERO,
5958 bottom: Pixels::ZERO,
5959 left: Pixels::ZERO,
5960 },
5961 ScrollbarAxis::Vertical => Edges {
5962 top: Pixels::ZERO,
5963 right: Pixels::ZERO,
5964 bottom: Pixels::ZERO,
5965 left: ScrollbarLayout::BORDER_WIDTH,
5966 },
5967 };
5968
5969 window.paint_layer(hitbox.bounds, |window| {
5970 window.paint_quad(quad(
5971 hitbox.bounds,
5972 Corners::default(),
5973 cx.theme().colors().scrollbar_track_background,
5974 scrollbar_edges,
5975 cx.theme().colors().scrollbar_track_border,
5976 BorderStyle::Solid,
5977 ));
5978
5979 if axis == ScrollbarAxis::Vertical {
5980 let fast_markers =
5981 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5982 // Refresh slow scrollbar markers in the background. Below, we
5983 // paint whatever markers have already been computed.
5984 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5985
5986 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5987 for marker in markers.iter().chain(&fast_markers) {
5988 let mut marker = marker.clone();
5989 marker.bounds.origin += hitbox.origin;
5990 window.paint_quad(marker);
5991 }
5992 }
5993
5994 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
5995 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
5996 ScrollbarThumbState::Dragging => {
5997 cx.theme().colors().scrollbar_thumb_active_background
5998 }
5999 ScrollbarThumbState::Hovered => {
6000 cx.theme().colors().scrollbar_thumb_hover_background
6001 }
6002 ScrollbarThumbState::Idle => {
6003 cx.theme().colors().scrollbar_thumb_background
6004 }
6005 };
6006 window.paint_quad(quad(
6007 thumb_bounds,
6008 Corners::default(),
6009 scrollbar_thumb_color,
6010 scrollbar_edges,
6011 cx.theme().colors().scrollbar_thumb_border,
6012 BorderStyle::Solid,
6013 ));
6014
6015 if any_scrollbar_dragged {
6016 window.set_window_cursor_style(CursorStyle::Arrow);
6017 } else {
6018 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
6019 }
6020 }
6021 })
6022 }
6023 }
6024
6025 window.on_mouse_event({
6026 let editor = self.editor.clone();
6027 let scrollbars_layout = scrollbars_layout.clone();
6028
6029 let mut mouse_position = window.mouse_position();
6030 move |event: &MouseMoveEvent, phase, window, cx| {
6031 if phase == DispatchPhase::Capture {
6032 return;
6033 }
6034
6035 editor.update(cx, |editor, cx| {
6036 if let Some((scrollbar_layout, axis)) = event
6037 .pressed_button
6038 .filter(|button| *button == MouseButton::Left)
6039 .and(editor.scroll_manager.dragging_scrollbar_axis())
6040 .and_then(|axis| {
6041 scrollbars_layout
6042 .iter_scrollbars()
6043 .find(|(_, a)| *a == axis)
6044 })
6045 {
6046 let ScrollbarLayout {
6047 hitbox,
6048 text_unit_size,
6049 ..
6050 } = scrollbar_layout;
6051
6052 let old_position = mouse_position.along(axis);
6053 let new_position = event.position.along(axis);
6054 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6055 .contains(&old_position)
6056 {
6057 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6058 (p + (new_position - old_position) / *text_unit_size).max(0.)
6059 });
6060 editor.set_scroll_position(position, window, cx);
6061 }
6062
6063 editor.scroll_manager.show_scrollbars(window, cx);
6064 cx.stop_propagation();
6065 } else if let Some((layout, axis)) = scrollbars_layout
6066 .get_hovered_axis(window)
6067 .filter(|_| !event.dragging())
6068 {
6069 if layout.thumb_hovered(&event.position) {
6070 editor
6071 .scroll_manager
6072 .set_hovered_scroll_thumb_axis(axis, cx);
6073 } else {
6074 editor.scroll_manager.reset_scrollbar_state(cx);
6075 }
6076
6077 editor.scroll_manager.show_scrollbars(window, cx);
6078 } else {
6079 editor.scroll_manager.reset_scrollbar_state(cx);
6080 }
6081
6082 mouse_position = event.position;
6083 })
6084 }
6085 });
6086
6087 if any_scrollbar_dragged {
6088 window.on_mouse_event({
6089 let editor = self.editor.clone();
6090 move |_: &MouseUpEvent, phase, window, cx| {
6091 if phase == DispatchPhase::Capture {
6092 return;
6093 }
6094
6095 editor.update(cx, |editor, cx| {
6096 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6097 editor
6098 .scroll_manager
6099 .set_hovered_scroll_thumb_axis(axis, cx);
6100 } else {
6101 editor.scroll_manager.reset_scrollbar_state(cx);
6102 }
6103 cx.stop_propagation();
6104 });
6105 }
6106 });
6107 } else {
6108 window.on_mouse_event({
6109 let editor = self.editor.clone();
6110
6111 move |event: &MouseDownEvent, phase, window, cx| {
6112 if phase == DispatchPhase::Capture {
6113 return;
6114 }
6115 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6116 else {
6117 return;
6118 };
6119
6120 let ScrollbarLayout {
6121 hitbox,
6122 visible_range,
6123 text_unit_size,
6124 thumb_bounds,
6125 ..
6126 } = scrollbar_layout;
6127
6128 let Some(thumb_bounds) = thumb_bounds else {
6129 return;
6130 };
6131
6132 editor.update(cx, |editor, cx| {
6133 editor
6134 .scroll_manager
6135 .set_dragged_scroll_thumb_axis(axis, cx);
6136
6137 let event_position = event.position.along(axis);
6138
6139 if event_position < thumb_bounds.origin.along(axis)
6140 || thumb_bounds.bottom_right().along(axis) < event_position
6141 {
6142 let center_position = ((event_position - hitbox.origin.along(axis))
6143 / *text_unit_size)
6144 .round() as u32;
6145 let start_position = center_position.saturating_sub(
6146 (visible_range.end - visible_range.start) as u32 / 2,
6147 );
6148
6149 let position = editor
6150 .scroll_position(cx)
6151 .apply_along(axis, |_| start_position as f32);
6152
6153 editor.set_scroll_position(position, window, cx);
6154 } else {
6155 editor.scroll_manager.show_scrollbars(window, cx);
6156 }
6157
6158 cx.stop_propagation();
6159 });
6160 }
6161 });
6162 }
6163 }
6164
6165 fn collect_fast_scrollbar_markers(
6166 &self,
6167 layout: &EditorLayout,
6168 scrollbar_layout: &ScrollbarLayout,
6169 cx: &mut App,
6170 ) -> Vec<PaintQuad> {
6171 const LIMIT: usize = 100;
6172 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6173 return vec![];
6174 }
6175 let cursor_ranges = layout
6176 .cursors
6177 .iter()
6178 .map(|(point, color)| ColoredRange {
6179 start: point.row(),
6180 end: point.row(),
6181 color: *color,
6182 })
6183 .collect_vec();
6184 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6185 }
6186
6187 fn refresh_slow_scrollbar_markers(
6188 &self,
6189 layout: &EditorLayout,
6190 scrollbar_layout: &ScrollbarLayout,
6191 window: &mut Window,
6192 cx: &mut App,
6193 ) {
6194 self.editor.update(cx, |editor, cx| {
6195 if !editor.is_singleton(cx)
6196 || !editor
6197 .scrollbar_marker_state
6198 .should_refresh(scrollbar_layout.hitbox.size)
6199 {
6200 return;
6201 }
6202
6203 let scrollbar_layout = scrollbar_layout.clone();
6204 let background_highlights = editor.background_highlights.clone();
6205 let snapshot = layout.position_map.snapshot.clone();
6206 let theme = cx.theme().clone();
6207 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6208
6209 editor.scrollbar_marker_state.dirty = false;
6210 editor.scrollbar_marker_state.pending_refresh =
6211 Some(cx.spawn_in(window, async move |editor, cx| {
6212 let scrollbar_size = scrollbar_layout.hitbox.size;
6213 let scrollbar_markers = cx
6214 .background_spawn(async move {
6215 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
6216 let mut marker_quads = Vec::new();
6217 if scrollbar_settings.git_diff {
6218 let marker_row_ranges =
6219 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
6220 let start_display_row =
6221 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6222 .to_display_point(&snapshot.display_snapshot)
6223 .row();
6224 let mut end_display_row =
6225 MultiBufferPoint::new(hunk.row_range.end.0, 0)
6226 .to_display_point(&snapshot.display_snapshot)
6227 .row();
6228 if end_display_row != start_display_row {
6229 end_display_row.0 -= 1;
6230 }
6231 let color = match &hunk.status().kind {
6232 DiffHunkStatusKind::Added => {
6233 theme.colors().version_control_added
6234 }
6235 DiffHunkStatusKind::Modified => {
6236 theme.colors().version_control_modified
6237 }
6238 DiffHunkStatusKind::Deleted => {
6239 theme.colors().version_control_deleted
6240 }
6241 };
6242 ColoredRange {
6243 start: start_display_row,
6244 end: end_display_row,
6245 color,
6246 }
6247 });
6248
6249 marker_quads.extend(
6250 scrollbar_layout
6251 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
6252 );
6253 }
6254
6255 for (background_highlight_id, (_, background_ranges)) in
6256 background_highlights.iter()
6257 {
6258 let is_search_highlights = *background_highlight_id
6259 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
6260 let is_text_highlights = *background_highlight_id
6261 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
6262 let is_symbol_occurrences = *background_highlight_id
6263 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
6264 || *background_highlight_id
6265 == HighlightKey::Type(
6266 TypeId::of::<DocumentHighlightWrite>(),
6267 );
6268 if (is_search_highlights && scrollbar_settings.search_results)
6269 || (is_text_highlights && scrollbar_settings.selected_text)
6270 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
6271 {
6272 let mut color = theme.status().info;
6273 if is_symbol_occurrences {
6274 color.fade_out(0.5);
6275 }
6276 let marker_row_ranges = background_ranges.iter().map(|range| {
6277 let display_start = range
6278 .start
6279 .to_display_point(&snapshot.display_snapshot);
6280 let display_end =
6281 range.end.to_display_point(&snapshot.display_snapshot);
6282 ColoredRange {
6283 start: display_start.row(),
6284 end: display_end.row(),
6285 color,
6286 }
6287 });
6288 marker_quads.extend(
6289 scrollbar_layout
6290 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
6291 );
6292 }
6293 }
6294
6295 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
6296 let diagnostics = snapshot
6297 .buffer_snapshot
6298 .diagnostics_in_range::<Point>(Point::zero()..max_point)
6299 // Don't show diagnostics the user doesn't care about
6300 .filter(|diagnostic| {
6301 match (
6302 scrollbar_settings.diagnostics,
6303 diagnostic.diagnostic.severity,
6304 ) {
6305 (ScrollbarDiagnostics::All, _) => true,
6306 (
6307 ScrollbarDiagnostics::Error,
6308 lsp::DiagnosticSeverity::ERROR,
6309 ) => true,
6310 (
6311 ScrollbarDiagnostics::Warning,
6312 lsp::DiagnosticSeverity::ERROR
6313 | lsp::DiagnosticSeverity::WARNING,
6314 ) => true,
6315 (
6316 ScrollbarDiagnostics::Information,
6317 lsp::DiagnosticSeverity::ERROR
6318 | lsp::DiagnosticSeverity::WARNING
6319 | lsp::DiagnosticSeverity::INFORMATION,
6320 ) => true,
6321 (_, _) => false,
6322 }
6323 })
6324 // We want to sort by severity, in order to paint the most severe diagnostics last.
6325 .sorted_by_key(|diagnostic| {
6326 std::cmp::Reverse(diagnostic.diagnostic.severity)
6327 });
6328
6329 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
6330 let start_display = diagnostic
6331 .range
6332 .start
6333 .to_display_point(&snapshot.display_snapshot);
6334 let end_display = diagnostic
6335 .range
6336 .end
6337 .to_display_point(&snapshot.display_snapshot);
6338 let color = match diagnostic.diagnostic.severity {
6339 lsp::DiagnosticSeverity::ERROR => theme.status().error,
6340 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
6341 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
6342 _ => theme.status().hint,
6343 };
6344 ColoredRange {
6345 start: start_display.row(),
6346 end: end_display.row(),
6347 color,
6348 }
6349 });
6350 marker_quads.extend(
6351 scrollbar_layout
6352 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
6353 );
6354 }
6355
6356 Arc::from(marker_quads)
6357 })
6358 .await;
6359
6360 editor.update(cx, |editor, cx| {
6361 editor.scrollbar_marker_state.markers = scrollbar_markers;
6362 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
6363 editor.scrollbar_marker_state.pending_refresh = None;
6364 cx.notify();
6365 })?;
6366
6367 Ok(())
6368 }));
6369 });
6370 }
6371
6372 fn paint_highlighted_range(
6373 &self,
6374 range: Range<DisplayPoint>,
6375 fill: bool,
6376 color: Hsla,
6377 corner_radius: Pixels,
6378 line_end_overshoot: Pixels,
6379 layout: &EditorLayout,
6380 window: &mut Window,
6381 ) {
6382 let start_row = layout.visible_display_row_range.start;
6383 let end_row = layout.visible_display_row_range.end;
6384 if range.start != range.end {
6385 let row_range = if range.end.column() == 0 {
6386 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
6387 } else {
6388 cmp::max(range.start.row(), start_row)
6389 ..cmp::min(range.end.row().next_row(), end_row)
6390 };
6391
6392 let highlighted_range = HighlightedRange {
6393 color,
6394 line_height: layout.position_map.line_height,
6395 corner_radius,
6396 start_y: layout.content_origin.y
6397 + row_range.start.as_f32() * layout.position_map.line_height
6398 - layout.position_map.scroll_pixel_position.y,
6399 lines: row_range
6400 .iter_rows()
6401 .map(|row| {
6402 let line_layout =
6403 &layout.position_map.line_layouts[row.minus(start_row) as usize];
6404 HighlightedRangeLine {
6405 start_x: if row == range.start.row() {
6406 layout.content_origin.x
6407 + line_layout.x_for_index(range.start.column() as usize)
6408 - layout.position_map.scroll_pixel_position.x
6409 } else {
6410 layout.content_origin.x
6411 - layout.position_map.scroll_pixel_position.x
6412 },
6413 end_x: if row == range.end.row() {
6414 layout.content_origin.x
6415 + line_layout.x_for_index(range.end.column() as usize)
6416 - layout.position_map.scroll_pixel_position.x
6417 } else {
6418 layout.content_origin.x + line_layout.width + line_end_overshoot
6419 - layout.position_map.scroll_pixel_position.x
6420 },
6421 }
6422 })
6423 .collect(),
6424 };
6425
6426 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
6427 }
6428 }
6429
6430 fn paint_inline_diagnostics(
6431 &mut self,
6432 layout: &mut EditorLayout,
6433 window: &mut Window,
6434 cx: &mut App,
6435 ) {
6436 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
6437 inline_diagnostic.1.paint(window, cx);
6438 }
6439 }
6440
6441 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6442 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
6443 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6444 blame_layout.element.paint(window, cx);
6445 })
6446 }
6447 }
6448
6449 fn paint_inline_code_actions(
6450 &mut self,
6451 layout: &mut EditorLayout,
6452 window: &mut Window,
6453 cx: &mut App,
6454 ) {
6455 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
6456 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6457 inline_code_actions.paint(window, cx);
6458 })
6459 }
6460 }
6461
6462 fn paint_diff_hunk_controls(
6463 &mut self,
6464 layout: &mut EditorLayout,
6465 window: &mut Window,
6466 cx: &mut App,
6467 ) {
6468 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
6469 diff_hunk_control.paint(window, cx);
6470 }
6471 }
6472
6473 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6474 if let Some(mut layout) = layout.minimap.take() {
6475 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
6476 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
6477
6478 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
6479 window.with_element_namespace("minimap", |window| {
6480 layout.minimap.paint(window, cx);
6481 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
6482 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
6483 ScrollbarThumbState::Idle => {
6484 cx.theme().colors().minimap_thumb_background
6485 }
6486 ScrollbarThumbState::Hovered => {
6487 cx.theme().colors().minimap_thumb_hover_background
6488 }
6489 ScrollbarThumbState::Dragging => {
6490 cx.theme().colors().minimap_thumb_active_background
6491 }
6492 };
6493 let minimap_thumb_border = match layout.thumb_border_style {
6494 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
6495 MinimapThumbBorder::LeftOnly => Edges {
6496 left: ScrollbarLayout::BORDER_WIDTH,
6497 ..Default::default()
6498 },
6499 MinimapThumbBorder::LeftOpen => Edges {
6500 right: ScrollbarLayout::BORDER_WIDTH,
6501 top: ScrollbarLayout::BORDER_WIDTH,
6502 bottom: ScrollbarLayout::BORDER_WIDTH,
6503 ..Default::default()
6504 },
6505 MinimapThumbBorder::RightOpen => Edges {
6506 left: ScrollbarLayout::BORDER_WIDTH,
6507 top: ScrollbarLayout::BORDER_WIDTH,
6508 bottom: ScrollbarLayout::BORDER_WIDTH,
6509 ..Default::default()
6510 },
6511 MinimapThumbBorder::None => Default::default(),
6512 };
6513
6514 window.paint_layer(minimap_hitbox.bounds, |window| {
6515 window.paint_quad(quad(
6516 thumb_bounds,
6517 Corners::default(),
6518 minimap_thumb_color,
6519 minimap_thumb_border,
6520 cx.theme().colors().minimap_thumb_border,
6521 BorderStyle::Solid,
6522 ));
6523 });
6524 }
6525 });
6526 });
6527
6528 if dragging_minimap {
6529 window.set_window_cursor_style(CursorStyle::Arrow);
6530 } else {
6531 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
6532 }
6533
6534 let minimap_axis = ScrollbarAxis::Vertical;
6535 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
6536 .min(layout.minimap_line_height);
6537
6538 let mut mouse_position = window.mouse_position();
6539
6540 window.on_mouse_event({
6541 let editor = self.editor.clone();
6542
6543 let minimap_hitbox = minimap_hitbox.clone();
6544
6545 move |event: &MouseMoveEvent, phase, window, cx| {
6546 if phase == DispatchPhase::Capture {
6547 return;
6548 }
6549
6550 editor.update(cx, |editor, cx| {
6551 if event.pressed_button == Some(MouseButton::Left)
6552 && editor.scroll_manager.is_dragging_minimap()
6553 {
6554 let old_position = mouse_position.along(minimap_axis);
6555 let new_position = event.position.along(minimap_axis);
6556 if (minimap_hitbox.origin.along(minimap_axis)
6557 ..minimap_hitbox.bottom_right().along(minimap_axis))
6558 .contains(&old_position)
6559 {
6560 let position =
6561 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
6562 (p + (new_position - old_position) / pixels_per_line)
6563 .max(0.)
6564 });
6565 editor.set_scroll_position(position, window, cx);
6566 }
6567 cx.stop_propagation();
6568 } else {
6569 if minimap_hitbox.is_hovered(window) {
6570 editor.scroll_manager.set_is_hovering_minimap_thumb(
6571 !event.dragging()
6572 && layout
6573 .thumb_layout
6574 .thumb_bounds
6575 .is_some_and(|bounds| bounds.contains(&event.position)),
6576 cx,
6577 );
6578
6579 // Stop hover events from propagating to the
6580 // underlying editor if the minimap hitbox is hovered
6581 if !event.dragging() {
6582 cx.stop_propagation();
6583 }
6584 } else {
6585 editor.scroll_manager.hide_minimap_thumb(cx);
6586 }
6587 }
6588 mouse_position = event.position;
6589 });
6590 }
6591 });
6592
6593 if dragging_minimap {
6594 window.on_mouse_event({
6595 let editor = self.editor.clone();
6596 move |event: &MouseUpEvent, phase, window, cx| {
6597 if phase == DispatchPhase::Capture {
6598 return;
6599 }
6600
6601 editor.update(cx, |editor, cx| {
6602 if minimap_hitbox.is_hovered(window) {
6603 editor.scroll_manager.set_is_hovering_minimap_thumb(
6604 layout
6605 .thumb_layout
6606 .thumb_bounds
6607 .is_some_and(|bounds| bounds.contains(&event.position)),
6608 cx,
6609 );
6610 } else {
6611 editor.scroll_manager.hide_minimap_thumb(cx);
6612 }
6613 cx.stop_propagation();
6614 });
6615 }
6616 });
6617 } else {
6618 window.on_mouse_event({
6619 let editor = self.editor.clone();
6620
6621 move |event: &MouseDownEvent, phase, window, cx| {
6622 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
6623 return;
6624 }
6625
6626 let event_position = event.position;
6627
6628 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
6629 return;
6630 };
6631
6632 editor.update(cx, |editor, cx| {
6633 if !thumb_bounds.contains(&event_position) {
6634 let click_position =
6635 event_position.relative_to(&minimap_hitbox.origin).y;
6636
6637 let top_position = (click_position
6638 - thumb_bounds.size.along(minimap_axis) / 2.0)
6639 .max(Pixels::ZERO);
6640
6641 let scroll_offset = (layout.minimap_scroll_top
6642 + top_position / layout.minimap_line_height)
6643 .min(layout.max_scroll_top);
6644
6645 let scroll_position = editor
6646 .scroll_position(cx)
6647 .apply_along(minimap_axis, |_| scroll_offset);
6648 editor.set_scroll_position(scroll_position, window, cx);
6649 }
6650
6651 editor.scroll_manager.set_is_dragging_minimap(cx);
6652 cx.stop_propagation();
6653 });
6654 }
6655 });
6656 }
6657 }
6658 }
6659
6660 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6661 for mut block in layout.blocks.drain(..) {
6662 if block.overlaps_gutter {
6663 block.element.paint(window, cx);
6664 } else {
6665 let mut bounds = layout.hitbox.bounds;
6666 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
6667 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6668 block.element.paint(window, cx);
6669 })
6670 }
6671 }
6672 }
6673
6674 fn paint_inline_completion_popover(
6675 &mut self,
6676 layout: &mut EditorLayout,
6677 window: &mut Window,
6678 cx: &mut App,
6679 ) {
6680 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
6681 inline_completion_popover.paint(window, cx);
6682 }
6683 }
6684
6685 fn paint_mouse_context_menu(
6686 &mut self,
6687 layout: &mut EditorLayout,
6688 window: &mut Window,
6689 cx: &mut App,
6690 ) {
6691 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
6692 mouse_context_menu.paint(window, cx);
6693 }
6694 }
6695
6696 fn paint_scroll_wheel_listener(
6697 &mut self,
6698 layout: &EditorLayout,
6699 window: &mut Window,
6700 cx: &mut App,
6701 ) {
6702 window.on_mouse_event({
6703 let position_map = layout.position_map.clone();
6704 let editor = self.editor.clone();
6705 let hitbox = layout.hitbox.clone();
6706 let mut delta = ScrollDelta::default();
6707
6708 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
6709 // accidentally turn off their scrolling.
6710 let base_scroll_sensitivity =
6711 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
6712
6713 // Use a minimum fast_scroll_sensitivity for same reason above
6714 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
6715 .fast_scroll_sensitivity
6716 .max(0.01);
6717
6718 move |event: &ScrollWheelEvent, phase, window, cx| {
6719 let scroll_sensitivity = {
6720 if event.modifiers.alt {
6721 fast_scroll_sensitivity
6722 } else {
6723 base_scroll_sensitivity
6724 }
6725 };
6726
6727 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
6728 delta = delta.coalesce(event.delta);
6729 editor.update(cx, |editor, cx| {
6730 let position_map: &PositionMap = &position_map;
6731
6732 let line_height = position_map.line_height;
6733 let max_glyph_advance = position_map.em_advance;
6734 let (delta, axis) = match delta {
6735 gpui::ScrollDelta::Pixels(mut pixels) => {
6736 //Trackpad
6737 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
6738 (pixels, axis)
6739 }
6740
6741 gpui::ScrollDelta::Lines(lines) => {
6742 //Not trackpad
6743 let pixels =
6744 point(lines.x * max_glyph_advance, lines.y * line_height);
6745 (pixels, None)
6746 }
6747 };
6748
6749 let current_scroll_position = position_map.snapshot.scroll_position();
6750 let x = (current_scroll_position.x * max_glyph_advance
6751 - (delta.x * scroll_sensitivity))
6752 / max_glyph_advance;
6753 let y = (current_scroll_position.y * line_height
6754 - (delta.y * scroll_sensitivity))
6755 / line_height;
6756 let mut scroll_position =
6757 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
6758 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
6759 if forbid_vertical_scroll {
6760 scroll_position.y = current_scroll_position.y;
6761 }
6762
6763 if scroll_position != current_scroll_position {
6764 editor.scroll(scroll_position, axis, window, cx);
6765 cx.stop_propagation();
6766 } else if y < 0. {
6767 // Due to clamping, we may fail to detect cases of overscroll to the top;
6768 // We want the scroll manager to get an update in such cases and detect the change of direction
6769 // on the next frame.
6770 cx.notify();
6771 }
6772 });
6773 }
6774 }
6775 });
6776 }
6777
6778 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
6779 if self.editor.read(cx).mode.is_minimap() {
6780 return;
6781 }
6782
6783 self.paint_scroll_wheel_listener(layout, window, cx);
6784
6785 window.on_mouse_event({
6786 let position_map = layout.position_map.clone();
6787 let editor = self.editor.clone();
6788 let diff_hunk_range =
6789 layout
6790 .display_hunks
6791 .iter()
6792 .find_map(|(hunk, hunk_hitbox)| match hunk {
6793 DisplayDiffHunk::Folded { .. } => None,
6794 DisplayDiffHunk::Unfolded {
6795 multi_buffer_range, ..
6796 } => {
6797 if hunk_hitbox
6798 .as_ref()
6799 .map(|hitbox| hitbox.is_hovered(window))
6800 .unwrap_or(false)
6801 {
6802 Some(multi_buffer_range.clone())
6803 } else {
6804 None
6805 }
6806 }
6807 });
6808 let line_numbers = layout.line_numbers.clone();
6809
6810 move |event: &MouseDownEvent, phase, window, cx| {
6811 if phase == DispatchPhase::Bubble {
6812 match event.button {
6813 MouseButton::Left => editor.update(cx, |editor, cx| {
6814 let pending_mouse_down = editor
6815 .pending_mouse_down
6816 .get_or_insert_with(Default::default)
6817 .clone();
6818
6819 *pending_mouse_down.borrow_mut() = Some(event.clone());
6820
6821 Self::mouse_left_down(
6822 editor,
6823 event,
6824 diff_hunk_range.clone(),
6825 &position_map,
6826 line_numbers.as_ref(),
6827 window,
6828 cx,
6829 );
6830 }),
6831 MouseButton::Right => editor.update(cx, |editor, cx| {
6832 Self::mouse_right_down(editor, event, &position_map, window, cx);
6833 }),
6834 MouseButton::Middle => editor.update(cx, |editor, cx| {
6835 Self::mouse_middle_down(editor, event, &position_map, window, cx);
6836 }),
6837 _ => {}
6838 };
6839 }
6840 }
6841 });
6842
6843 window.on_mouse_event({
6844 let editor = self.editor.clone();
6845 let position_map = layout.position_map.clone();
6846
6847 move |event: &MouseUpEvent, phase, window, cx| {
6848 if phase == DispatchPhase::Bubble {
6849 editor.update(cx, |editor, cx| {
6850 Self::mouse_up(editor, event, &position_map, window, cx)
6851 });
6852 }
6853 }
6854 });
6855
6856 window.on_mouse_event({
6857 let editor = self.editor.clone();
6858 let position_map = layout.position_map.clone();
6859 let mut captured_mouse_down = None;
6860
6861 move |event: &MouseUpEvent, phase, window, cx| match phase {
6862 // Clear the pending mouse down during the capture phase,
6863 // so that it happens even if another event handler stops
6864 // propagation.
6865 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
6866 let pending_mouse_down = editor
6867 .pending_mouse_down
6868 .get_or_insert_with(Default::default)
6869 .clone();
6870
6871 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
6872 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
6873 captured_mouse_down = pending_mouse_down.take();
6874 window.refresh();
6875 }
6876 }),
6877 // Fire click handlers during the bubble phase.
6878 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
6879 if let Some(mouse_down) = captured_mouse_down.take() {
6880 let event = ClickEvent {
6881 down: mouse_down,
6882 up: event.clone(),
6883 };
6884 Self::click(editor, &event, &position_map, window, cx);
6885 }
6886 }),
6887 }
6888 });
6889
6890 window.on_mouse_event({
6891 let position_map = layout.position_map.clone();
6892 let editor = self.editor.clone();
6893
6894 move |event: &MouseMoveEvent, phase, window, cx| {
6895 if phase == DispatchPhase::Bubble {
6896 editor.update(cx, |editor, cx| {
6897 if editor.hover_state.focused(window, cx) {
6898 return;
6899 }
6900 if event.pressed_button == Some(MouseButton::Left)
6901 || event.pressed_button == Some(MouseButton::Middle)
6902 {
6903 Self::mouse_dragged(editor, event, &position_map, window, cx)
6904 }
6905
6906 Self::mouse_moved(editor, event, &position_map, window, cx)
6907 });
6908 }
6909 }
6910 });
6911 }
6912
6913 fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
6914 let style = &self.style;
6915 let font_size = style.text.font_size.to_pixels(window.rem_size());
6916 let layout = window.text_system().shape_line(
6917 SharedString::from(" ".repeat(column)),
6918 font_size,
6919 &[TextRun {
6920 len: column,
6921 font: style.text.font(),
6922 color: Hsla::default(),
6923 background_color: None,
6924 underline: None,
6925 strikethrough: None,
6926 }],
6927 None,
6928 );
6929
6930 layout.width
6931 }
6932
6933 fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
6934 let digit_count = snapshot.widest_line_number().ilog10() + 1;
6935 self.column_pixels(digit_count as usize, window)
6936 }
6937
6938 fn shape_line_number(
6939 &self,
6940 text: SharedString,
6941 color: Hsla,
6942 window: &mut Window,
6943 ) -> ShapedLine {
6944 let run = TextRun {
6945 len: text.len(),
6946 font: self.style.text.font(),
6947 color,
6948 background_color: None,
6949 underline: None,
6950 strikethrough: None,
6951 };
6952 window.text_system().shape_line(
6953 text,
6954 self.style.text.font_size.to_pixels(window.rem_size()),
6955 &[run],
6956 None,
6957 )
6958 }
6959
6960 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
6961 let unstaged = status.has_secondary_hunk();
6962 let unstaged_hollow = ProjectSettings::get_global(cx)
6963 .git
6964 .hunk_style
6965 .map_or(false, |style| {
6966 matches!(style, GitHunkStyleSetting::UnstagedHollow)
6967 });
6968
6969 unstaged == unstaged_hollow
6970 }
6971}
6972
6973fn header_jump_data(
6974 snapshot: &EditorSnapshot,
6975 block_row_start: DisplayRow,
6976 height: u32,
6977 for_excerpt: &ExcerptInfo,
6978) -> JumpData {
6979 let range = &for_excerpt.range;
6980 let buffer = &for_excerpt.buffer;
6981 let jump_anchor = range.primary.start;
6982
6983 let excerpt_start = range.context.start;
6984 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
6985 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
6986 0
6987 } else {
6988 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
6989 jump_position.row.saturating_sub(excerpt_start_point.row)
6990 };
6991
6992 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
6993 .saturating_sub(
6994 snapshot
6995 .scroll_anchor
6996 .scroll_position(&snapshot.display_snapshot)
6997 .y as u32,
6998 );
6999
7000 JumpData::MultiBufferPoint {
7001 excerpt_id: for_excerpt.id,
7002 anchor: jump_anchor,
7003 position: jump_position,
7004 line_offset_from_top,
7005 }
7006}
7007
7008pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
7009
7010impl AcceptEditPredictionBinding {
7011 pub fn keystroke(&self) -> Option<&Keystroke> {
7012 if let Some(binding) = self.0.as_ref() {
7013 match &binding.keystrokes() {
7014 [keystroke, ..] => Some(keystroke),
7015 _ => None,
7016 }
7017 } else {
7018 None
7019 }
7020 }
7021}
7022
7023fn prepaint_gutter_button(
7024 button: IconButton,
7025 row: DisplayRow,
7026 line_height: Pixels,
7027 gutter_dimensions: &GutterDimensions,
7028 scroll_pixel_position: gpui::Point<Pixels>,
7029 gutter_hitbox: &Hitbox,
7030 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
7031 window: &mut Window,
7032 cx: &mut App,
7033) -> AnyElement {
7034 let mut button = button.into_any_element();
7035
7036 let available_space = size(
7037 AvailableSpace::MinContent,
7038 AvailableSpace::Definite(line_height),
7039 );
7040 let indicator_size = button.layout_as_root(available_space, window, cx);
7041
7042 let blame_width = gutter_dimensions.git_blame_entries_width;
7043 let gutter_width = display_hunks
7044 .binary_search_by(|(hunk, _)| match hunk {
7045 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
7046 DisplayDiffHunk::Unfolded {
7047 display_row_range, ..
7048 } => {
7049 if display_row_range.end <= row {
7050 Ordering::Less
7051 } else if display_row_range.start > row {
7052 Ordering::Greater
7053 } else {
7054 Ordering::Equal
7055 }
7056 }
7057 })
7058 .ok()
7059 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
7060 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
7061
7062 let mut x = left_offset;
7063 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
7064 - indicator_size.width
7065 - left_offset;
7066 x += available_width / 2.;
7067
7068 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
7069 y += (line_height - indicator_size.height) / 2.;
7070
7071 button.prepaint_as_root(
7072 gutter_hitbox.origin + point(x, y),
7073 available_space,
7074 window,
7075 cx,
7076 );
7077 button
7078}
7079
7080fn render_inline_blame_entry(
7081 blame_entry: BlameEntry,
7082 style: &EditorStyle,
7083 cx: &mut App,
7084) -> Option<AnyElement> {
7085 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7086 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
7087}
7088
7089fn render_blame_entry_popover(
7090 blame_entry: BlameEntry,
7091 scroll_handle: ScrollHandle,
7092 commit_message: Option<ParsedCommitMessage>,
7093 markdown: Entity<Markdown>,
7094 workspace: WeakEntity<Workspace>,
7095 blame: &Entity<GitBlame>,
7096 window: &mut Window,
7097 cx: &mut App,
7098) -> Option<AnyElement> {
7099 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7100 let blame = blame.read(cx);
7101 let repository = blame.repository(cx)?.clone();
7102 renderer.render_blame_entry_popover(
7103 blame_entry,
7104 scroll_handle,
7105 commit_message,
7106 markdown,
7107 repository,
7108 workspace,
7109 window,
7110 cx,
7111 )
7112}
7113
7114fn render_blame_entry(
7115 ix: usize,
7116 blame: &Entity<GitBlame>,
7117 blame_entry: BlameEntry,
7118 style: &EditorStyle,
7119 last_used_color: &mut Option<(PlayerColor, Oid)>,
7120 editor: Entity<Editor>,
7121 workspace: Entity<Workspace>,
7122 renderer: Arc<dyn BlameRenderer>,
7123 cx: &mut App,
7124) -> Option<AnyElement> {
7125 let mut sha_color = cx
7126 .theme()
7127 .players()
7128 .color_for_participant(blame_entry.sha.into());
7129
7130 // If the last color we used is the same as the one we get for this line, but
7131 // the commit SHAs are different, then we try again to get a different color.
7132 match *last_used_color {
7133 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
7134 let index: u32 = blame_entry.sha.into();
7135 sha_color = cx.theme().players().color_for_participant(index + 1);
7136 }
7137 _ => {}
7138 };
7139 last_used_color.replace((sha_color, blame_entry.sha));
7140
7141 let blame = blame.read(cx);
7142 let details = blame.details_for_entry(&blame_entry);
7143 let repository = blame.repository(cx)?;
7144 renderer.render_blame_entry(
7145 &style.text,
7146 blame_entry,
7147 details,
7148 repository,
7149 workspace.downgrade(),
7150 editor,
7151 ix,
7152 sha_color.cursor,
7153 cx,
7154 )
7155}
7156
7157#[derive(Debug)]
7158pub(crate) struct LineWithInvisibles {
7159 fragments: SmallVec<[LineFragment; 1]>,
7160 invisibles: Vec<Invisible>,
7161 len: usize,
7162 pub(crate) width: Pixels,
7163 font_size: Pixels,
7164}
7165
7166enum LineFragment {
7167 Text(ShapedLine),
7168 Element {
7169 id: ChunkRendererId,
7170 element: Option<AnyElement>,
7171 size: Size<Pixels>,
7172 len: usize,
7173 },
7174}
7175
7176impl fmt::Debug for LineFragment {
7177 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7178 match self {
7179 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
7180 LineFragment::Element { size, len, .. } => f
7181 .debug_struct("Element")
7182 .field("size", size)
7183 .field("len", len)
7184 .finish(),
7185 }
7186 }
7187}
7188
7189impl LineWithInvisibles {
7190 fn from_chunks<'a>(
7191 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
7192 editor_style: &EditorStyle,
7193 max_line_len: usize,
7194 max_line_count: usize,
7195 editor_mode: &EditorMode,
7196 text_width: Pixels,
7197 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7198 window: &mut Window,
7199 cx: &mut App,
7200 ) -> Vec<Self> {
7201 let text_style = &editor_style.text;
7202 let mut layouts = Vec::with_capacity(max_line_count);
7203 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
7204 let mut line = String::new();
7205 let mut invisibles = Vec::new();
7206 let mut width = Pixels::ZERO;
7207 let mut len = 0;
7208 let mut styles = Vec::new();
7209 let mut non_whitespace_added = false;
7210 let mut row = 0;
7211 let mut line_exceeded_max_len = false;
7212 let font_size = text_style.font_size.to_pixels(window.rem_size());
7213
7214 let ellipsis = SharedString::from("⋯");
7215
7216 for highlighted_chunk in chunks.chain([HighlightedChunk {
7217 text: "\n",
7218 style: None,
7219 is_tab: false,
7220 is_inlay: false,
7221 replacement: None,
7222 }]) {
7223 if let Some(replacement) = highlighted_chunk.replacement {
7224 if !line.is_empty() {
7225 let shaped_line = window.text_system().shape_line(
7226 line.clone().into(),
7227 font_size,
7228 &styles,
7229 None,
7230 );
7231 width += shaped_line.width;
7232 len += shaped_line.len;
7233 fragments.push(LineFragment::Text(shaped_line));
7234 line.clear();
7235 styles.clear();
7236 }
7237
7238 match replacement {
7239 ChunkReplacement::Renderer(renderer) => {
7240 let available_width = if renderer.constrain_width {
7241 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
7242 ellipsis.clone()
7243 } else {
7244 SharedString::from(Arc::from(highlighted_chunk.text))
7245 };
7246 let shaped_line = window.text_system().shape_line(
7247 chunk,
7248 font_size,
7249 &[text_style.to_run(highlighted_chunk.text.len())],
7250 None,
7251 );
7252 AvailableSpace::Definite(shaped_line.width)
7253 } else {
7254 AvailableSpace::MinContent
7255 };
7256
7257 let mut element = (renderer.render)(&mut ChunkRendererContext {
7258 context: cx,
7259 window,
7260 max_width: text_width,
7261 });
7262 let line_height = text_style.line_height_in_pixels(window.rem_size());
7263 let size = element.layout_as_root(
7264 size(available_width, AvailableSpace::Definite(line_height)),
7265 window,
7266 cx,
7267 );
7268
7269 width += size.width;
7270 len += highlighted_chunk.text.len();
7271 fragments.push(LineFragment::Element {
7272 id: renderer.id,
7273 element: Some(element),
7274 size,
7275 len: highlighted_chunk.text.len(),
7276 });
7277 }
7278 ChunkReplacement::Str(x) => {
7279 let text_style = if let Some(style) = highlighted_chunk.style {
7280 Cow::Owned(text_style.clone().highlight(style))
7281 } else {
7282 Cow::Borrowed(text_style)
7283 };
7284
7285 let run = TextRun {
7286 len: x.len(),
7287 font: text_style.font(),
7288 color: text_style.color,
7289 background_color: text_style.background_color,
7290 underline: text_style.underline,
7291 strikethrough: text_style.strikethrough,
7292 };
7293 let line_layout = window
7294 .text_system()
7295 .shape_line(x, font_size, &[run], None)
7296 .with_len(highlighted_chunk.text.len());
7297
7298 width += line_layout.width;
7299 len += highlighted_chunk.text.len();
7300 fragments.push(LineFragment::Text(line_layout))
7301 }
7302 }
7303 } else {
7304 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
7305 if ix > 0 {
7306 let shaped_line = window.text_system().shape_line(
7307 line.clone().into(),
7308 font_size,
7309 &styles,
7310 None,
7311 );
7312 width += shaped_line.width;
7313 len += shaped_line.len;
7314 fragments.push(LineFragment::Text(shaped_line));
7315 layouts.push(Self {
7316 width: mem::take(&mut width),
7317 len: mem::take(&mut len),
7318 fragments: mem::take(&mut fragments),
7319 invisibles: std::mem::take(&mut invisibles),
7320 font_size,
7321 });
7322
7323 line.clear();
7324 styles.clear();
7325 row += 1;
7326 line_exceeded_max_len = false;
7327 non_whitespace_added = false;
7328 if row == max_line_count {
7329 return layouts;
7330 }
7331 }
7332
7333 if !line_chunk.is_empty() && !line_exceeded_max_len {
7334 let text_style = if let Some(style) = highlighted_chunk.style {
7335 Cow::Owned(text_style.clone().highlight(style))
7336 } else {
7337 Cow::Borrowed(text_style)
7338 };
7339
7340 if line.len() + line_chunk.len() > max_line_len {
7341 let mut chunk_len = max_line_len - line.len();
7342 while !line_chunk.is_char_boundary(chunk_len) {
7343 chunk_len -= 1;
7344 }
7345 line_chunk = &line_chunk[..chunk_len];
7346 line_exceeded_max_len = true;
7347 }
7348
7349 styles.push(TextRun {
7350 len: line_chunk.len(),
7351 font: text_style.font(),
7352 color: text_style.color,
7353 background_color: text_style.background_color,
7354 underline: text_style.underline,
7355 strikethrough: text_style.strikethrough,
7356 });
7357
7358 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
7359 // Line wrap pads its contents with fake whitespaces,
7360 // avoid printing them
7361 let is_soft_wrapped = is_row_soft_wrapped(row);
7362 if highlighted_chunk.is_tab {
7363 if non_whitespace_added || !is_soft_wrapped {
7364 invisibles.push(Invisible::Tab {
7365 line_start_offset: line.len(),
7366 line_end_offset: line.len() + line_chunk.len(),
7367 });
7368 }
7369 } else {
7370 invisibles.extend(line_chunk.char_indices().filter_map(
7371 |(index, c)| {
7372 let is_whitespace = c.is_whitespace();
7373 non_whitespace_added |= !is_whitespace;
7374 if is_whitespace
7375 && (non_whitespace_added || !is_soft_wrapped)
7376 {
7377 Some(Invisible::Whitespace {
7378 line_offset: line.len() + index,
7379 })
7380 } else {
7381 None
7382 }
7383 },
7384 ))
7385 }
7386 }
7387
7388 line.push_str(line_chunk);
7389 }
7390 }
7391 }
7392 }
7393
7394 layouts
7395 }
7396
7397 fn prepaint(
7398 &mut self,
7399 line_height: Pixels,
7400 scroll_pixel_position: gpui::Point<Pixels>,
7401 row: DisplayRow,
7402 content_origin: gpui::Point<Pixels>,
7403 line_elements: &mut SmallVec<[AnyElement; 1]>,
7404 window: &mut Window,
7405 cx: &mut App,
7406 ) {
7407 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
7408 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
7409 for fragment in &mut self.fragments {
7410 match fragment {
7411 LineFragment::Text(line) => {
7412 fragment_origin.x += line.width;
7413 }
7414 LineFragment::Element { element, size, .. } => {
7415 let mut element = element
7416 .take()
7417 .expect("you can't prepaint LineWithInvisibles twice");
7418
7419 // Center the element vertically within the line.
7420 let mut element_origin = fragment_origin;
7421 element_origin.y += (line_height - size.height) / 2.;
7422 element.prepaint_at(element_origin, window, cx);
7423 line_elements.push(element);
7424
7425 fragment_origin.x += size.width;
7426 }
7427 }
7428 }
7429 }
7430
7431 fn draw(
7432 &self,
7433 layout: &EditorLayout,
7434 row: DisplayRow,
7435 content_origin: gpui::Point<Pixels>,
7436 whitespace_setting: ShowWhitespaceSetting,
7437 selection_ranges: &[Range<DisplayPoint>],
7438 window: &mut Window,
7439 cx: &mut App,
7440 ) {
7441 let line_height = layout.position_map.line_height;
7442 let line_y = line_height
7443 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7444
7445 let mut fragment_origin =
7446 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7447
7448 for fragment in &self.fragments {
7449 match fragment {
7450 LineFragment::Text(line) => {
7451 line.paint(fragment_origin, line_height, window, cx)
7452 .log_err();
7453 fragment_origin.x += line.width;
7454 }
7455 LineFragment::Element { size, .. } => {
7456 fragment_origin.x += size.width;
7457 }
7458 }
7459 }
7460
7461 self.draw_invisibles(
7462 selection_ranges,
7463 layout,
7464 content_origin,
7465 line_y,
7466 row,
7467 line_height,
7468 whitespace_setting,
7469 window,
7470 cx,
7471 );
7472 }
7473
7474 fn draw_background(
7475 &self,
7476 layout: &EditorLayout,
7477 row: DisplayRow,
7478 content_origin: gpui::Point<Pixels>,
7479 window: &mut Window,
7480 cx: &mut App,
7481 ) {
7482 let line_height = layout.position_map.line_height;
7483 let line_y = line_height
7484 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7485
7486 let mut fragment_origin =
7487 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7488
7489 for fragment in &self.fragments {
7490 match fragment {
7491 LineFragment::Text(line) => {
7492 line.paint_background(fragment_origin, line_height, window, cx)
7493 .log_err();
7494 fragment_origin.x += line.width;
7495 }
7496 LineFragment::Element { size, .. } => {
7497 fragment_origin.x += size.width;
7498 }
7499 }
7500 }
7501 }
7502
7503 fn draw_invisibles(
7504 &self,
7505 selection_ranges: &[Range<DisplayPoint>],
7506 layout: &EditorLayout,
7507 content_origin: gpui::Point<Pixels>,
7508 line_y: Pixels,
7509 row: DisplayRow,
7510 line_height: Pixels,
7511 whitespace_setting: ShowWhitespaceSetting,
7512 window: &mut Window,
7513 cx: &mut App,
7514 ) {
7515 let extract_whitespace_info = |invisible: &Invisible| {
7516 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
7517 Invisible::Tab {
7518 line_start_offset,
7519 line_end_offset,
7520 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
7521 Invisible::Whitespace { line_offset } => {
7522 (*line_offset, line_offset + 1, &layout.space_invisible)
7523 }
7524 };
7525
7526 let x_offset = self.x_for_index(token_offset);
7527 let invisible_offset =
7528 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
7529 let origin = content_origin
7530 + gpui::point(
7531 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
7532 line_y,
7533 );
7534
7535 (
7536 [token_offset, token_end_offset],
7537 Box::new(move |window: &mut Window, cx: &mut App| {
7538 invisible_symbol
7539 .paint(origin, line_height, window, cx)
7540 .log_err();
7541 }),
7542 )
7543 };
7544
7545 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
7546 match whitespace_setting {
7547 ShowWhitespaceSetting::None => (),
7548 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
7549 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
7550 let invisible_point = DisplayPoint::new(row, start as u32);
7551 if !selection_ranges
7552 .iter()
7553 .any(|region| region.start <= invisible_point && invisible_point < region.end)
7554 {
7555 return;
7556 }
7557
7558 paint(window, cx);
7559 }),
7560
7561 ShowWhitespaceSetting::Trailing => {
7562 let mut previous_start = self.len;
7563 for ([start, end], paint) in invisible_iter.rev() {
7564 if previous_start != end {
7565 break;
7566 }
7567 previous_start = start;
7568 paint(window, cx);
7569 }
7570 }
7571
7572 // For a whitespace to be on a boundary, any of the following conditions need to be met:
7573 // - It is a tab
7574 // - It is adjacent to an edge (start or end)
7575 // - It is adjacent to a whitespace (left or right)
7576 ShowWhitespaceSetting::Boundary => {
7577 // We'll need to keep track of the last invisible we've seen and then check if we are adjacent to it for some of
7578 // the above cases.
7579 // Note: We zip in the original `invisibles` to check for tab equality
7580 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
7581 for (([start, end], paint), invisible) in
7582 invisible_iter.zip_eq(self.invisibles.iter())
7583 {
7584 let should_render = match (&last_seen, invisible) {
7585 (_, Invisible::Tab { .. }) => true,
7586 (Some((_, last_end, _)), _) => *last_end == start,
7587 _ => false,
7588 };
7589
7590 if should_render || start == 0 || end == self.len {
7591 paint(window, cx);
7592
7593 // Since we are scanning from the left, we will skip over the first available whitespace that is part
7594 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
7595 if let Some((should_render_last, last_end, paint_last)) = last_seen {
7596 // Note that we need to make sure that the last one is actually adjacent
7597 if !should_render_last && last_end == start {
7598 paint_last(window, cx);
7599 }
7600 }
7601 }
7602
7603 // Manually render anything within a selection
7604 let invisible_point = DisplayPoint::new(row, start as u32);
7605 if selection_ranges.iter().any(|region| {
7606 region.start <= invisible_point && invisible_point < region.end
7607 }) {
7608 paint(window, cx);
7609 }
7610
7611 last_seen = Some((should_render, end, paint));
7612 }
7613 }
7614 }
7615 }
7616
7617 pub fn x_for_index(&self, index: usize) -> Pixels {
7618 let mut fragment_start_x = Pixels::ZERO;
7619 let mut fragment_start_index = 0;
7620
7621 for fragment in &self.fragments {
7622 match fragment {
7623 LineFragment::Text(shaped_line) => {
7624 let fragment_end_index = fragment_start_index + shaped_line.len;
7625 if index < fragment_end_index {
7626 return fragment_start_x
7627 + shaped_line.x_for_index(index - fragment_start_index);
7628 }
7629 fragment_start_x += shaped_line.width;
7630 fragment_start_index = fragment_end_index;
7631 }
7632 LineFragment::Element { len, size, .. } => {
7633 let fragment_end_index = fragment_start_index + len;
7634 if index < fragment_end_index {
7635 return fragment_start_x;
7636 }
7637 fragment_start_x += size.width;
7638 fragment_start_index = fragment_end_index;
7639 }
7640 }
7641 }
7642
7643 fragment_start_x
7644 }
7645
7646 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
7647 let mut fragment_start_x = Pixels::ZERO;
7648 let mut fragment_start_index = 0;
7649
7650 for fragment in &self.fragments {
7651 match fragment {
7652 LineFragment::Text(shaped_line) => {
7653 let fragment_end_x = fragment_start_x + shaped_line.width;
7654 if x < fragment_end_x {
7655 return Some(
7656 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
7657 );
7658 }
7659 fragment_start_x = fragment_end_x;
7660 fragment_start_index += shaped_line.len;
7661 }
7662 LineFragment::Element { len, size, .. } => {
7663 let fragment_end_x = fragment_start_x + size.width;
7664 if x < fragment_end_x {
7665 return Some(fragment_start_index);
7666 }
7667 fragment_start_index += len;
7668 fragment_start_x = fragment_end_x;
7669 }
7670 }
7671 }
7672
7673 None
7674 }
7675
7676 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
7677 let mut fragment_start_index = 0;
7678
7679 for fragment in &self.fragments {
7680 match fragment {
7681 LineFragment::Text(shaped_line) => {
7682 let fragment_end_index = fragment_start_index + shaped_line.len;
7683 if index < fragment_end_index {
7684 return shaped_line.font_id_for_index(index - fragment_start_index);
7685 }
7686 fragment_start_index = fragment_end_index;
7687 }
7688 LineFragment::Element { len, .. } => {
7689 let fragment_end_index = fragment_start_index + len;
7690 if index < fragment_end_index {
7691 return None;
7692 }
7693 fragment_start_index = fragment_end_index;
7694 }
7695 }
7696 }
7697
7698 None
7699 }
7700}
7701
7702#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7703enum Invisible {
7704 /// A tab character
7705 ///
7706 /// A tab character is internally represented by spaces (configured by the user's tab width)
7707 /// aligned to the nearest column, so it's necessary to store the start and end offset for
7708 /// adjacency checks.
7709 Tab {
7710 line_start_offset: usize,
7711 line_end_offset: usize,
7712 },
7713 Whitespace {
7714 line_offset: usize,
7715 },
7716}
7717
7718impl EditorElement {
7719 /// Returns the rem size to use when rendering the [`EditorElement`].
7720 ///
7721 /// This allows UI elements to scale based on the `buffer_font_size`.
7722 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
7723 match self.editor.read(cx).mode {
7724 EditorMode::Full {
7725 scale_ui_elements_with_buffer_font_size: true,
7726 ..
7727 }
7728 | EditorMode::Minimap { .. } => {
7729 let buffer_font_size = self.style.text.font_size;
7730 match buffer_font_size {
7731 AbsoluteLength::Pixels(pixels) => {
7732 let rem_size_scale = {
7733 // Our default UI font size is 14px on a 16px base scale.
7734 // This means the default UI font size is 0.875rems.
7735 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
7736
7737 // We then determine the delta between a single rem and the default font
7738 // size scale.
7739 let default_font_size_delta = 1. - default_font_size_scale;
7740
7741 // Finally, we add this delta to 1rem to get the scale factor that
7742 // should be used to scale up the UI.
7743 1. + default_font_size_delta
7744 };
7745
7746 Some(pixels * rem_size_scale)
7747 }
7748 AbsoluteLength::Rems(rems) => {
7749 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
7750 }
7751 }
7752 }
7753 // We currently use single-line and auto-height editors in UI contexts,
7754 // so we don't want to scale everything with the buffer font size, as it
7755 // ends up looking off.
7756 _ => None,
7757 }
7758 }
7759
7760 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
7761 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
7762 parent.upgrade()
7763 } else {
7764 Some(self.editor.clone())
7765 }
7766 }
7767}
7768
7769impl Element for EditorElement {
7770 type RequestLayoutState = ();
7771 type PrepaintState = EditorLayout;
7772
7773 fn id(&self) -> Option<ElementId> {
7774 None
7775 }
7776
7777 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
7778 None
7779 }
7780
7781 fn request_layout(
7782 &mut self,
7783 _: Option<&GlobalElementId>,
7784 _inspector_id: Option<&gpui::InspectorElementId>,
7785 window: &mut Window,
7786 cx: &mut App,
7787 ) -> (gpui::LayoutId, ()) {
7788 let rem_size = self.rem_size(cx);
7789 window.with_rem_size(rem_size, |window| {
7790 self.editor.update(cx, |editor, cx| {
7791 editor.set_style(self.style.clone(), window, cx);
7792
7793 let layout_id = match editor.mode {
7794 EditorMode::SingleLine { auto_width } => {
7795 let rem_size = window.rem_size();
7796
7797 let height = self.style.text.line_height_in_pixels(rem_size);
7798 if auto_width {
7799 let editor_handle = cx.entity().clone();
7800 let style = self.style.clone();
7801 window.request_measured_layout(
7802 Style::default(),
7803 move |_, _, window, cx| {
7804 let editor_snapshot = editor_handle
7805 .update(cx, |editor, cx| editor.snapshot(window, cx));
7806 let line = Self::layout_lines(
7807 DisplayRow(0)..DisplayRow(1),
7808 &editor_snapshot,
7809 &style,
7810 px(f32::MAX),
7811 |_| false, // Single lines never soft wrap
7812 window,
7813 cx,
7814 )
7815 .pop()
7816 .unwrap();
7817
7818 let font_id =
7819 window.text_system().resolve_font(&style.text.font());
7820 let font_size =
7821 style.text.font_size.to_pixels(window.rem_size());
7822 let em_width =
7823 window.text_system().em_width(font_id, font_size).unwrap();
7824
7825 size(line.width + em_width, height)
7826 },
7827 )
7828 } else {
7829 let mut style = Style::default();
7830 style.size.height = height.into();
7831 style.size.width = relative(1.).into();
7832 window.request_layout(style, None, cx)
7833 }
7834 }
7835 EditorMode::AutoHeight {
7836 min_lines,
7837 max_lines,
7838 } => {
7839 let editor_handle = cx.entity().clone();
7840 let max_line_number_width =
7841 self.max_line_number_width(&editor.snapshot(window, cx), window);
7842 window.request_measured_layout(
7843 Style::default(),
7844 move |known_dimensions, available_space, window, cx| {
7845 editor_handle
7846 .update(cx, |editor, cx| {
7847 compute_auto_height_layout(
7848 editor,
7849 min_lines,
7850 max_lines,
7851 max_line_number_width,
7852 known_dimensions,
7853 available_space.width,
7854 window,
7855 cx,
7856 )
7857 })
7858 .unwrap_or_default()
7859 },
7860 )
7861 }
7862 EditorMode::Minimap { .. } => {
7863 let mut style = Style::default();
7864 style.size.width = relative(1.).into();
7865 style.size.height = relative(1.).into();
7866 window.request_layout(style, None, cx)
7867 }
7868 EditorMode::Full {
7869 sized_by_content, ..
7870 } => {
7871 let mut style = Style::default();
7872 style.size.width = relative(1.).into();
7873 if sized_by_content {
7874 let snapshot = editor.snapshot(window, cx);
7875 let line_height =
7876 self.style.text.line_height_in_pixels(window.rem_size());
7877 let scroll_height =
7878 (snapshot.max_point().row().next_row().0 as f32) * line_height;
7879 style.size.height = scroll_height.into();
7880 } else {
7881 style.size.height = relative(1.).into();
7882 }
7883 window.request_layout(style, None, cx)
7884 }
7885 };
7886
7887 (layout_id, ())
7888 })
7889 })
7890 }
7891
7892 fn prepaint(
7893 &mut self,
7894 _: Option<&GlobalElementId>,
7895 _inspector_id: Option<&gpui::InspectorElementId>,
7896 bounds: Bounds<Pixels>,
7897 _: &mut Self::RequestLayoutState,
7898 window: &mut Window,
7899 cx: &mut App,
7900 ) -> Self::PrepaintState {
7901 let text_style = TextStyleRefinement {
7902 font_size: Some(self.style.text.font_size),
7903 line_height: Some(self.style.text.line_height),
7904 ..Default::default()
7905 };
7906 let focus_handle = self.editor.focus_handle(cx);
7907 window.set_view_id(self.editor.entity_id());
7908 window.set_focus_handle(&focus_handle, cx);
7909
7910 let rem_size = self.rem_size(cx);
7911 window.with_rem_size(rem_size, |window| {
7912 window.with_text_style(Some(text_style), |window| {
7913 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7914 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
7915 (editor.snapshot(window, cx), editor.read_only(cx))
7916 });
7917 let style = self.style.clone();
7918
7919 let rem_size = window.rem_size();
7920 let font_id = window.text_system().resolve_font(&style.text.font());
7921 let font_size = style.text.font_size.to_pixels(rem_size);
7922 let line_height = style.text.line_height_in_pixels(rem_size);
7923 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
7924 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
7925 let glyph_grid_cell = size(em_advance, line_height);
7926
7927 let gutter_dimensions = snapshot
7928 .gutter_dimensions(
7929 font_id,
7930 font_size,
7931 self.max_line_number_width(&snapshot, window),
7932 cx,
7933 )
7934 .or_else(|| {
7935 self.editor.read(cx).offset_content.then(|| {
7936 GutterDimensions::default_with_margin(font_id, font_size, cx)
7937 })
7938 })
7939 .unwrap_or_default();
7940 let text_width = bounds.size.width - gutter_dimensions.width;
7941
7942 let settings = EditorSettings::get_global(cx);
7943 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
7944 let vertical_scrollbar_width = (scrollbars_shown
7945 && settings.scrollbar.axes.vertical
7946 && self.editor.read(cx).show_scrollbars.vertical)
7947 .then_some(style.scrollbar_width)
7948 .unwrap_or_default();
7949 let minimap_width = self
7950 .get_minimap_width(
7951 &settings.minimap,
7952 scrollbars_shown,
7953 text_width,
7954 em_width,
7955 font_size,
7956 rem_size,
7957 cx,
7958 )
7959 .unwrap_or_default();
7960
7961 let right_margin = minimap_width + vertical_scrollbar_width;
7962
7963 let editor_width =
7964 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
7965 let editor_margins = EditorMargins {
7966 gutter: gutter_dimensions,
7967 right: right_margin,
7968 };
7969
7970 // Offset the content_bounds from the text_bounds by the gutter margin (which
7971 // is roughly half a character wide) to make hit testing work more like how we want.
7972 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
7973
7974 let editor_content_width = editor_width - content_offset.x;
7975
7976 snapshot = self.editor.update(cx, |editor, cx| {
7977 editor.last_bounds = Some(bounds);
7978 editor.gutter_dimensions = gutter_dimensions;
7979 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
7980 editor.set_visible_column_count(editor_content_width / em_advance);
7981
7982 if matches!(
7983 editor.mode,
7984 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
7985 ) {
7986 snapshot
7987 } else {
7988 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
7989 let wrap_width = match editor.soft_wrap_mode(cx) {
7990 SoftWrap::GitDiff => None,
7991 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
7992 SoftWrap::EditorWidth => Some(editor_content_width),
7993 SoftWrap::Column(column) => Some(wrap_width_for(column)),
7994 SoftWrap::Bounded(column) => {
7995 Some(editor_content_width.min(wrap_width_for(column)))
7996 }
7997 };
7998
7999 if editor.set_wrap_width(wrap_width, cx) {
8000 editor.snapshot(window, cx)
8001 } else {
8002 snapshot
8003 }
8004 }
8005 });
8006
8007 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
8008 let gutter_hitbox = window.insert_hitbox(
8009 gutter_bounds(bounds, gutter_dimensions),
8010 HitboxBehavior::Normal,
8011 );
8012 let text_hitbox = window.insert_hitbox(
8013 Bounds {
8014 origin: gutter_hitbox.top_right(),
8015 size: size(text_width, bounds.size.height),
8016 },
8017 HitboxBehavior::Normal,
8018 );
8019
8020 let content_origin = text_hitbox.origin + content_offset;
8021
8022 let editor_text_bounds =
8023 Bounds::from_corners(content_origin, bounds.bottom_right());
8024
8025 let height_in_lines = editor_text_bounds.size.height / line_height;
8026
8027 let max_row = snapshot.max_point().row().as_f32();
8028
8029 // The max scroll position for the top of the window
8030 let max_scroll_top = if matches!(
8031 snapshot.mode,
8032 EditorMode::SingleLine { .. }
8033 | EditorMode::AutoHeight { .. }
8034 | EditorMode::Full {
8035 sized_by_content: true,
8036 ..
8037 }
8038 ) {
8039 (max_row - height_in_lines + 1.).max(0.)
8040 } else {
8041 let settings = EditorSettings::get_global(cx);
8042 match settings.scroll_beyond_last_line {
8043 ScrollBeyondLastLine::OnePage => max_row,
8044 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
8045 ScrollBeyondLastLine::VerticalScrollMargin => {
8046 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
8047 .max(0.)
8048 }
8049 }
8050 };
8051
8052 let (
8053 autoscroll_request,
8054 autoscroll_containing_element,
8055 needs_horizontal_autoscroll,
8056 ) = self.editor.update(cx, |editor, cx| {
8057 let autoscroll_request = editor.autoscroll_request();
8058 let autoscroll_containing_element =
8059 autoscroll_request.is_some() || editor.has_pending_selection();
8060
8061 let (needs_horizontal_autoscroll, was_scrolled) = editor
8062 .autoscroll_vertically(bounds, line_height, max_scroll_top, window, cx);
8063 if was_scrolled.0 {
8064 snapshot = editor.snapshot(window, cx);
8065 }
8066 (
8067 autoscroll_request,
8068 autoscroll_containing_element,
8069 needs_horizontal_autoscroll,
8070 )
8071 });
8072
8073 let mut scroll_position = snapshot.scroll_position();
8074 // The scroll position is a fractional point, the whole number of which represents
8075 // the top of the window in terms of display rows.
8076 let start_row = DisplayRow(scroll_position.y as u32);
8077 let max_row = snapshot.max_point().row();
8078 let end_row = cmp::min(
8079 (scroll_position.y + height_in_lines).ceil() as u32,
8080 max_row.next_row().0,
8081 );
8082 let end_row = DisplayRow(end_row);
8083
8084 let row_infos = snapshot
8085 .row_infos(start_row)
8086 .take((start_row..end_row).len())
8087 .collect::<Vec<RowInfo>>();
8088 let is_row_soft_wrapped = |row: usize| {
8089 row_infos
8090 .get(row)
8091 .map_or(true, |info| info.buffer_row.is_none())
8092 };
8093
8094 let start_anchor = if start_row == Default::default() {
8095 Anchor::min()
8096 } else {
8097 snapshot.buffer_snapshot.anchor_before(
8098 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
8099 )
8100 };
8101 let end_anchor = if end_row > max_row {
8102 Anchor::max()
8103 } else {
8104 snapshot.buffer_snapshot.anchor_before(
8105 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
8106 )
8107 };
8108
8109 let mut highlighted_rows = self
8110 .editor
8111 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
8112
8113 let is_light = cx.theme().appearance().is_light();
8114
8115 for (ix, row_info) in row_infos.iter().enumerate() {
8116 let Some(diff_status) = row_info.diff_status else {
8117 continue;
8118 };
8119
8120 let background_color = match diff_status.kind {
8121 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
8122 DiffHunkStatusKind::Deleted => {
8123 cx.theme().colors().version_control_deleted
8124 }
8125 DiffHunkStatusKind::Modified => {
8126 debug_panic!("modified diff status for row info");
8127 continue;
8128 }
8129 };
8130
8131 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
8132
8133 let hollow_highlight = LineHighlight {
8134 background: (background_color.opacity(if is_light {
8135 0.08
8136 } else {
8137 0.06
8138 }))
8139 .into(),
8140 border: Some(if is_light {
8141 background_color.opacity(0.48)
8142 } else {
8143 background_color.opacity(0.36)
8144 }),
8145 include_gutter: true,
8146 type_id: None,
8147 };
8148
8149 let filled_highlight = LineHighlight {
8150 background: solid_background(background_color.opacity(hunk_opacity)),
8151 border: None,
8152 include_gutter: true,
8153 type_id: None,
8154 };
8155
8156 let background = if Self::diff_hunk_hollow(diff_status, cx) {
8157 hollow_highlight
8158 } else {
8159 filled_highlight
8160 };
8161
8162 highlighted_rows
8163 .entry(start_row + DisplayRow(ix as u32))
8164 .or_insert(background);
8165 }
8166
8167 let highlighted_ranges = self
8168 .editor_with_selections(cx)
8169 .map(|editor| {
8170 editor.read(cx).background_highlights_in_range(
8171 start_anchor..end_anchor,
8172 &snapshot.display_snapshot,
8173 cx.theme(),
8174 )
8175 })
8176 .unwrap_or_default();
8177 let highlighted_gutter_ranges =
8178 self.editor.read(cx).gutter_highlights_in_range(
8179 start_anchor..end_anchor,
8180 &snapshot.display_snapshot,
8181 cx,
8182 );
8183
8184 let document_colors = self
8185 .editor
8186 .read(cx)
8187 .colors
8188 .as_ref()
8189 .map(|colors| colors.editor_display_highlights(&snapshot));
8190 let redacted_ranges = self.editor.read(cx).redacted_ranges(
8191 start_anchor..end_anchor,
8192 &snapshot.display_snapshot,
8193 cx,
8194 );
8195
8196 let (local_selections, selected_buffer_ids): (
8197 Vec<Selection<Point>>,
8198 Vec<BufferId>,
8199 ) = self
8200 .editor_with_selections(cx)
8201 .map(|editor| {
8202 editor.update(cx, |editor, cx| {
8203 let all_selections = editor.selections.all::<Point>(cx);
8204 let selected_buffer_ids = if editor.is_singleton(cx) {
8205 Vec::new()
8206 } else {
8207 let mut selected_buffer_ids =
8208 Vec::with_capacity(all_selections.len());
8209
8210 for selection in all_selections {
8211 for buffer_id in snapshot
8212 .buffer_snapshot
8213 .buffer_ids_for_range(selection.range())
8214 {
8215 if selected_buffer_ids.last() != Some(&buffer_id) {
8216 selected_buffer_ids.push(buffer_id);
8217 }
8218 }
8219 }
8220
8221 selected_buffer_ids
8222 };
8223
8224 let mut selections = editor
8225 .selections
8226 .disjoint_in_range(start_anchor..end_anchor, cx);
8227 selections.extend(editor.selections.pending(cx));
8228
8229 (selections, selected_buffer_ids)
8230 })
8231 })
8232 .unwrap_or_default();
8233
8234 let (selections, mut active_rows, newest_selection_head) = self
8235 .layout_selections(
8236 start_anchor,
8237 end_anchor,
8238 &local_selections,
8239 &snapshot,
8240 start_row,
8241 end_row,
8242 window,
8243 cx,
8244 );
8245 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
8246 editor.active_breakpoints(start_row..end_row, window, cx)
8247 });
8248 for (display_row, (_, bp, state)) in &breakpoint_rows {
8249 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
8250 active_rows.entry(*display_row).or_default().breakpoint = true;
8251 }
8252 }
8253
8254 let line_numbers = self.layout_line_numbers(
8255 Some(&gutter_hitbox),
8256 gutter_dimensions,
8257 line_height,
8258 scroll_position,
8259 start_row..end_row,
8260 &row_infos,
8261 &active_rows,
8262 newest_selection_head,
8263 &snapshot,
8264 window,
8265 cx,
8266 );
8267
8268 // We add the gutter breakpoint indicator to breakpoint_rows after painting
8269 // line numbers so we don't paint a line number debug accent color if a user
8270 // has their mouse over that line when a breakpoint isn't there
8271 self.editor.update(cx, |editor, _| {
8272 if let Some(phantom_breakpoint) = &mut editor
8273 .gutter_breakpoint_indicator
8274 .0
8275 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
8276 {
8277 // Is there a non-phantom breakpoint on this line?
8278 phantom_breakpoint.collides_with_existing_breakpoint = true;
8279 breakpoint_rows
8280 .entry(phantom_breakpoint.display_row)
8281 .or_insert_with(|| {
8282 let position = snapshot.display_point_to_anchor(
8283 DisplayPoint::new(phantom_breakpoint.display_row, 0),
8284 Bias::Right,
8285 );
8286 let breakpoint = Breakpoint::new_standard();
8287 phantom_breakpoint.collides_with_existing_breakpoint = false;
8288 (position, breakpoint, None)
8289 });
8290 }
8291 });
8292
8293 let mut expand_toggles =
8294 window.with_element_namespace("expand_toggles", |window| {
8295 self.layout_expand_toggles(
8296 &gutter_hitbox,
8297 gutter_dimensions,
8298 em_width,
8299 line_height,
8300 scroll_position,
8301 &row_infos,
8302 window,
8303 cx,
8304 )
8305 });
8306
8307 let mut crease_toggles =
8308 window.with_element_namespace("crease_toggles", |window| {
8309 self.layout_crease_toggles(
8310 start_row..end_row,
8311 &row_infos,
8312 &active_rows,
8313 &snapshot,
8314 window,
8315 cx,
8316 )
8317 });
8318 let crease_trailers =
8319 window.with_element_namespace("crease_trailers", |window| {
8320 self.layout_crease_trailers(
8321 row_infos.iter().copied(),
8322 &snapshot,
8323 window,
8324 cx,
8325 )
8326 });
8327
8328 let display_hunks = self.layout_gutter_diff_hunks(
8329 line_height,
8330 &gutter_hitbox,
8331 start_row..end_row,
8332 &snapshot,
8333 window,
8334 cx,
8335 );
8336
8337 let mut line_layouts = Self::layout_lines(
8338 start_row..end_row,
8339 &snapshot,
8340 &self.style,
8341 editor_width,
8342 is_row_soft_wrapped,
8343 window,
8344 cx,
8345 );
8346 let new_renrerer_widths = line_layouts
8347 .iter()
8348 .flat_map(|layout| &layout.fragments)
8349 .filter_map(|fragment| {
8350 if let LineFragment::Element { id, size, .. } = fragment {
8351 Some((*id, size.width))
8352 } else {
8353 None
8354 }
8355 });
8356 if self.editor.update(cx, |editor, cx| {
8357 editor.update_renderer_widths(new_renrerer_widths, cx)
8358 }) {
8359 // If the fold widths have changed, we need to prepaint
8360 // the element again to account for any changes in
8361 // wrapping.
8362 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8363 }
8364
8365 let longest_line_blame_width = self
8366 .editor
8367 .update(cx, |editor, cx| {
8368 if !editor.show_git_blame_inline {
8369 return None;
8370 }
8371 let blame = editor.blame.as_ref()?;
8372 let blame_entry = blame
8373 .update(cx, |blame, cx| {
8374 let row_infos =
8375 snapshot.row_infos(snapshot.longest_row()).next()?;
8376 blame.blame_for_rows(&[row_infos], cx).next()
8377 })
8378 .flatten()?;
8379 let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
8380 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
8381 Some(
8382 element
8383 .layout_as_root(AvailableSpace::min_size(), window, cx)
8384 .width
8385 + inline_blame_padding,
8386 )
8387 })
8388 .unwrap_or(Pixels::ZERO);
8389
8390 let longest_line_width = layout_line(
8391 snapshot.longest_row(),
8392 &snapshot,
8393 &style,
8394 editor_width,
8395 is_row_soft_wrapped,
8396 window,
8397 cx,
8398 )
8399 .width;
8400
8401 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
8402 text_hitbox.bounds,
8403 glyph_grid_cell,
8404 size(longest_line_width, max_row.as_f32() * line_height),
8405 longest_line_blame_width,
8406 editor_width,
8407 EditorSettings::get_global(cx),
8408 );
8409
8410 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
8411
8412 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
8413 snapshot.sticky_header_excerpt(scroll_position.y)
8414 } else {
8415 None
8416 };
8417 let sticky_header_excerpt_id =
8418 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
8419
8420 let blocks = window.with_element_namespace("blocks", |window| {
8421 self.render_blocks(
8422 start_row..end_row,
8423 &snapshot,
8424 &hitbox,
8425 &text_hitbox,
8426 editor_width,
8427 &mut scroll_width,
8428 &editor_margins,
8429 em_width,
8430 gutter_dimensions.full_width(),
8431 line_height,
8432 &mut line_layouts,
8433 &local_selections,
8434 &selected_buffer_ids,
8435 is_row_soft_wrapped,
8436 sticky_header_excerpt_id,
8437 window,
8438 cx,
8439 )
8440 });
8441 let (mut blocks, row_block_types) = match blocks {
8442 Ok(blocks) => blocks,
8443 Err(resized_blocks) => {
8444 self.editor.update(cx, |editor, cx| {
8445 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
8446 });
8447 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8448 }
8449 };
8450
8451 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
8452 window.with_element_namespace("blocks", |window| {
8453 self.layout_sticky_buffer_header(
8454 sticky_header_excerpt,
8455 scroll_position.y,
8456 line_height,
8457 right_margin,
8458 &snapshot,
8459 &hitbox,
8460 &selected_buffer_ids,
8461 &blocks,
8462 window,
8463 cx,
8464 )
8465 })
8466 });
8467
8468 let start_buffer_row =
8469 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
8470 let end_buffer_row =
8471 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
8472
8473 let scroll_max = point(
8474 ((scroll_width - editor_content_width) / em_advance).max(0.0),
8475 max_scroll_top,
8476 );
8477
8478 self.editor.update(cx, |editor, cx| {
8479 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
8480 scroll_position.x = scroll_position.x.min(scroll_max.x);
8481 }
8482
8483 if needs_horizontal_autoscroll.0
8484 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
8485 start_row,
8486 editor_content_width,
8487 scroll_width,
8488 em_advance,
8489 &line_layouts,
8490 window,
8491 cx,
8492 )
8493 {
8494 scroll_position = new_scroll_position;
8495 }
8496 });
8497
8498 let scroll_pixel_position = point(
8499 scroll_position.x * em_advance,
8500 scroll_position.y * line_height,
8501 );
8502 let indent_guides = self.layout_indent_guides(
8503 content_origin,
8504 text_hitbox.origin,
8505 start_buffer_row..end_buffer_row,
8506 scroll_pixel_position,
8507 line_height,
8508 &snapshot,
8509 window,
8510 cx,
8511 );
8512
8513 let crease_trailers =
8514 window.with_element_namespace("crease_trailers", |window| {
8515 self.prepaint_crease_trailers(
8516 crease_trailers,
8517 &line_layouts,
8518 line_height,
8519 content_origin,
8520 scroll_pixel_position,
8521 em_width,
8522 window,
8523 cx,
8524 )
8525 });
8526
8527 let (inline_completion_popover, inline_completion_popover_origin) = self
8528 .editor
8529 .update(cx, |editor, cx| {
8530 editor.render_edit_prediction_popover(
8531 &text_hitbox.bounds,
8532 content_origin,
8533 right_margin,
8534 &snapshot,
8535 start_row..end_row,
8536 scroll_position.y,
8537 scroll_position.y + height_in_lines,
8538 &line_layouts,
8539 line_height,
8540 scroll_pixel_position,
8541 newest_selection_head,
8542 editor_width,
8543 &style,
8544 window,
8545 cx,
8546 )
8547 })
8548 .unzip();
8549
8550 let mut inline_diagnostics = self.layout_inline_diagnostics(
8551 &line_layouts,
8552 &crease_trailers,
8553 &row_block_types,
8554 content_origin,
8555 scroll_pixel_position,
8556 inline_completion_popover_origin,
8557 start_row,
8558 end_row,
8559 line_height,
8560 em_width,
8561 &style,
8562 window,
8563 cx,
8564 );
8565
8566 let mut inline_blame_layout = None;
8567 let mut inline_code_actions = None;
8568 if let Some(newest_selection_head) = newest_selection_head {
8569 let display_row = newest_selection_head.row();
8570 if (start_row..end_row).contains(&display_row)
8571 && !row_block_types.contains_key(&display_row)
8572 {
8573 inline_code_actions = self.layout_inline_code_actions(
8574 newest_selection_head,
8575 content_origin,
8576 scroll_pixel_position,
8577 line_height,
8578 &snapshot,
8579 window,
8580 cx,
8581 );
8582
8583 let line_ix = display_row.minus(start_row) as usize;
8584 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
8585 row_infos.get(line_ix),
8586 line_layouts.get(line_ix),
8587 crease_trailers.get(line_ix),
8588 ) {
8589 let crease_trailer_layout = crease_trailer.as_ref();
8590 if let Some(layout) = self.layout_inline_blame(
8591 display_row,
8592 row_info,
8593 line_layout,
8594 crease_trailer_layout,
8595 em_width,
8596 content_origin,
8597 scroll_pixel_position,
8598 line_height,
8599 &text_hitbox,
8600 window,
8601 cx,
8602 ) {
8603 inline_blame_layout = Some(layout);
8604 // Blame overrides inline diagnostics
8605 inline_diagnostics.remove(&display_row);
8606 }
8607 } else {
8608 log::error!(
8609 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
8610 line_layouts.len(): {}, \
8611 crease_trailers.len(): {}",
8612 line_ix,
8613 row_infos.len(),
8614 line_layouts.len(),
8615 crease_trailers.len(),
8616 );
8617 }
8618 }
8619 }
8620
8621 let blamed_display_rows = self.layout_blame_entries(
8622 &row_infos,
8623 em_width,
8624 scroll_position,
8625 line_height,
8626 &gutter_hitbox,
8627 gutter_dimensions.git_blame_entries_width,
8628 window,
8629 cx,
8630 );
8631
8632 let line_elements = self.prepaint_lines(
8633 start_row,
8634 &mut line_layouts,
8635 line_height,
8636 scroll_pixel_position,
8637 content_origin,
8638 window,
8639 cx,
8640 );
8641
8642 window.with_element_namespace("blocks", |window| {
8643 self.layout_blocks(
8644 &mut blocks,
8645 &hitbox,
8646 line_height,
8647 scroll_pixel_position,
8648 window,
8649 cx,
8650 );
8651 });
8652
8653 let cursors = self.collect_cursors(&snapshot, cx);
8654 let visible_row_range = start_row..end_row;
8655 let non_visible_cursors = cursors
8656 .iter()
8657 .any(|c| !visible_row_range.contains(&c.0.row()));
8658
8659 let visible_cursors = self.layout_visible_cursors(
8660 &snapshot,
8661 &selections,
8662 &row_block_types,
8663 start_row..end_row,
8664 &line_layouts,
8665 &text_hitbox,
8666 content_origin,
8667 scroll_position,
8668 scroll_pixel_position,
8669 line_height,
8670 em_width,
8671 em_advance,
8672 autoscroll_containing_element,
8673 window,
8674 cx,
8675 );
8676
8677 let scrollbars_layout = self.layout_scrollbars(
8678 &snapshot,
8679 &scrollbar_layout_information,
8680 content_offset,
8681 scroll_position,
8682 non_visible_cursors,
8683 right_margin,
8684 editor_width,
8685 window,
8686 cx,
8687 );
8688
8689 let gutter_settings = EditorSettings::get_global(cx).gutter;
8690
8691 let context_menu_layout =
8692 if let Some(newest_selection_head) = newest_selection_head {
8693 let newest_selection_point =
8694 newest_selection_head.to_point(&snapshot.display_snapshot);
8695 if (start_row..end_row).contains(&newest_selection_head.row()) {
8696 self.layout_cursor_popovers(
8697 line_height,
8698 &text_hitbox,
8699 content_origin,
8700 right_margin,
8701 start_row,
8702 scroll_pixel_position,
8703 &line_layouts,
8704 newest_selection_head,
8705 newest_selection_point,
8706 &style,
8707 window,
8708 cx,
8709 )
8710 } else {
8711 None
8712 }
8713 } else {
8714 None
8715 };
8716
8717 self.layout_gutter_menu(
8718 line_height,
8719 &text_hitbox,
8720 content_origin,
8721 right_margin,
8722 scroll_pixel_position,
8723 gutter_dimensions.width - gutter_dimensions.left_padding,
8724 window,
8725 cx,
8726 );
8727
8728 let test_indicators = if gutter_settings.runnables {
8729 self.layout_run_indicators(
8730 line_height,
8731 start_row..end_row,
8732 &row_infos,
8733 scroll_pixel_position,
8734 &gutter_dimensions,
8735 &gutter_hitbox,
8736 &display_hunks,
8737 &snapshot,
8738 &mut breakpoint_rows,
8739 window,
8740 cx,
8741 )
8742 } else {
8743 Vec::new()
8744 };
8745
8746 let show_breakpoints = snapshot
8747 .show_breakpoints
8748 .unwrap_or(gutter_settings.breakpoints);
8749 let breakpoints = if show_breakpoints {
8750 self.layout_breakpoints(
8751 line_height,
8752 start_row..end_row,
8753 scroll_pixel_position,
8754 &gutter_dimensions,
8755 &gutter_hitbox,
8756 &display_hunks,
8757 &snapshot,
8758 breakpoint_rows,
8759 &row_infos,
8760 window,
8761 cx,
8762 )
8763 } else {
8764 Vec::new()
8765 };
8766
8767 self.layout_signature_help(
8768 &hitbox,
8769 content_origin,
8770 scroll_pixel_position,
8771 newest_selection_head,
8772 start_row,
8773 &line_layouts,
8774 line_height,
8775 em_width,
8776 context_menu_layout,
8777 window,
8778 cx,
8779 );
8780
8781 if !cx.has_active_drag() {
8782 self.layout_hover_popovers(
8783 &snapshot,
8784 &hitbox,
8785 start_row..end_row,
8786 content_origin,
8787 scroll_pixel_position,
8788 &line_layouts,
8789 line_height,
8790 em_width,
8791 context_menu_layout,
8792 window,
8793 cx,
8794 );
8795 }
8796
8797 let mouse_context_menu = self.layout_mouse_context_menu(
8798 &snapshot,
8799 start_row..end_row,
8800 content_origin,
8801 window,
8802 cx,
8803 );
8804
8805 window.with_element_namespace("crease_toggles", |window| {
8806 self.prepaint_crease_toggles(
8807 &mut crease_toggles,
8808 line_height,
8809 &gutter_dimensions,
8810 gutter_settings,
8811 scroll_pixel_position,
8812 &gutter_hitbox,
8813 window,
8814 cx,
8815 )
8816 });
8817
8818 window.with_element_namespace("expand_toggles", |window| {
8819 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
8820 });
8821
8822 let wrap_guides = self.layout_wrap_guides(
8823 em_advance,
8824 scroll_position,
8825 content_origin,
8826 scrollbars_layout.as_ref(),
8827 vertical_scrollbar_width,
8828 &hitbox,
8829 window,
8830 cx,
8831 );
8832
8833 let minimap = window.with_element_namespace("minimap", |window| {
8834 self.layout_minimap(
8835 &snapshot,
8836 minimap_width,
8837 scroll_position,
8838 &scrollbar_layout_information,
8839 scrollbars_layout.as_ref(),
8840 window,
8841 cx,
8842 )
8843 });
8844
8845 let invisible_symbol_font_size = font_size / 2.;
8846 let tab_invisible = window.text_system().shape_line(
8847 "→".into(),
8848 invisible_symbol_font_size,
8849 &[TextRun {
8850 len: "→".len(),
8851 font: self.style.text.font(),
8852 color: cx.theme().colors().editor_invisible,
8853 background_color: None,
8854 underline: None,
8855 strikethrough: None,
8856 }],
8857 None,
8858 );
8859 let space_invisible = window.text_system().shape_line(
8860 "•".into(),
8861 invisible_symbol_font_size,
8862 &[TextRun {
8863 len: "•".len(),
8864 font: self.style.text.font(),
8865 color: cx.theme().colors().editor_invisible,
8866 background_color: None,
8867 underline: None,
8868 strikethrough: None,
8869 }],
8870 None,
8871 );
8872
8873 let mode = snapshot.mode.clone();
8874
8875 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
8876 (vec![], vec![])
8877 } else {
8878 self.layout_diff_hunk_controls(
8879 start_row..end_row,
8880 &row_infos,
8881 &text_hitbox,
8882 newest_selection_head,
8883 line_height,
8884 right_margin,
8885 scroll_pixel_position,
8886 &display_hunks,
8887 &highlighted_rows,
8888 self.editor.clone(),
8889 window,
8890 cx,
8891 )
8892 };
8893
8894 let position_map = Rc::new(PositionMap {
8895 size: bounds.size,
8896 visible_row_range,
8897 scroll_pixel_position,
8898 scroll_max,
8899 line_layouts,
8900 line_height,
8901 em_width,
8902 em_advance,
8903 snapshot,
8904 gutter_hitbox: gutter_hitbox.clone(),
8905 text_hitbox: text_hitbox.clone(),
8906 inline_blame_bounds: inline_blame_layout
8907 .as_ref()
8908 .map(|layout| (layout.bounds, layout.entry.clone())),
8909 display_hunks: display_hunks.clone(),
8910 diff_hunk_control_bounds: diff_hunk_control_bounds.clone(),
8911 });
8912
8913 self.editor.update(cx, |editor, _| {
8914 editor.last_position_map = Some(position_map.clone())
8915 });
8916
8917 EditorLayout {
8918 mode,
8919 position_map,
8920 visible_display_row_range: start_row..end_row,
8921 wrap_guides,
8922 indent_guides,
8923 hitbox,
8924 gutter_hitbox,
8925 display_hunks,
8926 content_origin,
8927 scrollbars_layout,
8928 minimap,
8929 active_rows,
8930 highlighted_rows,
8931 highlighted_ranges,
8932 highlighted_gutter_ranges,
8933 redacted_ranges,
8934 document_colors,
8935 line_elements,
8936 line_numbers,
8937 blamed_display_rows,
8938 inline_diagnostics,
8939 inline_blame_layout,
8940 inline_code_actions,
8941 blocks,
8942 cursors,
8943 visible_cursors,
8944 selections,
8945 inline_completion_popover,
8946 diff_hunk_controls,
8947 mouse_context_menu,
8948 test_indicators,
8949 breakpoints,
8950 crease_toggles,
8951 crease_trailers,
8952 tab_invisible,
8953 space_invisible,
8954 sticky_buffer_header,
8955 expand_toggles,
8956 }
8957 })
8958 })
8959 })
8960 }
8961
8962 fn paint(
8963 &mut self,
8964 _: Option<&GlobalElementId>,
8965 _inspector_id: Option<&gpui::InspectorElementId>,
8966 bounds: Bounds<gpui::Pixels>,
8967 _: &mut Self::RequestLayoutState,
8968 layout: &mut Self::PrepaintState,
8969 window: &mut Window,
8970 cx: &mut App,
8971 ) {
8972 let focus_handle = self.editor.focus_handle(cx);
8973 let key_context = self
8974 .editor
8975 .update(cx, |editor, cx| editor.key_context(window, cx));
8976
8977 window.set_key_context(key_context);
8978 window.handle_input(
8979 &focus_handle,
8980 ElementInputHandler::new(bounds, self.editor.clone()),
8981 cx,
8982 );
8983 self.register_actions(window, cx);
8984 self.register_key_listeners(window, cx, layout);
8985
8986 let text_style = TextStyleRefinement {
8987 font_size: Some(self.style.text.font_size),
8988 line_height: Some(self.style.text.line_height),
8989 ..Default::default()
8990 };
8991 let rem_size = self.rem_size(cx);
8992 window.with_rem_size(rem_size, |window| {
8993 window.with_text_style(Some(text_style), |window| {
8994 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8995 self.paint_mouse_listeners(layout, window, cx);
8996 self.paint_background(layout, window, cx);
8997 self.paint_indent_guides(layout, window, cx);
8998
8999 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9000 self.paint_blamed_display_rows(layout, window, cx);
9001 self.paint_line_numbers(layout, window, cx);
9002 }
9003
9004 self.paint_text(layout, window, cx);
9005
9006 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9007 self.paint_gutter_highlights(layout, window, cx);
9008 self.paint_gutter_indicators(layout, window, cx);
9009 }
9010
9011 if !layout.blocks.is_empty() {
9012 window.with_element_namespace("blocks", |window| {
9013 self.paint_blocks(layout, window, cx);
9014 });
9015 }
9016
9017 window.with_element_namespace("blocks", |window| {
9018 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
9019 sticky_header.paint(window, cx)
9020 }
9021 });
9022
9023 self.paint_minimap(layout, window, cx);
9024 self.paint_scrollbars(layout, window, cx);
9025 self.paint_inline_completion_popover(layout, window, cx);
9026 self.paint_mouse_context_menu(layout, window, cx);
9027 });
9028 })
9029 })
9030 }
9031}
9032
9033pub(super) fn gutter_bounds(
9034 editor_bounds: Bounds<Pixels>,
9035 gutter_dimensions: GutterDimensions,
9036) -> Bounds<Pixels> {
9037 Bounds {
9038 origin: editor_bounds.origin,
9039 size: size(gutter_dimensions.width, editor_bounds.size.height),
9040 }
9041}
9042
9043#[derive(Clone, Copy)]
9044struct ContextMenuLayout {
9045 y_flipped: bool,
9046 bounds: Bounds<Pixels>,
9047}
9048
9049/// Holds information required for layouting the editor scrollbars.
9050struct ScrollbarLayoutInformation {
9051 /// The bounds of the editor area (excluding the content offset).
9052 editor_bounds: Bounds<Pixels>,
9053 /// The available range to scroll within the document.
9054 scroll_range: Size<Pixels>,
9055 /// The space available for one glyph in the editor.
9056 glyph_grid_cell: Size<Pixels>,
9057}
9058
9059impl ScrollbarLayoutInformation {
9060 pub fn new(
9061 editor_bounds: Bounds<Pixels>,
9062 glyph_grid_cell: Size<Pixels>,
9063 document_size: Size<Pixels>,
9064 longest_line_blame_width: Pixels,
9065 editor_width: Pixels,
9066 settings: &EditorSettings,
9067 ) -> Self {
9068 let vertical_overscroll = match settings.scroll_beyond_last_line {
9069 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
9070 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
9071 ScrollBeyondLastLine::VerticalScrollMargin => {
9072 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
9073 }
9074 };
9075
9076 let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
9077 glyph_grid_cell.width
9078 } else {
9079 px(0.0)
9080 };
9081
9082 let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
9083
9084 let scroll_range = document_size + overscroll;
9085
9086 ScrollbarLayoutInformation {
9087 editor_bounds,
9088 scroll_range,
9089 glyph_grid_cell,
9090 }
9091 }
9092}
9093
9094impl IntoElement for EditorElement {
9095 type Element = Self;
9096
9097 fn into_element(self) -> Self::Element {
9098 self
9099 }
9100}
9101
9102pub struct EditorLayout {
9103 position_map: Rc<PositionMap>,
9104 hitbox: Hitbox,
9105 gutter_hitbox: Hitbox,
9106 content_origin: gpui::Point<Pixels>,
9107 scrollbars_layout: Option<EditorScrollbars>,
9108 minimap: Option<MinimapLayout>,
9109 mode: EditorMode,
9110 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
9111 indent_guides: Option<Vec<IndentGuideLayout>>,
9112 visible_display_row_range: Range<DisplayRow>,
9113 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
9114 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
9115 line_elements: SmallVec<[AnyElement; 1]>,
9116 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
9117 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9118 blamed_display_rows: Option<Vec<AnyElement>>,
9119 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
9120 inline_blame_layout: Option<InlineBlameLayout>,
9121 inline_code_actions: Option<AnyElement>,
9122 blocks: Vec<BlockLayout>,
9123 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9124 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9125 redacted_ranges: Vec<Range<DisplayPoint>>,
9126 cursors: Vec<(DisplayPoint, Hsla)>,
9127 visible_cursors: Vec<CursorLayout>,
9128 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
9129 test_indicators: Vec<AnyElement>,
9130 breakpoints: Vec<AnyElement>,
9131 crease_toggles: Vec<Option<AnyElement>>,
9132 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
9133 diff_hunk_controls: Vec<AnyElement>,
9134 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
9135 inline_completion_popover: Option<AnyElement>,
9136 mouse_context_menu: Option<AnyElement>,
9137 tab_invisible: ShapedLine,
9138 space_invisible: ShapedLine,
9139 sticky_buffer_header: Option<AnyElement>,
9140 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
9141}
9142
9143impl EditorLayout {
9144 fn line_end_overshoot(&self) -> Pixels {
9145 0.15 * self.position_map.line_height
9146 }
9147}
9148
9149struct LineNumberLayout {
9150 shaped_line: ShapedLine,
9151 hitbox: Option<Hitbox>,
9152}
9153
9154struct ColoredRange<T> {
9155 start: T,
9156 end: T,
9157 color: Hsla,
9158}
9159
9160impl Along for ScrollbarAxes {
9161 type Unit = bool;
9162
9163 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
9164 match axis {
9165 ScrollbarAxis::Horizontal => self.horizontal,
9166 ScrollbarAxis::Vertical => self.vertical,
9167 }
9168 }
9169
9170 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
9171 match axis {
9172 ScrollbarAxis::Horizontal => ScrollbarAxes {
9173 horizontal: f(self.horizontal),
9174 vertical: self.vertical,
9175 },
9176 ScrollbarAxis::Vertical => ScrollbarAxes {
9177 horizontal: self.horizontal,
9178 vertical: f(self.vertical),
9179 },
9180 }
9181 }
9182}
9183
9184#[derive(Clone)]
9185struct EditorScrollbars {
9186 pub vertical: Option<ScrollbarLayout>,
9187 pub horizontal: Option<ScrollbarLayout>,
9188 pub visible: bool,
9189}
9190
9191impl EditorScrollbars {
9192 pub fn from_scrollbar_axes(
9193 settings_visibility: ScrollbarAxes,
9194 layout_information: &ScrollbarLayoutInformation,
9195 content_offset: gpui::Point<Pixels>,
9196 scroll_position: gpui::Point<f32>,
9197 scrollbar_width: Pixels,
9198 right_margin: Pixels,
9199 editor_width: Pixels,
9200 show_scrollbars: bool,
9201 scrollbar_state: Option<&ActiveScrollbarState>,
9202 window: &mut Window,
9203 ) -> Self {
9204 let ScrollbarLayoutInformation {
9205 editor_bounds,
9206 scroll_range,
9207 glyph_grid_cell,
9208 } = layout_information;
9209
9210 let viewport_size = size(editor_width, editor_bounds.size.height);
9211
9212 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
9213 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
9214 Corner::BottomLeft,
9215 editor_bounds.bottom_left(),
9216 size(
9217 // The horizontal viewport size differs from the space available for the
9218 // horizontal scrollbar, so we have to manually stich it together here.
9219 editor_bounds.size.width - right_margin,
9220 scrollbar_width,
9221 ),
9222 ),
9223 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
9224 Corner::TopRight,
9225 editor_bounds.top_right(),
9226 size(scrollbar_width, viewport_size.height),
9227 ),
9228 };
9229
9230 let mut create_scrollbar_layout = |axis| {
9231 settings_visibility
9232 .along(axis)
9233 .then(|| {
9234 (
9235 viewport_size.along(axis) - content_offset.along(axis),
9236 scroll_range.along(axis),
9237 )
9238 })
9239 .filter(|(viewport_size, scroll_range)| {
9240 // The scrollbar should only be rendered if the content does
9241 // not entirely fit into the editor
9242 // However, this only applies to the horizontal scrollbar, as information about the
9243 // vertical scrollbar layout is always needed for scrollbar diagnostics.
9244 axis != ScrollbarAxis::Horizontal || viewport_size < scroll_range
9245 })
9246 .map(|(viewport_size, scroll_range)| {
9247 ScrollbarLayout::new(
9248 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
9249 viewport_size,
9250 scroll_range,
9251 glyph_grid_cell.along(axis),
9252 content_offset.along(axis),
9253 scroll_position.along(axis),
9254 show_scrollbars,
9255 axis,
9256 )
9257 .with_thumb_state(
9258 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
9259 )
9260 })
9261 };
9262
9263 Self {
9264 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
9265 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
9266 visible: show_scrollbars,
9267 }
9268 }
9269
9270 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
9271 [
9272 (&self.vertical, ScrollbarAxis::Vertical),
9273 (&self.horizontal, ScrollbarAxis::Horizontal),
9274 ]
9275 .into_iter()
9276 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
9277 }
9278
9279 /// Returns the currently hovered scrollbar axis, if any.
9280 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
9281 self.iter_scrollbars()
9282 .find(|s| s.0.hitbox.is_hovered(window))
9283 }
9284}
9285
9286#[derive(Clone)]
9287struct ScrollbarLayout {
9288 hitbox: Hitbox,
9289 visible_range: Range<f32>,
9290 text_unit_size: Pixels,
9291 thumb_bounds: Option<Bounds<Pixels>>,
9292 thumb_state: ScrollbarThumbState,
9293}
9294
9295impl ScrollbarLayout {
9296 const BORDER_WIDTH: Pixels = px(1.0);
9297 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
9298 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
9299 const MIN_THUMB_SIZE: Pixels = px(25.0);
9300
9301 fn new(
9302 scrollbar_track_hitbox: Hitbox,
9303 viewport_size: Pixels,
9304 scroll_range: Pixels,
9305 glyph_space: Pixels,
9306 content_offset: Pixels,
9307 scroll_position: f32,
9308 show_thumb: bool,
9309 axis: ScrollbarAxis,
9310 ) -> Self {
9311 let track_bounds = scrollbar_track_hitbox.bounds;
9312 // The length of the track available to the scrollbar thumb. We deliberately
9313 // exclude the content size here so that the thumb aligns with the content.
9314 let track_length = track_bounds.size.along(axis) - content_offset;
9315
9316 Self::new_with_hitbox_and_track_length(
9317 scrollbar_track_hitbox,
9318 track_length,
9319 viewport_size,
9320 scroll_range,
9321 glyph_space,
9322 content_offset,
9323 scroll_position,
9324 show_thumb,
9325 axis,
9326 )
9327 }
9328
9329 fn for_minimap(
9330 minimap_track_hitbox: Hitbox,
9331 visible_lines: f32,
9332 total_editor_lines: f32,
9333 minimap_line_height: Pixels,
9334 scroll_position: f32,
9335 minimap_scroll_top: f32,
9336 show_thumb: bool,
9337 ) -> Self {
9338 // The scrollbar thumb size is calculated as
9339 // (visible_content/total_content) × scrollbar_track_length.
9340 //
9341 // For the minimap's thumb layout, we leverage this by setting the
9342 // scrollbar track length to the entire document size (using minimap line
9343 // height). This creates a thumb that exactly represents the editor
9344 // viewport scaled to minimap proportions.
9345 //
9346 // We adjust the thumb position relative to `minimap_scroll_top` to
9347 // accommodate for the deliberately oversized track.
9348 //
9349 // This approach ensures that the minimap thumb accurately reflects the
9350 // editor's current scroll position whilst nicely synchronizing the minimap
9351 // thumb and scrollbar thumb.
9352 let scroll_range = total_editor_lines * minimap_line_height;
9353 let viewport_size = visible_lines * minimap_line_height;
9354
9355 let track_top_offset = -minimap_scroll_top * minimap_line_height;
9356
9357 Self::new_with_hitbox_and_track_length(
9358 minimap_track_hitbox,
9359 scroll_range,
9360 viewport_size,
9361 scroll_range,
9362 minimap_line_height,
9363 track_top_offset,
9364 scroll_position,
9365 show_thumb,
9366 ScrollbarAxis::Vertical,
9367 )
9368 }
9369
9370 fn new_with_hitbox_and_track_length(
9371 scrollbar_track_hitbox: Hitbox,
9372 track_length: Pixels,
9373 viewport_size: Pixels,
9374 scroll_range: Pixels,
9375 glyph_space: Pixels,
9376 content_offset: Pixels,
9377 scroll_position: f32,
9378 show_thumb: bool,
9379 axis: ScrollbarAxis,
9380 ) -> Self {
9381 let text_units_per_page = viewport_size / glyph_space;
9382 let visible_range = scroll_position..scroll_position + text_units_per_page;
9383 let total_text_units = scroll_range / glyph_space;
9384
9385 let thumb_percentage = text_units_per_page / total_text_units;
9386 let thumb_size = (track_length * thumb_percentage)
9387 .max(ScrollbarLayout::MIN_THUMB_SIZE)
9388 .min(track_length);
9389
9390 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
9391
9392 let content_larger_than_viewport = text_unit_divisor > 0.;
9393
9394 let text_unit_size = if content_larger_than_viewport {
9395 (track_length - thumb_size) / text_unit_divisor
9396 } else {
9397 glyph_space
9398 };
9399
9400 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
9401 Self::thumb_bounds(
9402 &scrollbar_track_hitbox,
9403 content_offset,
9404 visible_range.start,
9405 text_unit_size,
9406 thumb_size,
9407 axis,
9408 )
9409 });
9410
9411 ScrollbarLayout {
9412 hitbox: scrollbar_track_hitbox,
9413 visible_range,
9414 text_unit_size,
9415 thumb_bounds,
9416 thumb_state: Default::default(),
9417 }
9418 }
9419
9420 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
9421 if let Some(thumb_state) = thumb_state {
9422 Self {
9423 thumb_state,
9424 ..self
9425 }
9426 } else {
9427 self
9428 }
9429 }
9430
9431 fn thumb_bounds(
9432 scrollbar_track: &Hitbox,
9433 content_offset: Pixels,
9434 visible_range_start: f32,
9435 text_unit_size: Pixels,
9436 thumb_size: Pixels,
9437 axis: ScrollbarAxis,
9438 ) -> Bounds<Pixels> {
9439 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
9440 origin + content_offset + visible_range_start * text_unit_size
9441 });
9442 Bounds::new(
9443 thumb_origin,
9444 scrollbar_track.size.apply_along(axis, |_| thumb_size),
9445 )
9446 }
9447
9448 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
9449 self.thumb_bounds
9450 .is_some_and(|bounds| bounds.contains(position))
9451 }
9452
9453 fn marker_quads_for_ranges(
9454 &self,
9455 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
9456 column: Option<usize>,
9457 ) -> Vec<PaintQuad> {
9458 struct MinMax {
9459 min: Pixels,
9460 max: Pixels,
9461 }
9462 let (x_range, height_limit) = if let Some(column) = column {
9463 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
9464 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
9465 let end = start + column_width;
9466 (
9467 Range { start, end },
9468 MinMax {
9469 min: Self::MIN_MARKER_HEIGHT,
9470 max: px(f32::MAX),
9471 },
9472 )
9473 } else {
9474 (
9475 Range {
9476 start: Self::BORDER_WIDTH,
9477 end: self.hitbox.size.width,
9478 },
9479 MinMax {
9480 min: Self::LINE_MARKER_HEIGHT,
9481 max: Self::LINE_MARKER_HEIGHT,
9482 },
9483 )
9484 };
9485
9486 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
9487 let mut pixel_ranges = row_ranges
9488 .into_iter()
9489 .map(|range| {
9490 let start_y = row_to_y(range.start);
9491 let end_y = row_to_y(range.end)
9492 + self
9493 .text_unit_size
9494 .max(height_limit.min)
9495 .min(height_limit.max);
9496 ColoredRange {
9497 start: start_y,
9498 end: end_y,
9499 color: range.color,
9500 }
9501 })
9502 .peekable();
9503
9504 let mut quads = Vec::new();
9505 while let Some(mut pixel_range) = pixel_ranges.next() {
9506 while let Some(next_pixel_range) = pixel_ranges.peek() {
9507 if pixel_range.end >= next_pixel_range.start - px(1.0)
9508 && pixel_range.color == next_pixel_range.color
9509 {
9510 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
9511 pixel_ranges.next();
9512 } else {
9513 break;
9514 }
9515 }
9516
9517 let bounds = Bounds::from_corners(
9518 point(x_range.start, pixel_range.start),
9519 point(x_range.end, pixel_range.end),
9520 );
9521 quads.push(quad(
9522 bounds,
9523 Corners::default(),
9524 pixel_range.color,
9525 Edges::default(),
9526 Hsla::transparent_black(),
9527 BorderStyle::default(),
9528 ));
9529 }
9530
9531 quads
9532 }
9533}
9534
9535struct MinimapLayout {
9536 pub minimap: AnyElement,
9537 pub thumb_layout: ScrollbarLayout,
9538 pub minimap_scroll_top: f32,
9539 pub minimap_line_height: Pixels,
9540 pub thumb_border_style: MinimapThumbBorder,
9541 pub max_scroll_top: f32,
9542}
9543
9544impl MinimapLayout {
9545 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
9546 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
9547 /// The minimap width as a percentage of the editor width.
9548 const MINIMAP_WIDTH_PCT: f32 = 0.15;
9549 /// Calculates the scroll top offset the minimap editor has to have based on the
9550 /// current scroll progress.
9551 fn calculate_minimap_top_offset(
9552 document_lines: f32,
9553 visible_editor_lines: f32,
9554 visible_minimap_lines: f32,
9555 scroll_position: f32,
9556 ) -> f32 {
9557 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
9558 if non_visible_document_lines == 0. {
9559 0.
9560 } else {
9561 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
9562 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
9563 }
9564 }
9565}
9566
9567struct CreaseTrailerLayout {
9568 element: AnyElement,
9569 bounds: Bounds<Pixels>,
9570}
9571
9572pub(crate) struct PositionMap {
9573 pub size: Size<Pixels>,
9574 pub line_height: Pixels,
9575 pub scroll_pixel_position: gpui::Point<Pixels>,
9576 pub scroll_max: gpui::Point<f32>,
9577 pub em_width: Pixels,
9578 pub em_advance: Pixels,
9579 pub visible_row_range: Range<DisplayRow>,
9580 pub line_layouts: Vec<LineWithInvisibles>,
9581 pub snapshot: EditorSnapshot,
9582 pub text_hitbox: Hitbox,
9583 pub gutter_hitbox: Hitbox,
9584 pub inline_blame_bounds: Option<(Bounds<Pixels>, BlameEntry)>,
9585 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9586 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
9587}
9588
9589#[derive(Debug, Copy, Clone)]
9590pub struct PointForPosition {
9591 pub previous_valid: DisplayPoint,
9592 pub next_valid: DisplayPoint,
9593 pub exact_unclipped: DisplayPoint,
9594 pub column_overshoot_after_line_end: u32,
9595}
9596
9597impl PointForPosition {
9598 pub fn as_valid(&self) -> Option<DisplayPoint> {
9599 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
9600 Some(self.previous_valid)
9601 } else {
9602 None
9603 }
9604 }
9605
9606 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
9607 let Some(valid_point) = self.as_valid() else {
9608 return false;
9609 };
9610 let range = selection.range();
9611
9612 let candidate_row = valid_point.row();
9613 let candidate_col = valid_point.column();
9614
9615 let start_row = range.start.row();
9616 let start_col = range.start.column();
9617 let end_row = range.end.row();
9618 let end_col = range.end.column();
9619
9620 if candidate_row < start_row || candidate_row > end_row {
9621 false
9622 } else if start_row == end_row {
9623 candidate_col >= start_col && candidate_col < end_col
9624 } else {
9625 if candidate_row == start_row {
9626 candidate_col >= start_col
9627 } else if candidate_row == end_row {
9628 candidate_col < end_col
9629 } else {
9630 true
9631 }
9632 }
9633 }
9634}
9635
9636impl PositionMap {
9637 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
9638 let text_bounds = self.text_hitbox.bounds;
9639 let scroll_position = self.snapshot.scroll_position();
9640 let position = position - text_bounds.origin;
9641 let y = position.y.max(px(0.)).min(self.size.height);
9642 let x = position.x + (scroll_position.x * self.em_advance);
9643 let row = ((y / self.line_height) + scroll_position.y) as u32;
9644
9645 let (column, x_overshoot_after_line_end) = if let Some(line) = self
9646 .line_layouts
9647 .get(row as usize - scroll_position.y as usize)
9648 {
9649 if let Some(ix) = line.index_for_x(x) {
9650 (ix as u32, px(0.))
9651 } else {
9652 (line.len as u32, px(0.).max(x - line.width))
9653 }
9654 } else {
9655 (0, x)
9656 };
9657
9658 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
9659 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
9660 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
9661
9662 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
9663 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
9664 PointForPosition {
9665 previous_valid,
9666 next_valid,
9667 exact_unclipped,
9668 column_overshoot_after_line_end,
9669 }
9670 }
9671}
9672
9673struct BlockLayout {
9674 id: BlockId,
9675 x_offset: Pixels,
9676 row: Option<DisplayRow>,
9677 element: AnyElement,
9678 available_space: Size<AvailableSpace>,
9679 style: BlockStyle,
9680 overlaps_gutter: bool,
9681 is_buffer_header: bool,
9682}
9683
9684pub fn layout_line(
9685 row: DisplayRow,
9686 snapshot: &EditorSnapshot,
9687 style: &EditorStyle,
9688 text_width: Pixels,
9689 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
9690 window: &mut Window,
9691 cx: &mut App,
9692) -> LineWithInvisibles {
9693 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
9694 LineWithInvisibles::from_chunks(
9695 chunks,
9696 &style,
9697 MAX_LINE_LEN,
9698 1,
9699 &snapshot.mode,
9700 text_width,
9701 is_row_soft_wrapped,
9702 window,
9703 cx,
9704 )
9705 .pop()
9706 .unwrap()
9707}
9708
9709#[derive(Debug)]
9710pub struct IndentGuideLayout {
9711 origin: gpui::Point<Pixels>,
9712 length: Pixels,
9713 single_indent_width: Pixels,
9714 depth: u32,
9715 active: bool,
9716 settings: IndentGuideSettings,
9717}
9718
9719pub struct CursorLayout {
9720 origin: gpui::Point<Pixels>,
9721 block_width: Pixels,
9722 line_height: Pixels,
9723 color: Hsla,
9724 shape: CursorShape,
9725 block_text: Option<ShapedLine>,
9726 cursor_name: Option<AnyElement>,
9727}
9728
9729#[derive(Debug)]
9730pub struct CursorName {
9731 string: SharedString,
9732 color: Hsla,
9733 is_top_row: bool,
9734}
9735
9736impl CursorLayout {
9737 pub fn new(
9738 origin: gpui::Point<Pixels>,
9739 block_width: Pixels,
9740 line_height: Pixels,
9741 color: Hsla,
9742 shape: CursorShape,
9743 block_text: Option<ShapedLine>,
9744 ) -> CursorLayout {
9745 CursorLayout {
9746 origin,
9747 block_width,
9748 line_height,
9749 color,
9750 shape,
9751 block_text,
9752 cursor_name: None,
9753 }
9754 }
9755
9756 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
9757 Bounds {
9758 origin: self.origin + origin,
9759 size: size(self.block_width, self.line_height),
9760 }
9761 }
9762
9763 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
9764 match self.shape {
9765 CursorShape::Bar => Bounds {
9766 origin: self.origin + origin,
9767 size: size(px(2.0), self.line_height),
9768 },
9769 CursorShape::Block | CursorShape::Hollow => Bounds {
9770 origin: self.origin + origin,
9771 size: size(self.block_width, self.line_height),
9772 },
9773 CursorShape::Underline => Bounds {
9774 origin: self.origin
9775 + origin
9776 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
9777 size: size(self.block_width, px(2.0)),
9778 },
9779 }
9780 }
9781
9782 pub fn layout(
9783 &mut self,
9784 origin: gpui::Point<Pixels>,
9785 cursor_name: Option<CursorName>,
9786 window: &mut Window,
9787 cx: &mut App,
9788 ) {
9789 if let Some(cursor_name) = cursor_name {
9790 let bounds = self.bounds(origin);
9791 let text_size = self.line_height / 1.5;
9792
9793 let name_origin = if cursor_name.is_top_row {
9794 point(bounds.right() - px(1.), bounds.top())
9795 } else {
9796 match self.shape {
9797 CursorShape::Bar => point(
9798 bounds.right() - px(2.),
9799 bounds.top() - text_size / 2. - px(1.),
9800 ),
9801 _ => point(
9802 bounds.right() - px(1.),
9803 bounds.top() - text_size / 2. - px(1.),
9804 ),
9805 }
9806 };
9807 let mut name_element = div()
9808 .bg(self.color)
9809 .text_size(text_size)
9810 .px_0p5()
9811 .line_height(text_size + px(2.))
9812 .text_color(cursor_name.color)
9813 .child(cursor_name.string.clone())
9814 .into_any_element();
9815
9816 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
9817
9818 self.cursor_name = Some(name_element);
9819 }
9820 }
9821
9822 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
9823 let bounds = self.bounds(origin);
9824
9825 //Draw background or border quad
9826 let cursor = if matches!(self.shape, CursorShape::Hollow) {
9827 outline(bounds, self.color, BorderStyle::Solid)
9828 } else {
9829 fill(bounds, self.color)
9830 };
9831
9832 if let Some(name) = &mut self.cursor_name {
9833 name.paint(window, cx);
9834 }
9835
9836 window.paint_quad(cursor);
9837
9838 if let Some(block_text) = &self.block_text {
9839 block_text
9840 .paint(self.origin + origin, self.line_height, window, cx)
9841 .log_err();
9842 }
9843 }
9844
9845 pub fn shape(&self) -> CursorShape {
9846 self.shape
9847 }
9848}
9849
9850#[derive(Debug)]
9851pub struct HighlightedRange {
9852 pub start_y: Pixels,
9853 pub line_height: Pixels,
9854 pub lines: Vec<HighlightedRangeLine>,
9855 pub color: Hsla,
9856 pub corner_radius: Pixels,
9857}
9858
9859#[derive(Debug)]
9860pub struct HighlightedRangeLine {
9861 pub start_x: Pixels,
9862 pub end_x: Pixels,
9863}
9864
9865impl HighlightedRange {
9866 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
9867 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
9868 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
9869 self.paint_lines(
9870 self.start_y + self.line_height,
9871 &self.lines[1..],
9872 fill,
9873 bounds,
9874 window,
9875 );
9876 } else {
9877 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
9878 }
9879 }
9880
9881 fn paint_lines(
9882 &self,
9883 start_y: Pixels,
9884 lines: &[HighlightedRangeLine],
9885 fill: bool,
9886 _bounds: Bounds<Pixels>,
9887 window: &mut Window,
9888 ) {
9889 if lines.is_empty() {
9890 return;
9891 }
9892
9893 let first_line = lines.first().unwrap();
9894 let last_line = lines.last().unwrap();
9895
9896 let first_top_left = point(first_line.start_x, start_y);
9897 let first_top_right = point(first_line.end_x, start_y);
9898
9899 let curve_height = point(Pixels::ZERO, self.corner_radius);
9900 let curve_width = |start_x: Pixels, end_x: Pixels| {
9901 let max = (end_x - start_x) / 2.;
9902 let width = if max < self.corner_radius {
9903 max
9904 } else {
9905 self.corner_radius
9906 };
9907
9908 point(width, Pixels::ZERO)
9909 };
9910
9911 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
9912 let mut builder = if fill {
9913 gpui::PathBuilder::fill()
9914 } else {
9915 gpui::PathBuilder::stroke(px(1.))
9916 };
9917 builder.move_to(first_top_right - top_curve_width);
9918 builder.curve_to(first_top_right + curve_height, first_top_right);
9919
9920 let mut iter = lines.iter().enumerate().peekable();
9921 while let Some((ix, line)) = iter.next() {
9922 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
9923
9924 if let Some((_, next_line)) = iter.peek() {
9925 let next_top_right = point(next_line.end_x, bottom_right.y);
9926
9927 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
9928 Ordering::Equal => {
9929 builder.line_to(bottom_right);
9930 }
9931 Ordering::Less => {
9932 let curve_width = curve_width(next_top_right.x, bottom_right.x);
9933 builder.line_to(bottom_right - curve_height);
9934 if self.corner_radius > Pixels::ZERO {
9935 builder.curve_to(bottom_right - curve_width, bottom_right);
9936 }
9937 builder.line_to(next_top_right + curve_width);
9938 if self.corner_radius > Pixels::ZERO {
9939 builder.curve_to(next_top_right + curve_height, next_top_right);
9940 }
9941 }
9942 Ordering::Greater => {
9943 let curve_width = curve_width(bottom_right.x, next_top_right.x);
9944 builder.line_to(bottom_right - curve_height);
9945 if self.corner_radius > Pixels::ZERO {
9946 builder.curve_to(bottom_right + curve_width, bottom_right);
9947 }
9948 builder.line_to(next_top_right - curve_width);
9949 if self.corner_radius > Pixels::ZERO {
9950 builder.curve_to(next_top_right + curve_height, next_top_right);
9951 }
9952 }
9953 }
9954 } else {
9955 let curve_width = curve_width(line.start_x, line.end_x);
9956 builder.line_to(bottom_right - curve_height);
9957 if self.corner_radius > Pixels::ZERO {
9958 builder.curve_to(bottom_right - curve_width, bottom_right);
9959 }
9960
9961 let bottom_left = point(line.start_x, bottom_right.y);
9962 builder.line_to(bottom_left + curve_width);
9963 if self.corner_radius > Pixels::ZERO {
9964 builder.curve_to(bottom_left - curve_height, bottom_left);
9965 }
9966 }
9967 }
9968
9969 if first_line.start_x > last_line.start_x {
9970 let curve_width = curve_width(last_line.start_x, first_line.start_x);
9971 let second_top_left = point(last_line.start_x, start_y + self.line_height);
9972 builder.line_to(second_top_left + curve_height);
9973 if self.corner_radius > Pixels::ZERO {
9974 builder.curve_to(second_top_left + curve_width, second_top_left);
9975 }
9976 let first_bottom_left = point(first_line.start_x, second_top_left.y);
9977 builder.line_to(first_bottom_left - curve_width);
9978 if self.corner_radius > Pixels::ZERO {
9979 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
9980 }
9981 }
9982
9983 builder.line_to(first_top_left + curve_height);
9984 if self.corner_radius > Pixels::ZERO {
9985 builder.curve_to(first_top_left + top_curve_width, first_top_left);
9986 }
9987 builder.line_to(first_top_right - top_curve_width);
9988
9989 if let Ok(path) = builder.build() {
9990 window.paint_path(path, self.color);
9991 }
9992 }
9993}
9994
9995enum CursorPopoverType {
9996 CodeContextMenu,
9997 EditPrediction,
9998}
9999
10000pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10001 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
10002}
10003
10004fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10005 (delta.pow(1.2) / 300.0).into()
10006}
10007
10008pub fn register_action<T: Action>(
10009 editor: &Entity<Editor>,
10010 window: &mut Window,
10011 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
10012) {
10013 let editor = editor.clone();
10014 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
10015 let action = action.downcast_ref().unwrap();
10016 if phase == DispatchPhase::Bubble {
10017 editor.update(cx, |editor, cx| {
10018 listener(editor, action, window, cx);
10019 })
10020 }
10021 })
10022}
10023
10024fn compute_auto_height_layout(
10025 editor: &mut Editor,
10026 min_lines: usize,
10027 max_lines: Option<usize>,
10028 max_line_number_width: Pixels,
10029 known_dimensions: Size<Option<Pixels>>,
10030 available_width: AvailableSpace,
10031 window: &mut Window,
10032 cx: &mut Context<Editor>,
10033) -> Option<Size<Pixels>> {
10034 let width = known_dimensions.width.or({
10035 if let AvailableSpace::Definite(available_width) = available_width {
10036 Some(available_width)
10037 } else {
10038 None
10039 }
10040 })?;
10041 if let Some(height) = known_dimensions.height {
10042 return Some(size(width, height));
10043 }
10044
10045 let style = editor.style.as_ref().unwrap();
10046 let font_id = window.text_system().resolve_font(&style.text.font());
10047 let font_size = style.text.font_size.to_pixels(window.rem_size());
10048 let line_height = style.text.line_height_in_pixels(window.rem_size());
10049 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10050
10051 let mut snapshot = editor.snapshot(window, cx);
10052 let gutter_dimensions = snapshot
10053 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10054 .or_else(|| {
10055 editor
10056 .offset_content
10057 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10058 })
10059 .unwrap_or_default();
10060
10061 editor.gutter_dimensions = gutter_dimensions;
10062 let text_width = width - gutter_dimensions.width;
10063 let overscroll = size(em_width, px(0.));
10064
10065 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10066 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
10067 if editor.set_wrap_width(Some(editor_width), cx) {
10068 snapshot = editor.snapshot(window, cx);
10069 }
10070 }
10071
10072 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10073
10074 let min_height = line_height * min_lines as f32;
10075 let content_height = scroll_height.max(min_height);
10076
10077 let final_height = if let Some(max_lines) = max_lines {
10078 let max_height = line_height * max_lines as f32;
10079 content_height.min(max_height)
10080 } else {
10081 content_height
10082 };
10083
10084 Some(size(width, final_height))
10085}
10086
10087#[cfg(test)]
10088mod tests {
10089 use super::*;
10090 use crate::{
10091 Editor, MultiBuffer, SelectionEffects,
10092 display_map::{BlockPlacement, BlockProperties},
10093 editor_tests::{init_test, update_test_language_settings},
10094 };
10095 use gpui::{TestAppContext, VisualTestContext};
10096 use language::language_settings;
10097 use log::info;
10098 use std::num::NonZeroU32;
10099 use util::test::sample_text;
10100
10101 #[gpui::test]
10102 fn test_shape_line_numbers(cx: &mut TestAppContext) {
10103 init_test(cx, |_| {});
10104 let window = cx.add_window(|window, cx| {
10105 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10106 Editor::new(EditorMode::full(), buffer, None, window, cx)
10107 });
10108
10109 let editor = window.root(cx).unwrap();
10110 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10111 let line_height = window
10112 .update(cx, |_, window, _| {
10113 style.text.line_height_in_pixels(window.rem_size())
10114 })
10115 .unwrap();
10116 let element = EditorElement::new(&editor, style);
10117 let snapshot = window
10118 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10119 .unwrap();
10120
10121 let layouts = cx
10122 .update_window(*window, |_, window, cx| {
10123 element.layout_line_numbers(
10124 None,
10125 GutterDimensions {
10126 left_padding: Pixels::ZERO,
10127 right_padding: Pixels::ZERO,
10128 width: px(30.0),
10129 margin: Pixels::ZERO,
10130 git_blame_entries_width: None,
10131 },
10132 line_height,
10133 gpui::Point::default(),
10134 DisplayRow(0)..DisplayRow(6),
10135 &(0..6)
10136 .map(|row| RowInfo {
10137 buffer_row: Some(row),
10138 ..Default::default()
10139 })
10140 .collect::<Vec<_>>(),
10141 &BTreeMap::default(),
10142 Some(DisplayPoint::new(DisplayRow(0), 0)),
10143 &snapshot,
10144 window,
10145 cx,
10146 )
10147 })
10148 .unwrap();
10149 assert_eq!(layouts.len(), 6);
10150
10151 let relative_rows = window
10152 .update(cx, |editor, window, cx| {
10153 let snapshot = editor.snapshot(window, cx);
10154 element.calculate_relative_line_numbers(
10155 &snapshot,
10156 &(DisplayRow(0)..DisplayRow(6)),
10157 Some(DisplayRow(3)),
10158 )
10159 })
10160 .unwrap();
10161 assert_eq!(relative_rows[&DisplayRow(0)], 3);
10162 assert_eq!(relative_rows[&DisplayRow(1)], 2);
10163 assert_eq!(relative_rows[&DisplayRow(2)], 1);
10164 // current line has no relative number
10165 assert_eq!(relative_rows[&DisplayRow(4)], 1);
10166 assert_eq!(relative_rows[&DisplayRow(5)], 2);
10167
10168 // works if cursor is before screen
10169 let relative_rows = window
10170 .update(cx, |editor, window, cx| {
10171 let snapshot = editor.snapshot(window, cx);
10172 element.calculate_relative_line_numbers(
10173 &snapshot,
10174 &(DisplayRow(3)..DisplayRow(6)),
10175 Some(DisplayRow(1)),
10176 )
10177 })
10178 .unwrap();
10179 assert_eq!(relative_rows.len(), 3);
10180 assert_eq!(relative_rows[&DisplayRow(3)], 2);
10181 assert_eq!(relative_rows[&DisplayRow(4)], 3);
10182 assert_eq!(relative_rows[&DisplayRow(5)], 4);
10183
10184 // works if cursor is after screen
10185 let relative_rows = window
10186 .update(cx, |editor, window, cx| {
10187 let snapshot = editor.snapshot(window, cx);
10188 element.calculate_relative_line_numbers(
10189 &snapshot,
10190 &(DisplayRow(0)..DisplayRow(3)),
10191 Some(DisplayRow(6)),
10192 )
10193 })
10194 .unwrap();
10195 assert_eq!(relative_rows.len(), 3);
10196 assert_eq!(relative_rows[&DisplayRow(0)], 5);
10197 assert_eq!(relative_rows[&DisplayRow(1)], 4);
10198 assert_eq!(relative_rows[&DisplayRow(2)], 3);
10199 }
10200
10201 #[gpui::test]
10202 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10203 init_test(cx, |_| {});
10204
10205 let window = cx.add_window(|window, cx| {
10206 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10207 Editor::new(EditorMode::full(), buffer, None, window, cx)
10208 });
10209 let cx = &mut VisualTestContext::from_window(*window, cx);
10210 let editor = window.root(cx).unwrap();
10211 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10212
10213 window
10214 .update(cx, |editor, window, cx| {
10215 editor.cursor_shape = CursorShape::Block;
10216 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10217 s.select_ranges([
10218 Point::new(0, 0)..Point::new(1, 0),
10219 Point::new(3, 2)..Point::new(3, 3),
10220 Point::new(5, 6)..Point::new(6, 0),
10221 ]);
10222 });
10223 })
10224 .unwrap();
10225
10226 let (_, state) = cx.draw(
10227 point(px(500.), px(500.)),
10228 size(px(500.), px(500.)),
10229 |_, _| EditorElement::new(&editor, style),
10230 );
10231
10232 assert_eq!(state.selections.len(), 1);
10233 let local_selections = &state.selections[0].1;
10234 assert_eq!(local_selections.len(), 3);
10235 // moves cursor back one line
10236 assert_eq!(
10237 local_selections[0].head,
10238 DisplayPoint::new(DisplayRow(0), 6)
10239 );
10240 assert_eq!(
10241 local_selections[0].range,
10242 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10243 );
10244
10245 // moves cursor back one column
10246 assert_eq!(
10247 local_selections[1].range,
10248 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10249 );
10250 assert_eq!(
10251 local_selections[1].head,
10252 DisplayPoint::new(DisplayRow(3), 2)
10253 );
10254
10255 // leaves cursor on the max point
10256 assert_eq!(
10257 local_selections[2].range,
10258 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10259 );
10260 assert_eq!(
10261 local_selections[2].head,
10262 DisplayPoint::new(DisplayRow(6), 0)
10263 );
10264
10265 // active lines does not include 1 (even though the range of the selection does)
10266 assert_eq!(
10267 state.active_rows.keys().cloned().collect::<Vec<_>>(),
10268 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10269 );
10270 }
10271
10272 #[gpui::test]
10273 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10274 init_test(cx, |_| {});
10275
10276 let window = cx.add_window(|window, cx| {
10277 let buffer = MultiBuffer::build_simple("", cx);
10278 Editor::new(EditorMode::full(), buffer, None, window, cx)
10279 });
10280 let cx = &mut VisualTestContext::from_window(*window, cx);
10281 let editor = window.root(cx).unwrap();
10282 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10283 window
10284 .update(cx, |editor, window, cx| {
10285 editor.set_placeholder_text("hello", cx);
10286 editor.insert_blocks(
10287 [BlockProperties {
10288 style: BlockStyle::Fixed,
10289 placement: BlockPlacement::Above(Anchor::min()),
10290 height: Some(3),
10291 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10292 priority: 0,
10293 render_in_minimap: true,
10294 }],
10295 None,
10296 cx,
10297 );
10298
10299 // Blur the editor so that it displays placeholder text.
10300 window.blur();
10301 })
10302 .unwrap();
10303
10304 let (_, state) = cx.draw(
10305 point(px(500.), px(500.)),
10306 size(px(500.), px(500.)),
10307 |_, _| EditorElement::new(&editor, style),
10308 );
10309 assert_eq!(state.position_map.line_layouts.len(), 4);
10310 assert_eq!(state.line_numbers.len(), 1);
10311 assert_eq!(
10312 state
10313 .line_numbers
10314 .get(&MultiBufferRow(0))
10315 .map(|line_number| line_number.shaped_line.text.as_ref()),
10316 Some("1")
10317 );
10318 }
10319
10320 #[gpui::test]
10321 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10322 const TAB_SIZE: u32 = 4;
10323
10324 let input_text = "\t \t|\t| a b";
10325 let expected_invisibles = vec![
10326 Invisible::Tab {
10327 line_start_offset: 0,
10328 line_end_offset: TAB_SIZE as usize,
10329 },
10330 Invisible::Whitespace {
10331 line_offset: TAB_SIZE as usize,
10332 },
10333 Invisible::Tab {
10334 line_start_offset: TAB_SIZE as usize + 1,
10335 line_end_offset: TAB_SIZE as usize * 2,
10336 },
10337 Invisible::Tab {
10338 line_start_offset: TAB_SIZE as usize * 2 + 1,
10339 line_end_offset: TAB_SIZE as usize * 3,
10340 },
10341 Invisible::Whitespace {
10342 line_offset: TAB_SIZE as usize * 3 + 1,
10343 },
10344 Invisible::Whitespace {
10345 line_offset: TAB_SIZE as usize * 3 + 3,
10346 },
10347 ];
10348 assert_eq!(
10349 expected_invisibles.len(),
10350 input_text
10351 .chars()
10352 .filter(|initial_char| initial_char.is_whitespace())
10353 .count(),
10354 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10355 );
10356
10357 for show_line_numbers in [true, false] {
10358 init_test(cx, |s| {
10359 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10360 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10361 });
10362
10363 let actual_invisibles = collect_invisibles_from_new_editor(
10364 cx,
10365 EditorMode::full(),
10366 input_text,
10367 px(500.0),
10368 show_line_numbers,
10369 );
10370
10371 assert_eq!(expected_invisibles, actual_invisibles);
10372 }
10373 }
10374
10375 #[gpui::test]
10376 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10377 init_test(cx, |s| {
10378 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10379 s.defaults.tab_size = NonZeroU32::new(4);
10380 });
10381
10382 for editor_mode_without_invisibles in [
10383 EditorMode::SingleLine { auto_width: false },
10384 EditorMode::AutoHeight {
10385 min_lines: 1,
10386 max_lines: Some(100),
10387 },
10388 ] {
10389 for show_line_numbers in [true, false] {
10390 let invisibles = collect_invisibles_from_new_editor(
10391 cx,
10392 editor_mode_without_invisibles.clone(),
10393 "\t\t\t| | a b",
10394 px(500.0),
10395 show_line_numbers,
10396 );
10397 assert!(
10398 invisibles.is_empty(),
10399 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10400 );
10401 }
10402 }
10403 }
10404
10405 #[gpui::test]
10406 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10407 let tab_size = 4;
10408 let input_text = "a\tbcd ".repeat(9);
10409 let repeated_invisibles = [
10410 Invisible::Tab {
10411 line_start_offset: 1,
10412 line_end_offset: tab_size as usize,
10413 },
10414 Invisible::Whitespace {
10415 line_offset: tab_size as usize + 3,
10416 },
10417 Invisible::Whitespace {
10418 line_offset: tab_size as usize + 4,
10419 },
10420 Invisible::Whitespace {
10421 line_offset: tab_size as usize + 5,
10422 },
10423 Invisible::Whitespace {
10424 line_offset: tab_size as usize + 6,
10425 },
10426 Invisible::Whitespace {
10427 line_offset: tab_size as usize + 7,
10428 },
10429 ];
10430 let expected_invisibles = std::iter::once(repeated_invisibles)
10431 .cycle()
10432 .take(9)
10433 .flatten()
10434 .collect::<Vec<_>>();
10435 assert_eq!(
10436 expected_invisibles.len(),
10437 input_text
10438 .chars()
10439 .filter(|initial_char| initial_char.is_whitespace())
10440 .count(),
10441 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10442 );
10443 info!("Expected invisibles: {expected_invisibles:?}");
10444
10445 init_test(cx, |_| {});
10446
10447 // Put the same string with repeating whitespace pattern into editors of various size,
10448 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10449 let resize_step = 10.0;
10450 let mut editor_width = 200.0;
10451 while editor_width <= 1000.0 {
10452 for show_line_numbers in [true, false] {
10453 update_test_language_settings(cx, |s| {
10454 s.defaults.tab_size = NonZeroU32::new(tab_size);
10455 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10456 s.defaults.preferred_line_length = Some(editor_width as u32);
10457 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10458 });
10459
10460 let actual_invisibles = collect_invisibles_from_new_editor(
10461 cx,
10462 EditorMode::full(),
10463 &input_text,
10464 px(editor_width),
10465 show_line_numbers,
10466 );
10467
10468 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10469 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10470 let mut i = 0;
10471 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10472 i = actual_index;
10473 match expected_invisibles.get(i) {
10474 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10475 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10476 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10477 _ => {
10478 panic!(
10479 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10480 )
10481 }
10482 },
10483 None => {
10484 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10485 }
10486 }
10487 }
10488 let missing_expected_invisibles = &expected_invisibles[i + 1..];
10489 assert!(
10490 missing_expected_invisibles.is_empty(),
10491 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10492 );
10493
10494 editor_width += resize_step;
10495 }
10496 }
10497 }
10498
10499 fn collect_invisibles_from_new_editor(
10500 cx: &mut TestAppContext,
10501 editor_mode: EditorMode,
10502 input_text: &str,
10503 editor_width: Pixels,
10504 show_line_numbers: bool,
10505 ) -> Vec<Invisible> {
10506 info!(
10507 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10508 editor_width.0
10509 );
10510 let window = cx.add_window(|window, cx| {
10511 let buffer = MultiBuffer::build_simple(input_text, cx);
10512 Editor::new(editor_mode, buffer, None, window, cx)
10513 });
10514 let cx = &mut VisualTestContext::from_window(*window, cx);
10515 let editor = window.root(cx).unwrap();
10516
10517 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10518 window
10519 .update(cx, |editor, _, cx| {
10520 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10521 editor.set_wrap_width(Some(editor_width), cx);
10522 editor.set_show_line_numbers(show_line_numbers, cx);
10523 })
10524 .unwrap();
10525 let (_, state) = cx.draw(
10526 point(px(500.), px(500.)),
10527 size(px(500.), px(500.)),
10528 |_, _| EditorElement::new(&editor, style),
10529 );
10530 state
10531 .position_map
10532 .line_layouts
10533 .iter()
10534 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10535 .cloned()
10536 .collect()
10537 }
10538}