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