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 let y = display_row_range.start.as_f32() * line_height
4989 + text_hitbox.bounds.top()
4990 - scroll_pixel_position.y;
4991
4992 let mut element = render_diff_hunk_controls(
4993 display_row_range.start.0,
4994 status,
4995 multi_buffer_range.clone(),
4996 *is_created_file,
4997 line_height,
4998 &editor,
4999 window,
5000 cx,
5001 );
5002 let size =
5003 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5004
5005 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5006
5007 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5008 control_bounds.push((display_row_range.start, bounds));
5009
5010 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5011 element.prepaint(window, cx)
5012 });
5013 controls.push(element);
5014 }
5015 }
5016 }
5017
5018 (controls, control_bounds)
5019 }
5020
5021 fn layout_signature_help(
5022 &self,
5023 hitbox: &Hitbox,
5024 content_origin: gpui::Point<Pixels>,
5025 scroll_pixel_position: gpui::Point<Pixels>,
5026 newest_selection_head: Option<DisplayPoint>,
5027 start_row: DisplayRow,
5028 line_layouts: &[LineWithInvisibles],
5029 line_height: Pixels,
5030 em_width: Pixels,
5031 context_menu_layout: Option<ContextMenuLayout>,
5032 window: &mut Window,
5033 cx: &mut App,
5034 ) {
5035 if !self.editor.focus_handle(cx).is_focused(window) {
5036 return;
5037 }
5038 let Some(newest_selection_head) = newest_selection_head else {
5039 return;
5040 };
5041
5042 let max_size = size(
5043 (120. * em_width) // Default size
5044 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5045 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5046 (16. * line_height) // Default size
5047 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5048 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5049 );
5050
5051 let maybe_element = self.editor.update(cx, |editor, cx| {
5052 if let Some(popover) = editor.signature_help_state.popover_mut() {
5053 let element = popover.render(max_size, window, cx);
5054 Some(element)
5055 } else {
5056 None
5057 }
5058 });
5059 let Some(mut element) = maybe_element else {
5060 return;
5061 };
5062
5063 let selection_row = newest_selection_head.row();
5064 let Some(cursor_row_layout) = (selection_row >= start_row)
5065 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5066 .flatten()
5067 else {
5068 return;
5069 };
5070
5071 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5072 - scroll_pixel_position.x;
5073 let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
5074 let target_point = content_origin + point(target_x, target_y);
5075
5076 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5077
5078 let (popover_bounds_above, popover_bounds_below) = {
5079 let horizontal_offset = (hitbox.top_right().x
5080 - POPOVER_RIGHT_OFFSET
5081 - (target_point.x + actual_size.width))
5082 .min(Pixels::ZERO);
5083 let initial_x = target_point.x + horizontal_offset;
5084 (
5085 Bounds::new(
5086 point(initial_x, target_point.y - actual_size.height),
5087 actual_size,
5088 ),
5089 Bounds::new(
5090 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5091 actual_size,
5092 ),
5093 )
5094 };
5095
5096 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5097 context_menu_layout
5098 .as_ref()
5099 .map_or(false, |menu| bounds.intersects(&menu.bounds))
5100 };
5101
5102 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5103 && !intersects_menu(popover_bounds_above)
5104 {
5105 // try placing above cursor
5106 popover_bounds_above.origin
5107 } else if popover_bounds_below.is_contained_within(hitbox)
5108 && !intersects_menu(popover_bounds_below)
5109 {
5110 // try placing below cursor
5111 popover_bounds_below.origin
5112 } else {
5113 // try surrounding context menu if exists
5114 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5115 let y_for_horizontal_positioning = if menu.y_flipped {
5116 menu.bounds.bottom() - actual_size.height
5117 } else {
5118 menu.bounds.top()
5119 };
5120 let possible_origins = vec![
5121 // left of context menu
5122 point(
5123 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5124 y_for_horizontal_positioning,
5125 ),
5126 // right of context menu
5127 point(
5128 menu.bounds.right() + HOVER_POPOVER_GAP,
5129 y_for_horizontal_positioning,
5130 ),
5131 // top of context menu
5132 point(
5133 menu.bounds.left(),
5134 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5135 ),
5136 // bottom of context menu
5137 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5138 ];
5139 possible_origins
5140 .into_iter()
5141 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5142 });
5143 origin_surrounding_menu.unwrap_or_else(|| {
5144 // fallback to existing above/below cursor logic
5145 // this might overlap menu or overflow in rare case
5146 if popover_bounds_above.is_contained_within(hitbox) {
5147 popover_bounds_above.origin
5148 } else {
5149 popover_bounds_below.origin
5150 }
5151 })
5152 };
5153
5154 window.defer_draw(element, final_origin, 2);
5155 }
5156
5157 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5158 window.paint_layer(layout.hitbox.bounds, |window| {
5159 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5160 let gutter_bg = cx.theme().colors().editor_gutter_background;
5161 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5162 window.paint_quad(fill(
5163 layout.position_map.text_hitbox.bounds,
5164 self.style.background,
5165 ));
5166
5167 if matches!(
5168 layout.mode,
5169 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5170 ) {
5171 let show_active_line_background = match layout.mode {
5172 EditorMode::Full {
5173 show_active_line_background,
5174 ..
5175 } => show_active_line_background,
5176 EditorMode::Minimap { .. } => true,
5177 _ => false,
5178 };
5179 let mut active_rows = layout.active_rows.iter().peekable();
5180 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5181 let mut end_row = start_row.0;
5182 while active_rows
5183 .peek()
5184 .map_or(false, |(active_row, has_selection)| {
5185 active_row.0 == end_row + 1
5186 && has_selection.selection == contains_non_empty_selection.selection
5187 })
5188 {
5189 active_rows.next().unwrap();
5190 end_row += 1;
5191 }
5192
5193 if show_active_line_background && !contains_non_empty_selection.selection {
5194 let highlight_h_range =
5195 match layout.position_map.snapshot.current_line_highlight {
5196 CurrentLineHighlight::Gutter => Some(Range {
5197 start: layout.hitbox.left(),
5198 end: layout.gutter_hitbox.right(),
5199 }),
5200 CurrentLineHighlight::Line => Some(Range {
5201 start: layout.position_map.text_hitbox.bounds.left(),
5202 end: layout.position_map.text_hitbox.bounds.right(),
5203 }),
5204 CurrentLineHighlight::All => Some(Range {
5205 start: layout.hitbox.left(),
5206 end: layout.hitbox.right(),
5207 }),
5208 CurrentLineHighlight::None => None,
5209 };
5210 if let Some(range) = highlight_h_range {
5211 let active_line_bg = cx.theme().colors().editor_active_line_background;
5212 let bounds = Bounds {
5213 origin: point(
5214 range.start,
5215 layout.hitbox.origin.y
5216 + (start_row.as_f32() - scroll_top)
5217 * layout.position_map.line_height,
5218 ),
5219 size: size(
5220 range.end - range.start,
5221 layout.position_map.line_height
5222 * (end_row - start_row.0 + 1) as f32,
5223 ),
5224 };
5225 window.paint_quad(fill(bounds, active_line_bg));
5226 }
5227 }
5228 }
5229
5230 let mut paint_highlight = |highlight_row_start: DisplayRow,
5231 highlight_row_end: DisplayRow,
5232 highlight: crate::LineHighlight,
5233 edges| {
5234 let mut origin_x = layout.hitbox.left();
5235 let mut width = layout.hitbox.size.width;
5236 if !highlight.include_gutter {
5237 origin_x += layout.gutter_hitbox.size.width;
5238 width -= layout.gutter_hitbox.size.width;
5239 }
5240
5241 let origin = point(
5242 origin_x,
5243 layout.hitbox.origin.y
5244 + (highlight_row_start.as_f32() - scroll_top)
5245 * layout.position_map.line_height,
5246 );
5247 let size = size(
5248 width,
5249 layout.position_map.line_height
5250 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5251 );
5252 let mut quad = fill(Bounds { origin, size }, highlight.background);
5253 if let Some(border_color) = highlight.border {
5254 quad.border_color = border_color;
5255 quad.border_widths = edges
5256 }
5257 window.paint_quad(quad);
5258 };
5259
5260 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5261 None;
5262 for (&new_row, &new_background) in &layout.highlighted_rows {
5263 match &mut current_paint {
5264 &mut Some((current_background, ref mut current_range, mut edges)) => {
5265 let new_range_started = current_background != new_background
5266 || current_range.end.next_row() != new_row;
5267 if new_range_started {
5268 if current_range.end.next_row() == new_row {
5269 edges.bottom = px(0.);
5270 };
5271 paint_highlight(
5272 current_range.start,
5273 current_range.end,
5274 current_background,
5275 edges,
5276 );
5277 let edges = Edges {
5278 top: if current_range.end.next_row() != new_row {
5279 px(1.)
5280 } else {
5281 px(0.)
5282 },
5283 bottom: px(1.),
5284 ..Default::default()
5285 };
5286 current_paint = Some((new_background, new_row..new_row, edges));
5287 continue;
5288 } else {
5289 current_range.end = current_range.end.next_row();
5290 }
5291 }
5292 None => {
5293 let edges = Edges {
5294 top: px(1.),
5295 bottom: px(1.),
5296 ..Default::default()
5297 };
5298 current_paint = Some((new_background, new_row..new_row, edges))
5299 }
5300 };
5301 }
5302 if let Some((color, range, edges)) = current_paint {
5303 paint_highlight(range.start, range.end, color, edges);
5304 }
5305
5306 for (guide_x, active) in layout.wrap_guides.iter() {
5307 let color = if *active {
5308 cx.theme().colors().editor_active_wrap_guide
5309 } else {
5310 cx.theme().colors().editor_wrap_guide
5311 };
5312 window.paint_quad(fill(
5313 Bounds {
5314 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5315 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5316 },
5317 color,
5318 ));
5319 }
5320 }
5321 })
5322 }
5323
5324 fn paint_indent_guides(
5325 &mut self,
5326 layout: &mut EditorLayout,
5327 window: &mut Window,
5328 cx: &mut App,
5329 ) {
5330 let Some(indent_guides) = &layout.indent_guides else {
5331 return;
5332 };
5333
5334 let faded_color = |color: Hsla, alpha: f32| {
5335 let mut faded = color;
5336 faded.a = alpha;
5337 faded
5338 };
5339
5340 for indent_guide in indent_guides {
5341 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
5342 let settings = indent_guide.settings;
5343
5344 // TODO fixed for now, expose them through themes later
5345 const INDENT_AWARE_ALPHA: f32 = 0.2;
5346 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
5347 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
5348 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
5349
5350 let line_color = match (settings.coloring, indent_guide.active) {
5351 (IndentGuideColoring::Disabled, _) => None,
5352 (IndentGuideColoring::Fixed, false) => {
5353 Some(cx.theme().colors().editor_indent_guide)
5354 }
5355 (IndentGuideColoring::Fixed, true) => {
5356 Some(cx.theme().colors().editor_indent_guide_active)
5357 }
5358 (IndentGuideColoring::IndentAware, false) => {
5359 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
5360 }
5361 (IndentGuideColoring::IndentAware, true) => {
5362 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
5363 }
5364 };
5365
5366 let background_color = match (settings.background_coloring, indent_guide.active) {
5367 (IndentGuideBackgroundColoring::Disabled, _) => None,
5368 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
5369 indent_accent_colors,
5370 INDENT_AWARE_BACKGROUND_ALPHA,
5371 )),
5372 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
5373 indent_accent_colors,
5374 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
5375 )),
5376 };
5377
5378 let requested_line_width = if indent_guide.active {
5379 settings.active_line_width
5380 } else {
5381 settings.line_width
5382 }
5383 .clamp(1, 10);
5384 let mut line_indicator_width = 0.;
5385 if let Some(color) = line_color {
5386 window.paint_quad(fill(
5387 Bounds {
5388 origin: indent_guide.origin,
5389 size: size(px(requested_line_width as f32), indent_guide.length),
5390 },
5391 color,
5392 ));
5393 line_indicator_width = requested_line_width as f32;
5394 }
5395
5396 if let Some(color) = background_color {
5397 let width = indent_guide.single_indent_width - px(line_indicator_width);
5398 window.paint_quad(fill(
5399 Bounds {
5400 origin: point(
5401 indent_guide.origin.x + px(line_indicator_width),
5402 indent_guide.origin.y,
5403 ),
5404 size: size(width, indent_guide.length),
5405 },
5406 color,
5407 ));
5408 }
5409 }
5410 }
5411
5412 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5413 let is_singleton = self.editor.read(cx).is_singleton(cx);
5414
5415 let line_height = layout.position_map.line_height;
5416 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
5417
5418 for LineNumberLayout {
5419 shaped_line,
5420 hitbox,
5421 } in layout.line_numbers.values()
5422 {
5423 let Some(hitbox) = hitbox else {
5424 continue;
5425 };
5426
5427 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
5428 let color = cx.theme().colors().editor_hover_line_number;
5429
5430 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
5431 line.paint(hitbox.origin, line_height, window, cx).log_err()
5432 } else {
5433 shaped_line
5434 .paint(hitbox.origin, line_height, window, cx)
5435 .log_err()
5436 }) else {
5437 continue;
5438 };
5439
5440 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
5441 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
5442 if is_singleton {
5443 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
5444 } else {
5445 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
5446 }
5447 }
5448 }
5449
5450 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5451 if layout.display_hunks.is_empty() {
5452 return;
5453 }
5454
5455 let line_height = layout.position_map.line_height;
5456 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5457 for (hunk, hitbox) in &layout.display_hunks {
5458 let hunk_to_paint = match hunk {
5459 DisplayDiffHunk::Folded { .. } => {
5460 let hunk_bounds = Self::diff_hunk_bounds(
5461 &layout.position_map.snapshot,
5462 line_height,
5463 layout.gutter_hitbox.bounds,
5464 &hunk,
5465 );
5466 Some((
5467 hunk_bounds,
5468 cx.theme().colors().version_control_modified,
5469 Corners::all(px(0.)),
5470 DiffHunkStatus::modified_none(),
5471 ))
5472 }
5473 DisplayDiffHunk::Unfolded {
5474 status,
5475 display_row_range,
5476 ..
5477 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
5478 DiffHunkStatusKind::Added => (
5479 hunk_hitbox.bounds,
5480 cx.theme().colors().version_control_added,
5481 Corners::all(px(0.)),
5482 *status,
5483 ),
5484 DiffHunkStatusKind::Modified => (
5485 hunk_hitbox.bounds,
5486 cx.theme().colors().version_control_modified,
5487 Corners::all(px(0.)),
5488 *status,
5489 ),
5490 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
5491 hunk_hitbox.bounds,
5492 cx.theme().colors().version_control_deleted,
5493 Corners::all(px(0.)),
5494 *status,
5495 ),
5496 DiffHunkStatusKind::Deleted => (
5497 Bounds::new(
5498 point(
5499 hunk_hitbox.origin.x - hunk_hitbox.size.width,
5500 hunk_hitbox.origin.y,
5501 ),
5502 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
5503 ),
5504 cx.theme().colors().version_control_deleted,
5505 Corners::all(1. * line_height),
5506 *status,
5507 ),
5508 }),
5509 };
5510
5511 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
5512 // Flatten the background color with the editor color to prevent
5513 // elements below transparent hunks from showing through
5514 let flattened_background_color = cx
5515 .theme()
5516 .colors()
5517 .editor_background
5518 .blend(background_color);
5519
5520 if !Self::diff_hunk_hollow(status, cx) {
5521 window.paint_quad(quad(
5522 hunk_bounds,
5523 corner_radii,
5524 flattened_background_color,
5525 Edges::default(),
5526 transparent_black(),
5527 BorderStyle::default(),
5528 ));
5529 } else {
5530 let flattened_unstaged_background_color = cx
5531 .theme()
5532 .colors()
5533 .editor_background
5534 .blend(background_color.opacity(0.3));
5535
5536 window.paint_quad(quad(
5537 hunk_bounds,
5538 corner_radii,
5539 flattened_unstaged_background_color,
5540 Edges::all(Pixels(1.0)),
5541 flattened_background_color,
5542 BorderStyle::Solid,
5543 ));
5544 }
5545 }
5546 }
5547 });
5548 }
5549
5550 fn gutter_strip_width(line_height: Pixels) -> Pixels {
5551 (0.275 * line_height).floor()
5552 }
5553
5554 fn diff_hunk_bounds(
5555 snapshot: &EditorSnapshot,
5556 line_height: Pixels,
5557 gutter_bounds: Bounds<Pixels>,
5558 hunk: &DisplayDiffHunk,
5559 ) -> Bounds<Pixels> {
5560 let scroll_position = snapshot.scroll_position();
5561 let scroll_top = scroll_position.y * line_height;
5562 let gutter_strip_width = Self::gutter_strip_width(line_height);
5563
5564 match hunk {
5565 DisplayDiffHunk::Folded { display_row, .. } => {
5566 let start_y = display_row.as_f32() * line_height - scroll_top;
5567 let end_y = start_y + line_height;
5568 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5569 let highlight_size = size(gutter_strip_width, end_y - start_y);
5570 Bounds::new(highlight_origin, highlight_size)
5571 }
5572 DisplayDiffHunk::Unfolded {
5573 display_row_range,
5574 status,
5575 ..
5576 } => {
5577 if status.is_deleted() && display_row_range.is_empty() {
5578 let row = display_row_range.start;
5579
5580 let offset = line_height / 2.;
5581 let start_y = row.as_f32() * line_height - offset - scroll_top;
5582 let end_y = start_y + line_height;
5583
5584 let width = (0.35 * line_height).floor();
5585 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5586 let highlight_size = size(width, end_y - start_y);
5587 Bounds::new(highlight_origin, highlight_size)
5588 } else {
5589 let start_row = display_row_range.start;
5590 let end_row = display_row_range.end;
5591 // If we're in a multibuffer, row range span might include an
5592 // excerpt header, so if we were to draw the marker straight away,
5593 // the hunk might include the rows of that header.
5594 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
5595 // Instead, we simply check whether the range we're dealing with includes
5596 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
5597 let end_row_in_current_excerpt = snapshot
5598 .blocks_in_range(start_row..end_row)
5599 .find_map(|(start_row, block)| {
5600 if matches!(block, Block::ExcerptBoundary { .. }) {
5601 Some(start_row)
5602 } else {
5603 None
5604 }
5605 })
5606 .unwrap_or(end_row);
5607
5608 let start_y = start_row.as_f32() * line_height - scroll_top;
5609 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
5610
5611 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5612 let highlight_size = size(gutter_strip_width, end_y - start_y);
5613 Bounds::new(highlight_origin, highlight_size)
5614 }
5615 }
5616 }
5617 }
5618
5619 fn paint_gutter_indicators(
5620 &self,
5621 layout: &mut EditorLayout,
5622 window: &mut Window,
5623 cx: &mut App,
5624 ) {
5625 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5626 window.with_element_namespace("crease_toggles", |window| {
5627 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
5628 crease_toggle.paint(window, cx);
5629 }
5630 });
5631
5632 window.with_element_namespace("expand_toggles", |window| {
5633 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
5634 expand_toggle.paint(window, cx);
5635 }
5636 });
5637
5638 for breakpoint in layout.breakpoints.iter_mut() {
5639 breakpoint.paint(window, cx);
5640 }
5641
5642 for test_indicator in layout.test_indicators.iter_mut() {
5643 test_indicator.paint(window, cx);
5644 }
5645 });
5646 }
5647
5648 fn paint_gutter_highlights(
5649 &self,
5650 layout: &mut EditorLayout,
5651 window: &mut Window,
5652 cx: &mut App,
5653 ) {
5654 for (_, hunk_hitbox) in &layout.display_hunks {
5655 if let Some(hunk_hitbox) = hunk_hitbox {
5656 if !self
5657 .editor
5658 .read(cx)
5659 .buffer()
5660 .read(cx)
5661 .all_diff_hunks_expanded()
5662 {
5663 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
5664 }
5665 }
5666 }
5667
5668 let show_git_gutter = layout
5669 .position_map
5670 .snapshot
5671 .show_git_diff_gutter
5672 .unwrap_or_else(|| {
5673 matches!(
5674 ProjectSettings::get_global(cx).git.git_gutter,
5675 Some(GitGutterSetting::TrackedFiles)
5676 )
5677 });
5678 if show_git_gutter {
5679 Self::paint_gutter_diff_hunks(layout, window, cx)
5680 }
5681
5682 let highlight_width = 0.275 * layout.position_map.line_height;
5683 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
5684 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5685 for (range, color) in &layout.highlighted_gutter_ranges {
5686 let start_row = if range.start.row() < layout.visible_display_row_range.start {
5687 layout.visible_display_row_range.start - DisplayRow(1)
5688 } else {
5689 range.start.row()
5690 };
5691 let end_row = if range.end.row() > layout.visible_display_row_range.end {
5692 layout.visible_display_row_range.end + DisplayRow(1)
5693 } else {
5694 range.end.row()
5695 };
5696
5697 let start_y = layout.gutter_hitbox.top()
5698 + start_row.0 as f32 * layout.position_map.line_height
5699 - layout.position_map.scroll_pixel_position.y;
5700 let end_y = layout.gutter_hitbox.top()
5701 + (end_row.0 + 1) as f32 * layout.position_map.line_height
5702 - layout.position_map.scroll_pixel_position.y;
5703 let bounds = Bounds::from_corners(
5704 point(layout.gutter_hitbox.left(), start_y),
5705 point(layout.gutter_hitbox.left() + highlight_width, end_y),
5706 );
5707 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
5708 }
5709 });
5710 }
5711
5712 fn paint_blamed_display_rows(
5713 &self,
5714 layout: &mut EditorLayout,
5715 window: &mut Window,
5716 cx: &mut App,
5717 ) {
5718 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
5719 return;
5720 };
5721
5722 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5723 for mut blame_element in blamed_display_rows.into_iter() {
5724 blame_element.paint(window, cx);
5725 }
5726 })
5727 }
5728
5729 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5730 window.with_content_mask(
5731 Some(ContentMask {
5732 bounds: layout.position_map.text_hitbox.bounds,
5733 }),
5734 |window| {
5735 let editor = self.editor.read(cx);
5736 if editor.mouse_cursor_hidden {
5737 window.set_window_cursor_style(CursorStyle::None);
5738 } else if let SelectionDragState::ReadyToDrag {
5739 mouse_down_time, ..
5740 } = &editor.selection_drag_state
5741 {
5742 let drag_and_drop_delay = Duration::from_millis(
5743 EditorSettings::get_global(cx).drag_and_drop_selection.delay,
5744 );
5745 if mouse_down_time.elapsed() >= drag_and_drop_delay {
5746 window.set_cursor_style(
5747 CursorStyle::DragCopy,
5748 &layout.position_map.text_hitbox,
5749 );
5750 }
5751 } else if matches!(
5752 editor.selection_drag_state,
5753 SelectionDragState::Dragging { .. }
5754 ) {
5755 window
5756 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
5757 } else if editor
5758 .hovered_link_state
5759 .as_ref()
5760 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
5761 {
5762 window.set_cursor_style(
5763 CursorStyle::PointingHand,
5764 &layout.position_map.text_hitbox,
5765 );
5766 } else {
5767 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
5768 };
5769
5770 self.paint_lines_background(layout, window, cx);
5771 let invisible_display_ranges = self.paint_highlights(layout, window);
5772 self.paint_document_colors(layout, window);
5773 self.paint_lines(&invisible_display_ranges, layout, window, cx);
5774 self.paint_redactions(layout, window);
5775 self.paint_cursors(layout, window, cx);
5776 self.paint_inline_diagnostics(layout, window, cx);
5777 self.paint_inline_blame(layout, window, cx);
5778 self.paint_inline_code_actions(layout, window, cx);
5779 self.paint_diff_hunk_controls(layout, window, cx);
5780 window.with_element_namespace("crease_trailers", |window| {
5781 for trailer in layout.crease_trailers.iter_mut().flatten() {
5782 trailer.element.paint(window, cx);
5783 }
5784 });
5785 },
5786 )
5787 }
5788
5789 fn paint_highlights(
5790 &mut self,
5791 layout: &mut EditorLayout,
5792 window: &mut Window,
5793 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
5794 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5795 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
5796 let line_end_overshoot = 0.15 * layout.position_map.line_height;
5797 for (range, color) in &layout.highlighted_ranges {
5798 self.paint_highlighted_range(
5799 range.clone(),
5800 true,
5801 *color,
5802 Pixels::ZERO,
5803 line_end_overshoot,
5804 layout,
5805 window,
5806 );
5807 }
5808
5809 let corner_radius = 0.15 * layout.position_map.line_height;
5810
5811 for (player_color, selections) in &layout.selections {
5812 for selection in selections.iter() {
5813 self.paint_highlighted_range(
5814 selection.range.clone(),
5815 true,
5816 player_color.selection,
5817 corner_radius,
5818 corner_radius * 2.,
5819 layout,
5820 window,
5821 );
5822
5823 if selection.is_local && !selection.range.is_empty() {
5824 invisible_display_ranges.push(selection.range.clone());
5825 }
5826 }
5827 }
5828 invisible_display_ranges
5829 })
5830 }
5831
5832 fn paint_lines(
5833 &mut self,
5834 invisible_display_ranges: &[Range<DisplayPoint>],
5835 layout: &mut EditorLayout,
5836 window: &mut Window,
5837 cx: &mut App,
5838 ) {
5839 let whitespace_setting = self
5840 .editor
5841 .read(cx)
5842 .buffer
5843 .read(cx)
5844 .language_settings(cx)
5845 .show_whitespaces;
5846
5847 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5848 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5849 line_with_invisibles.draw(
5850 layout,
5851 row,
5852 layout.content_origin,
5853 whitespace_setting,
5854 invisible_display_ranges,
5855 window,
5856 cx,
5857 )
5858 }
5859
5860 for line_element in &mut layout.line_elements {
5861 line_element.paint(window, cx);
5862 }
5863 }
5864
5865 fn paint_lines_background(
5866 &mut self,
5867 layout: &mut EditorLayout,
5868 window: &mut Window,
5869 cx: &mut App,
5870 ) {
5871 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5872 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5873 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
5874 }
5875 }
5876
5877 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
5878 if layout.redacted_ranges.is_empty() {
5879 return;
5880 }
5881
5882 let line_end_overshoot = layout.line_end_overshoot();
5883
5884 // A softer than perfect black
5885 let redaction_color = gpui::rgb(0x0e1111);
5886
5887 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5888 for range in layout.redacted_ranges.iter() {
5889 self.paint_highlighted_range(
5890 range.clone(),
5891 true,
5892 redaction_color.into(),
5893 Pixels::ZERO,
5894 line_end_overshoot,
5895 layout,
5896 window,
5897 );
5898 }
5899 });
5900 }
5901
5902 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
5903 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
5904 return;
5905 };
5906 if image_colors.is_empty()
5907 || colors_render_mode == &DocumentColorsRenderMode::None
5908 || colors_render_mode == &DocumentColorsRenderMode::Inlay
5909 {
5910 return;
5911 }
5912
5913 let line_end_overshoot = layout.line_end_overshoot();
5914
5915 for (range, color) in image_colors {
5916 match colors_render_mode {
5917 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
5918 DocumentColorsRenderMode::Background => {
5919 self.paint_highlighted_range(
5920 range.clone(),
5921 true,
5922 *color,
5923 Pixels::ZERO,
5924 line_end_overshoot,
5925 layout,
5926 window,
5927 );
5928 }
5929 DocumentColorsRenderMode::Border => {
5930 self.paint_highlighted_range(
5931 range.clone(),
5932 false,
5933 *color,
5934 Pixels::ZERO,
5935 line_end_overshoot,
5936 layout,
5937 window,
5938 );
5939 }
5940 }
5941 }
5942 }
5943
5944 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5945 for cursor in &mut layout.visible_cursors {
5946 cursor.paint(layout.content_origin, window, cx);
5947 }
5948 }
5949
5950 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5951 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
5952 return;
5953 };
5954 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
5955
5956 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
5957 let hitbox = &scrollbar_layout.hitbox;
5958 if scrollbars_layout.visible {
5959 let scrollbar_edges = match axis {
5960 ScrollbarAxis::Horizontal => Edges {
5961 top: Pixels::ZERO,
5962 right: Pixels::ZERO,
5963 bottom: Pixels::ZERO,
5964 left: Pixels::ZERO,
5965 },
5966 ScrollbarAxis::Vertical => Edges {
5967 top: Pixels::ZERO,
5968 right: Pixels::ZERO,
5969 bottom: Pixels::ZERO,
5970 left: ScrollbarLayout::BORDER_WIDTH,
5971 },
5972 };
5973
5974 window.paint_layer(hitbox.bounds, |window| {
5975 window.paint_quad(quad(
5976 hitbox.bounds,
5977 Corners::default(),
5978 cx.theme().colors().scrollbar_track_background,
5979 scrollbar_edges,
5980 cx.theme().colors().scrollbar_track_border,
5981 BorderStyle::Solid,
5982 ));
5983
5984 if axis == ScrollbarAxis::Vertical {
5985 let fast_markers =
5986 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5987 // Refresh slow scrollbar markers in the background. Below, we
5988 // paint whatever markers have already been computed.
5989 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5990
5991 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5992 for marker in markers.iter().chain(&fast_markers) {
5993 let mut marker = marker.clone();
5994 marker.bounds.origin += hitbox.origin;
5995 window.paint_quad(marker);
5996 }
5997 }
5998
5999 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6000 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6001 ScrollbarThumbState::Dragging => {
6002 cx.theme().colors().scrollbar_thumb_active_background
6003 }
6004 ScrollbarThumbState::Hovered => {
6005 cx.theme().colors().scrollbar_thumb_hover_background
6006 }
6007 ScrollbarThumbState::Idle => {
6008 cx.theme().colors().scrollbar_thumb_background
6009 }
6010 };
6011 window.paint_quad(quad(
6012 thumb_bounds,
6013 Corners::default(),
6014 scrollbar_thumb_color,
6015 scrollbar_edges,
6016 cx.theme().colors().scrollbar_thumb_border,
6017 BorderStyle::Solid,
6018 ));
6019
6020 if any_scrollbar_dragged {
6021 window.set_window_cursor_style(CursorStyle::Arrow);
6022 } else {
6023 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
6024 }
6025 }
6026 })
6027 }
6028 }
6029
6030 window.on_mouse_event({
6031 let editor = self.editor.clone();
6032 let scrollbars_layout = scrollbars_layout.clone();
6033
6034 let mut mouse_position = window.mouse_position();
6035 move |event: &MouseMoveEvent, phase, window, cx| {
6036 if phase == DispatchPhase::Capture {
6037 return;
6038 }
6039
6040 editor.update(cx, |editor, cx| {
6041 if let Some((scrollbar_layout, axis)) = event
6042 .pressed_button
6043 .filter(|button| *button == MouseButton::Left)
6044 .and(editor.scroll_manager.dragging_scrollbar_axis())
6045 .and_then(|axis| {
6046 scrollbars_layout
6047 .iter_scrollbars()
6048 .find(|(_, a)| *a == axis)
6049 })
6050 {
6051 let ScrollbarLayout {
6052 hitbox,
6053 text_unit_size,
6054 ..
6055 } = scrollbar_layout;
6056
6057 let old_position = mouse_position.along(axis);
6058 let new_position = event.position.along(axis);
6059 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6060 .contains(&old_position)
6061 {
6062 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6063 (p + (new_position - old_position) / *text_unit_size).max(0.)
6064 });
6065 editor.set_scroll_position(position, window, cx);
6066 }
6067
6068 editor.scroll_manager.show_scrollbars(window, cx);
6069 cx.stop_propagation();
6070 } else if let Some((layout, axis)) = scrollbars_layout
6071 .get_hovered_axis(window)
6072 .filter(|_| !event.dragging())
6073 {
6074 if layout.thumb_hovered(&event.position) {
6075 editor
6076 .scroll_manager
6077 .set_hovered_scroll_thumb_axis(axis, cx);
6078 } else {
6079 editor.scroll_manager.reset_scrollbar_state(cx);
6080 }
6081
6082 editor.scroll_manager.show_scrollbars(window, cx);
6083 } else {
6084 editor.scroll_manager.reset_scrollbar_state(cx);
6085 }
6086
6087 mouse_position = event.position;
6088 })
6089 }
6090 });
6091
6092 if any_scrollbar_dragged {
6093 window.on_mouse_event({
6094 let editor = self.editor.clone();
6095 move |_: &MouseUpEvent, phase, window, cx| {
6096 if phase == DispatchPhase::Capture {
6097 return;
6098 }
6099
6100 editor.update(cx, |editor, cx| {
6101 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6102 editor
6103 .scroll_manager
6104 .set_hovered_scroll_thumb_axis(axis, cx);
6105 } else {
6106 editor.scroll_manager.reset_scrollbar_state(cx);
6107 }
6108 cx.stop_propagation();
6109 });
6110 }
6111 });
6112 } else {
6113 window.on_mouse_event({
6114 let editor = self.editor.clone();
6115
6116 move |event: &MouseDownEvent, phase, window, cx| {
6117 if phase == DispatchPhase::Capture {
6118 return;
6119 }
6120 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6121 else {
6122 return;
6123 };
6124
6125 let ScrollbarLayout {
6126 hitbox,
6127 visible_range,
6128 text_unit_size,
6129 thumb_bounds,
6130 ..
6131 } = scrollbar_layout;
6132
6133 let Some(thumb_bounds) = thumb_bounds else {
6134 return;
6135 };
6136
6137 editor.update(cx, |editor, cx| {
6138 editor
6139 .scroll_manager
6140 .set_dragged_scroll_thumb_axis(axis, cx);
6141
6142 let event_position = event.position.along(axis);
6143
6144 if event_position < thumb_bounds.origin.along(axis)
6145 || thumb_bounds.bottom_right().along(axis) < event_position
6146 {
6147 let center_position = ((event_position - hitbox.origin.along(axis))
6148 / *text_unit_size)
6149 .round() as u32;
6150 let start_position = center_position.saturating_sub(
6151 (visible_range.end - visible_range.start) as u32 / 2,
6152 );
6153
6154 let position = editor
6155 .scroll_position(cx)
6156 .apply_along(axis, |_| start_position as f32);
6157
6158 editor.set_scroll_position(position, window, cx);
6159 } else {
6160 editor.scroll_manager.show_scrollbars(window, cx);
6161 }
6162
6163 cx.stop_propagation();
6164 });
6165 }
6166 });
6167 }
6168 }
6169
6170 fn collect_fast_scrollbar_markers(
6171 &self,
6172 layout: &EditorLayout,
6173 scrollbar_layout: &ScrollbarLayout,
6174 cx: &mut App,
6175 ) -> Vec<PaintQuad> {
6176 const LIMIT: usize = 100;
6177 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6178 return vec![];
6179 }
6180 let cursor_ranges = layout
6181 .cursors
6182 .iter()
6183 .map(|(point, color)| ColoredRange {
6184 start: point.row(),
6185 end: point.row(),
6186 color: *color,
6187 })
6188 .collect_vec();
6189 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6190 }
6191
6192 fn refresh_slow_scrollbar_markers(
6193 &self,
6194 layout: &EditorLayout,
6195 scrollbar_layout: &ScrollbarLayout,
6196 window: &mut Window,
6197 cx: &mut App,
6198 ) {
6199 self.editor.update(cx, |editor, cx| {
6200 if !editor.is_singleton(cx)
6201 || !editor
6202 .scrollbar_marker_state
6203 .should_refresh(scrollbar_layout.hitbox.size)
6204 {
6205 return;
6206 }
6207
6208 let scrollbar_layout = scrollbar_layout.clone();
6209 let background_highlights = editor.background_highlights.clone();
6210 let snapshot = layout.position_map.snapshot.clone();
6211 let theme = cx.theme().clone();
6212 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6213
6214 editor.scrollbar_marker_state.dirty = false;
6215 editor.scrollbar_marker_state.pending_refresh =
6216 Some(cx.spawn_in(window, async move |editor, cx| {
6217 let scrollbar_size = scrollbar_layout.hitbox.size;
6218 let scrollbar_markers = cx
6219 .background_spawn(async move {
6220 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
6221 let mut marker_quads = Vec::new();
6222 if scrollbar_settings.git_diff {
6223 let marker_row_ranges =
6224 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
6225 let start_display_row =
6226 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6227 .to_display_point(&snapshot.display_snapshot)
6228 .row();
6229 let mut end_display_row =
6230 MultiBufferPoint::new(hunk.row_range.end.0, 0)
6231 .to_display_point(&snapshot.display_snapshot)
6232 .row();
6233 if end_display_row != start_display_row {
6234 end_display_row.0 -= 1;
6235 }
6236 let color = match &hunk.status().kind {
6237 DiffHunkStatusKind::Added => {
6238 theme.colors().version_control_added
6239 }
6240 DiffHunkStatusKind::Modified => {
6241 theme.colors().version_control_modified
6242 }
6243 DiffHunkStatusKind::Deleted => {
6244 theme.colors().version_control_deleted
6245 }
6246 };
6247 ColoredRange {
6248 start: start_display_row,
6249 end: end_display_row,
6250 color,
6251 }
6252 });
6253
6254 marker_quads.extend(
6255 scrollbar_layout
6256 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
6257 );
6258 }
6259
6260 for (background_highlight_id, (_, background_ranges)) in
6261 background_highlights.iter()
6262 {
6263 let is_search_highlights = *background_highlight_id
6264 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
6265 let is_text_highlights = *background_highlight_id
6266 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
6267 let is_symbol_occurrences = *background_highlight_id
6268 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
6269 || *background_highlight_id
6270 == HighlightKey::Type(
6271 TypeId::of::<DocumentHighlightWrite>(),
6272 );
6273 if (is_search_highlights && scrollbar_settings.search_results)
6274 || (is_text_highlights && scrollbar_settings.selected_text)
6275 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
6276 {
6277 let mut color = theme.status().info;
6278 if is_symbol_occurrences {
6279 color.fade_out(0.5);
6280 }
6281 let marker_row_ranges = background_ranges.iter().map(|range| {
6282 let display_start = range
6283 .start
6284 .to_display_point(&snapshot.display_snapshot);
6285 let display_end =
6286 range.end.to_display_point(&snapshot.display_snapshot);
6287 ColoredRange {
6288 start: display_start.row(),
6289 end: display_end.row(),
6290 color,
6291 }
6292 });
6293 marker_quads.extend(
6294 scrollbar_layout
6295 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
6296 );
6297 }
6298 }
6299
6300 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
6301 let diagnostics = snapshot
6302 .buffer_snapshot
6303 .diagnostics_in_range::<Point>(Point::zero()..max_point)
6304 // Don't show diagnostics the user doesn't care about
6305 .filter(|diagnostic| {
6306 match (
6307 scrollbar_settings.diagnostics,
6308 diagnostic.diagnostic.severity,
6309 ) {
6310 (ScrollbarDiagnostics::All, _) => true,
6311 (
6312 ScrollbarDiagnostics::Error,
6313 lsp::DiagnosticSeverity::ERROR,
6314 ) => true,
6315 (
6316 ScrollbarDiagnostics::Warning,
6317 lsp::DiagnosticSeverity::ERROR
6318 | lsp::DiagnosticSeverity::WARNING,
6319 ) => true,
6320 (
6321 ScrollbarDiagnostics::Information,
6322 lsp::DiagnosticSeverity::ERROR
6323 | lsp::DiagnosticSeverity::WARNING
6324 | lsp::DiagnosticSeverity::INFORMATION,
6325 ) => true,
6326 (_, _) => false,
6327 }
6328 })
6329 // We want to sort by severity, in order to paint the most severe diagnostics last.
6330 .sorted_by_key(|diagnostic| {
6331 std::cmp::Reverse(diagnostic.diagnostic.severity)
6332 });
6333
6334 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
6335 let start_display = diagnostic
6336 .range
6337 .start
6338 .to_display_point(&snapshot.display_snapshot);
6339 let end_display = diagnostic
6340 .range
6341 .end
6342 .to_display_point(&snapshot.display_snapshot);
6343 let color = match diagnostic.diagnostic.severity {
6344 lsp::DiagnosticSeverity::ERROR => theme.status().error,
6345 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
6346 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
6347 _ => theme.status().hint,
6348 };
6349 ColoredRange {
6350 start: start_display.row(),
6351 end: end_display.row(),
6352 color,
6353 }
6354 });
6355 marker_quads.extend(
6356 scrollbar_layout
6357 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
6358 );
6359 }
6360
6361 Arc::from(marker_quads)
6362 })
6363 .await;
6364
6365 editor.update(cx, |editor, cx| {
6366 editor.scrollbar_marker_state.markers = scrollbar_markers;
6367 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
6368 editor.scrollbar_marker_state.pending_refresh = None;
6369 cx.notify();
6370 })?;
6371
6372 Ok(())
6373 }));
6374 });
6375 }
6376
6377 fn paint_highlighted_range(
6378 &self,
6379 range: Range<DisplayPoint>,
6380 fill: bool,
6381 color: Hsla,
6382 corner_radius: Pixels,
6383 line_end_overshoot: Pixels,
6384 layout: &EditorLayout,
6385 window: &mut Window,
6386 ) {
6387 let start_row = layout.visible_display_row_range.start;
6388 let end_row = layout.visible_display_row_range.end;
6389 if range.start != range.end {
6390 let row_range = if range.end.column() == 0 {
6391 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
6392 } else {
6393 cmp::max(range.start.row(), start_row)
6394 ..cmp::min(range.end.row().next_row(), end_row)
6395 };
6396
6397 let highlighted_range = HighlightedRange {
6398 color,
6399 line_height: layout.position_map.line_height,
6400 corner_radius,
6401 start_y: layout.content_origin.y
6402 + row_range.start.as_f32() * layout.position_map.line_height
6403 - layout.position_map.scroll_pixel_position.y,
6404 lines: row_range
6405 .iter_rows()
6406 .map(|row| {
6407 let line_layout =
6408 &layout.position_map.line_layouts[row.minus(start_row) as usize];
6409 HighlightedRangeLine {
6410 start_x: if row == range.start.row() {
6411 layout.content_origin.x
6412 + line_layout.x_for_index(range.start.column() as usize)
6413 - layout.position_map.scroll_pixel_position.x
6414 } else {
6415 layout.content_origin.x
6416 - layout.position_map.scroll_pixel_position.x
6417 },
6418 end_x: if row == range.end.row() {
6419 layout.content_origin.x
6420 + line_layout.x_for_index(range.end.column() as usize)
6421 - layout.position_map.scroll_pixel_position.x
6422 } else {
6423 layout.content_origin.x + line_layout.width + line_end_overshoot
6424 - layout.position_map.scroll_pixel_position.x
6425 },
6426 }
6427 })
6428 .collect(),
6429 };
6430
6431 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
6432 }
6433 }
6434
6435 fn paint_inline_diagnostics(
6436 &mut self,
6437 layout: &mut EditorLayout,
6438 window: &mut Window,
6439 cx: &mut App,
6440 ) {
6441 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
6442 inline_diagnostic.1.paint(window, cx);
6443 }
6444 }
6445
6446 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6447 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
6448 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6449 blame_layout.element.paint(window, cx);
6450 })
6451 }
6452 }
6453
6454 fn paint_inline_code_actions(
6455 &mut self,
6456 layout: &mut EditorLayout,
6457 window: &mut Window,
6458 cx: &mut App,
6459 ) {
6460 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
6461 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6462 inline_code_actions.paint(window, cx);
6463 })
6464 }
6465 }
6466
6467 fn paint_diff_hunk_controls(
6468 &mut self,
6469 layout: &mut EditorLayout,
6470 window: &mut Window,
6471 cx: &mut App,
6472 ) {
6473 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
6474 diff_hunk_control.paint(window, cx);
6475 }
6476 }
6477
6478 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6479 if let Some(mut layout) = layout.minimap.take() {
6480 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
6481 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
6482
6483 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
6484 window.with_element_namespace("minimap", |window| {
6485 layout.minimap.paint(window, cx);
6486 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
6487 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
6488 ScrollbarThumbState::Idle => {
6489 cx.theme().colors().minimap_thumb_background
6490 }
6491 ScrollbarThumbState::Hovered => {
6492 cx.theme().colors().minimap_thumb_hover_background
6493 }
6494 ScrollbarThumbState::Dragging => {
6495 cx.theme().colors().minimap_thumb_active_background
6496 }
6497 };
6498 let minimap_thumb_border = match layout.thumb_border_style {
6499 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
6500 MinimapThumbBorder::LeftOnly => Edges {
6501 left: ScrollbarLayout::BORDER_WIDTH,
6502 ..Default::default()
6503 },
6504 MinimapThumbBorder::LeftOpen => Edges {
6505 right: ScrollbarLayout::BORDER_WIDTH,
6506 top: ScrollbarLayout::BORDER_WIDTH,
6507 bottom: ScrollbarLayout::BORDER_WIDTH,
6508 ..Default::default()
6509 },
6510 MinimapThumbBorder::RightOpen => Edges {
6511 left: ScrollbarLayout::BORDER_WIDTH,
6512 top: ScrollbarLayout::BORDER_WIDTH,
6513 bottom: ScrollbarLayout::BORDER_WIDTH,
6514 ..Default::default()
6515 },
6516 MinimapThumbBorder::None => Default::default(),
6517 };
6518
6519 window.paint_layer(minimap_hitbox.bounds, |window| {
6520 window.paint_quad(quad(
6521 thumb_bounds,
6522 Corners::default(),
6523 minimap_thumb_color,
6524 minimap_thumb_border,
6525 cx.theme().colors().minimap_thumb_border,
6526 BorderStyle::Solid,
6527 ));
6528 });
6529 }
6530 });
6531 });
6532
6533 if dragging_minimap {
6534 window.set_window_cursor_style(CursorStyle::Arrow);
6535 } else {
6536 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
6537 }
6538
6539 let minimap_axis = ScrollbarAxis::Vertical;
6540 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
6541 .min(layout.minimap_line_height);
6542
6543 let mut mouse_position = window.mouse_position();
6544
6545 window.on_mouse_event({
6546 let editor = self.editor.clone();
6547
6548 let minimap_hitbox = minimap_hitbox.clone();
6549
6550 move |event: &MouseMoveEvent, phase, window, cx| {
6551 if phase == DispatchPhase::Capture {
6552 return;
6553 }
6554
6555 editor.update(cx, |editor, cx| {
6556 if event.pressed_button == Some(MouseButton::Left)
6557 && editor.scroll_manager.is_dragging_minimap()
6558 {
6559 let old_position = mouse_position.along(minimap_axis);
6560 let new_position = event.position.along(minimap_axis);
6561 if (minimap_hitbox.origin.along(minimap_axis)
6562 ..minimap_hitbox.bottom_right().along(minimap_axis))
6563 .contains(&old_position)
6564 {
6565 let position =
6566 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
6567 (p + (new_position - old_position) / pixels_per_line)
6568 .max(0.)
6569 });
6570 editor.set_scroll_position(position, window, cx);
6571 }
6572 cx.stop_propagation();
6573 } else {
6574 if minimap_hitbox.is_hovered(window) {
6575 editor.scroll_manager.set_is_hovering_minimap_thumb(
6576 !event.dragging()
6577 && layout
6578 .thumb_layout
6579 .thumb_bounds
6580 .is_some_and(|bounds| bounds.contains(&event.position)),
6581 cx,
6582 );
6583
6584 // Stop hover events from propagating to the
6585 // underlying editor if the minimap hitbox is hovered
6586 if !event.dragging() {
6587 cx.stop_propagation();
6588 }
6589 } else {
6590 editor.scroll_manager.hide_minimap_thumb(cx);
6591 }
6592 }
6593 mouse_position = event.position;
6594 });
6595 }
6596 });
6597
6598 if dragging_minimap {
6599 window.on_mouse_event({
6600 let editor = self.editor.clone();
6601 move |event: &MouseUpEvent, phase, window, cx| {
6602 if phase == DispatchPhase::Capture {
6603 return;
6604 }
6605
6606 editor.update(cx, |editor, cx| {
6607 if minimap_hitbox.is_hovered(window) {
6608 editor.scroll_manager.set_is_hovering_minimap_thumb(
6609 layout
6610 .thumb_layout
6611 .thumb_bounds
6612 .is_some_and(|bounds| bounds.contains(&event.position)),
6613 cx,
6614 );
6615 } else {
6616 editor.scroll_manager.hide_minimap_thumb(cx);
6617 }
6618 cx.stop_propagation();
6619 });
6620 }
6621 });
6622 } else {
6623 window.on_mouse_event({
6624 let editor = self.editor.clone();
6625
6626 move |event: &MouseDownEvent, phase, window, cx| {
6627 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
6628 return;
6629 }
6630
6631 let event_position = event.position;
6632
6633 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
6634 return;
6635 };
6636
6637 editor.update(cx, |editor, cx| {
6638 if !thumb_bounds.contains(&event_position) {
6639 let click_position =
6640 event_position.relative_to(&minimap_hitbox.origin).y;
6641
6642 let top_position = (click_position
6643 - thumb_bounds.size.along(minimap_axis) / 2.0)
6644 .max(Pixels::ZERO);
6645
6646 let scroll_offset = (layout.minimap_scroll_top
6647 + top_position / layout.minimap_line_height)
6648 .min(layout.max_scroll_top);
6649
6650 let scroll_position = editor
6651 .scroll_position(cx)
6652 .apply_along(minimap_axis, |_| scroll_offset);
6653 editor.set_scroll_position(scroll_position, window, cx);
6654 }
6655
6656 editor.scroll_manager.set_is_dragging_minimap(cx);
6657 cx.stop_propagation();
6658 });
6659 }
6660 });
6661 }
6662 }
6663 }
6664
6665 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6666 for mut block in layout.blocks.drain(..) {
6667 if block.overlaps_gutter {
6668 block.element.paint(window, cx);
6669 } else {
6670 let mut bounds = layout.hitbox.bounds;
6671 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
6672 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6673 block.element.paint(window, cx);
6674 })
6675 }
6676 }
6677 }
6678
6679 fn paint_inline_completion_popover(
6680 &mut self,
6681 layout: &mut EditorLayout,
6682 window: &mut Window,
6683 cx: &mut App,
6684 ) {
6685 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
6686 inline_completion_popover.paint(window, cx);
6687 }
6688 }
6689
6690 fn paint_mouse_context_menu(
6691 &mut self,
6692 layout: &mut EditorLayout,
6693 window: &mut Window,
6694 cx: &mut App,
6695 ) {
6696 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
6697 mouse_context_menu.paint(window, cx);
6698 }
6699 }
6700
6701 fn paint_scroll_wheel_listener(
6702 &mut self,
6703 layout: &EditorLayout,
6704 window: &mut Window,
6705 cx: &mut App,
6706 ) {
6707 window.on_mouse_event({
6708 let position_map = layout.position_map.clone();
6709 let editor = self.editor.clone();
6710 let hitbox = layout.hitbox.clone();
6711 let mut delta = ScrollDelta::default();
6712
6713 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
6714 // accidentally turn off their scrolling.
6715 let base_scroll_sensitivity =
6716 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
6717
6718 // Use a minimum fast_scroll_sensitivity for same reason above
6719 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
6720 .fast_scroll_sensitivity
6721 .max(0.01);
6722
6723 move |event: &ScrollWheelEvent, phase, window, cx| {
6724 let scroll_sensitivity = {
6725 if event.modifiers.alt {
6726 fast_scroll_sensitivity
6727 } else {
6728 base_scroll_sensitivity
6729 }
6730 };
6731
6732 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
6733 delta = delta.coalesce(event.delta);
6734 editor.update(cx, |editor, cx| {
6735 let position_map: &PositionMap = &position_map;
6736
6737 let line_height = position_map.line_height;
6738 let max_glyph_advance = position_map.em_advance;
6739 let (delta, axis) = match delta {
6740 gpui::ScrollDelta::Pixels(mut pixels) => {
6741 //Trackpad
6742 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
6743 (pixels, axis)
6744 }
6745
6746 gpui::ScrollDelta::Lines(lines) => {
6747 //Not trackpad
6748 let pixels =
6749 point(lines.x * max_glyph_advance, lines.y * line_height);
6750 (pixels, None)
6751 }
6752 };
6753
6754 let current_scroll_position = position_map.snapshot.scroll_position();
6755 let x = (current_scroll_position.x * max_glyph_advance
6756 - (delta.x * scroll_sensitivity))
6757 / max_glyph_advance;
6758 let y = (current_scroll_position.y * line_height
6759 - (delta.y * scroll_sensitivity))
6760 / line_height;
6761 let mut scroll_position =
6762 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
6763 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
6764 if forbid_vertical_scroll {
6765 scroll_position.y = current_scroll_position.y;
6766 }
6767
6768 if scroll_position != current_scroll_position {
6769 editor.scroll(scroll_position, axis, window, cx);
6770 cx.stop_propagation();
6771 } else if y < 0. {
6772 // Due to clamping, we may fail to detect cases of overscroll to the top;
6773 // We want the scroll manager to get an update in such cases and detect the change of direction
6774 // on the next frame.
6775 cx.notify();
6776 }
6777 });
6778 }
6779 }
6780 });
6781 }
6782
6783 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
6784 if layout.mode.is_minimap() {
6785 return;
6786 }
6787
6788 self.paint_scroll_wheel_listener(layout, window, cx);
6789
6790 window.on_mouse_event({
6791 let position_map = layout.position_map.clone();
6792 let editor = self.editor.clone();
6793 let diff_hunk_range =
6794 layout
6795 .display_hunks
6796 .iter()
6797 .find_map(|(hunk, hunk_hitbox)| match hunk {
6798 DisplayDiffHunk::Folded { .. } => None,
6799 DisplayDiffHunk::Unfolded {
6800 multi_buffer_range, ..
6801 } => {
6802 if hunk_hitbox
6803 .as_ref()
6804 .map(|hitbox| hitbox.is_hovered(window))
6805 .unwrap_or(false)
6806 {
6807 Some(multi_buffer_range.clone())
6808 } else {
6809 None
6810 }
6811 }
6812 });
6813 let line_numbers = layout.line_numbers.clone();
6814
6815 move |event: &MouseDownEvent, phase, window, cx| {
6816 if phase == DispatchPhase::Bubble {
6817 match event.button {
6818 MouseButton::Left => editor.update(cx, |editor, cx| {
6819 let pending_mouse_down = editor
6820 .pending_mouse_down
6821 .get_or_insert_with(Default::default)
6822 .clone();
6823
6824 *pending_mouse_down.borrow_mut() = Some(event.clone());
6825
6826 Self::mouse_left_down(
6827 editor,
6828 event,
6829 diff_hunk_range.clone(),
6830 &position_map,
6831 line_numbers.as_ref(),
6832 window,
6833 cx,
6834 );
6835 }),
6836 MouseButton::Right => editor.update(cx, |editor, cx| {
6837 Self::mouse_right_down(editor, event, &position_map, window, cx);
6838 }),
6839 MouseButton::Middle => editor.update(cx, |editor, cx| {
6840 Self::mouse_middle_down(editor, event, &position_map, window, cx);
6841 }),
6842 _ => {}
6843 };
6844 }
6845 }
6846 });
6847
6848 window.on_mouse_event({
6849 let editor = self.editor.clone();
6850 let position_map = layout.position_map.clone();
6851
6852 move |event: &MouseUpEvent, phase, window, cx| {
6853 if phase == DispatchPhase::Bubble {
6854 editor.update(cx, |editor, cx| {
6855 Self::mouse_up(editor, event, &position_map, window, cx)
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 let mut captured_mouse_down = None;
6865
6866 move |event: &MouseUpEvent, phase, window, cx| match phase {
6867 // Clear the pending mouse down during the capture phase,
6868 // so that it happens even if another event handler stops
6869 // propagation.
6870 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
6871 let pending_mouse_down = editor
6872 .pending_mouse_down
6873 .get_or_insert_with(Default::default)
6874 .clone();
6875
6876 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
6877 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
6878 captured_mouse_down = pending_mouse_down.take();
6879 window.refresh();
6880 }
6881 }),
6882 // Fire click handlers during the bubble phase.
6883 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
6884 if let Some(mouse_down) = captured_mouse_down.take() {
6885 let event = ClickEvent {
6886 down: mouse_down,
6887 up: event.clone(),
6888 };
6889 Self::click(editor, &event, &position_map, window, cx);
6890 }
6891 }),
6892 }
6893 });
6894
6895 window.on_mouse_event({
6896 let position_map = layout.position_map.clone();
6897 let editor = self.editor.clone();
6898
6899 move |event: &MouseMoveEvent, phase, window, cx| {
6900 if phase == DispatchPhase::Bubble {
6901 editor.update(cx, |editor, cx| {
6902 if editor.hover_state.focused(window, cx) {
6903 return;
6904 }
6905 if event.pressed_button == Some(MouseButton::Left)
6906 || event.pressed_button == Some(MouseButton::Middle)
6907 {
6908 Self::mouse_dragged(editor, event, &position_map, window, cx)
6909 }
6910
6911 Self::mouse_moved(editor, event, &position_map, window, cx)
6912 });
6913 }
6914 }
6915 });
6916 }
6917
6918 fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
6919 let style = &self.style;
6920 let font_size = style.text.font_size.to_pixels(window.rem_size());
6921 let layout = window.text_system().shape_line(
6922 SharedString::from(" ".repeat(column)),
6923 font_size,
6924 &[TextRun {
6925 len: column,
6926 font: style.text.font(),
6927 color: Hsla::default(),
6928 background_color: None,
6929 underline: None,
6930 strikethrough: None,
6931 }],
6932 None,
6933 );
6934
6935 layout.width
6936 }
6937
6938 fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
6939 let digit_count = snapshot.widest_line_number().ilog10() + 1;
6940 self.column_pixels(digit_count as usize, window)
6941 }
6942
6943 fn shape_line_number(
6944 &self,
6945 text: SharedString,
6946 color: Hsla,
6947 window: &mut Window,
6948 ) -> ShapedLine {
6949 let run = TextRun {
6950 len: text.len(),
6951 font: self.style.text.font(),
6952 color,
6953 background_color: None,
6954 underline: None,
6955 strikethrough: None,
6956 };
6957 window.text_system().shape_line(
6958 text,
6959 self.style.text.font_size.to_pixels(window.rem_size()),
6960 &[run],
6961 None,
6962 )
6963 }
6964
6965 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
6966 let unstaged = status.has_secondary_hunk();
6967 let unstaged_hollow = ProjectSettings::get_global(cx)
6968 .git
6969 .hunk_style
6970 .map_or(false, |style| {
6971 matches!(style, GitHunkStyleSetting::UnstagedHollow)
6972 });
6973
6974 unstaged == unstaged_hollow
6975 }
6976}
6977
6978fn header_jump_data(
6979 snapshot: &EditorSnapshot,
6980 block_row_start: DisplayRow,
6981 height: u32,
6982 for_excerpt: &ExcerptInfo,
6983) -> JumpData {
6984 let range = &for_excerpt.range;
6985 let buffer = &for_excerpt.buffer;
6986 let jump_anchor = range.primary.start;
6987
6988 let excerpt_start = range.context.start;
6989 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
6990 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
6991 0
6992 } else {
6993 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
6994 jump_position.row.saturating_sub(excerpt_start_point.row)
6995 };
6996
6997 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
6998 .saturating_sub(
6999 snapshot
7000 .scroll_anchor
7001 .scroll_position(&snapshot.display_snapshot)
7002 .y as u32,
7003 );
7004
7005 JumpData::MultiBufferPoint {
7006 excerpt_id: for_excerpt.id,
7007 anchor: jump_anchor,
7008 position: jump_position,
7009 line_offset_from_top,
7010 }
7011}
7012
7013pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
7014
7015impl AcceptEditPredictionBinding {
7016 pub fn keystroke(&self) -> Option<&Keystroke> {
7017 if let Some(binding) = self.0.as_ref() {
7018 match &binding.keystrokes() {
7019 [keystroke, ..] => Some(keystroke),
7020 _ => None,
7021 }
7022 } else {
7023 None
7024 }
7025 }
7026}
7027
7028fn prepaint_gutter_button(
7029 button: IconButton,
7030 row: DisplayRow,
7031 line_height: Pixels,
7032 gutter_dimensions: &GutterDimensions,
7033 scroll_pixel_position: gpui::Point<Pixels>,
7034 gutter_hitbox: &Hitbox,
7035 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
7036 window: &mut Window,
7037 cx: &mut App,
7038) -> AnyElement {
7039 let mut button = button.into_any_element();
7040
7041 let available_space = size(
7042 AvailableSpace::MinContent,
7043 AvailableSpace::Definite(line_height),
7044 );
7045 let indicator_size = button.layout_as_root(available_space, window, cx);
7046
7047 let blame_width = gutter_dimensions.git_blame_entries_width;
7048 let gutter_width = display_hunks
7049 .binary_search_by(|(hunk, _)| match hunk {
7050 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
7051 DisplayDiffHunk::Unfolded {
7052 display_row_range, ..
7053 } => {
7054 if display_row_range.end <= row {
7055 Ordering::Less
7056 } else if display_row_range.start > row {
7057 Ordering::Greater
7058 } else {
7059 Ordering::Equal
7060 }
7061 }
7062 })
7063 .ok()
7064 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
7065 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
7066
7067 let mut x = left_offset;
7068 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
7069 - indicator_size.width
7070 - left_offset;
7071 x += available_width / 2.;
7072
7073 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
7074 y += (line_height - indicator_size.height) / 2.;
7075
7076 button.prepaint_as_root(
7077 gutter_hitbox.origin + point(x, y),
7078 available_space,
7079 window,
7080 cx,
7081 );
7082 button
7083}
7084
7085fn render_inline_blame_entry(
7086 blame_entry: BlameEntry,
7087 style: &EditorStyle,
7088 cx: &mut App,
7089) -> Option<AnyElement> {
7090 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7091 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
7092}
7093
7094fn render_blame_entry_popover(
7095 blame_entry: BlameEntry,
7096 scroll_handle: ScrollHandle,
7097 commit_message: Option<ParsedCommitMessage>,
7098 markdown: Entity<Markdown>,
7099 workspace: WeakEntity<Workspace>,
7100 blame: &Entity<GitBlame>,
7101 window: &mut Window,
7102 cx: &mut App,
7103) -> Option<AnyElement> {
7104 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7105 let blame = blame.read(cx);
7106 let repository = blame.repository(cx)?.clone();
7107 renderer.render_blame_entry_popover(
7108 blame_entry,
7109 scroll_handle,
7110 commit_message,
7111 markdown,
7112 repository,
7113 workspace,
7114 window,
7115 cx,
7116 )
7117}
7118
7119fn render_blame_entry(
7120 ix: usize,
7121 blame: &Entity<GitBlame>,
7122 blame_entry: BlameEntry,
7123 style: &EditorStyle,
7124 last_used_color: &mut Option<(PlayerColor, Oid)>,
7125 editor: Entity<Editor>,
7126 workspace: Entity<Workspace>,
7127 renderer: Arc<dyn BlameRenderer>,
7128 cx: &mut App,
7129) -> Option<AnyElement> {
7130 let mut sha_color = cx
7131 .theme()
7132 .players()
7133 .color_for_participant(blame_entry.sha.into());
7134
7135 // If the last color we used is the same as the one we get for this line, but
7136 // the commit SHAs are different, then we try again to get a different color.
7137 match *last_used_color {
7138 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
7139 let index: u32 = blame_entry.sha.into();
7140 sha_color = cx.theme().players().color_for_participant(index + 1);
7141 }
7142 _ => {}
7143 };
7144 last_used_color.replace((sha_color, blame_entry.sha));
7145
7146 let blame = blame.read(cx);
7147 let details = blame.details_for_entry(&blame_entry);
7148 let repository = blame.repository(cx)?;
7149 renderer.render_blame_entry(
7150 &style.text,
7151 blame_entry,
7152 details,
7153 repository,
7154 workspace.downgrade(),
7155 editor,
7156 ix,
7157 sha_color.cursor,
7158 cx,
7159 )
7160}
7161
7162#[derive(Debug)]
7163pub(crate) struct LineWithInvisibles {
7164 fragments: SmallVec<[LineFragment; 1]>,
7165 invisibles: Vec<Invisible>,
7166 len: usize,
7167 pub(crate) width: Pixels,
7168 font_size: Pixels,
7169}
7170
7171enum LineFragment {
7172 Text(ShapedLine),
7173 Element {
7174 id: ChunkRendererId,
7175 element: Option<AnyElement>,
7176 size: Size<Pixels>,
7177 len: usize,
7178 },
7179}
7180
7181impl fmt::Debug for LineFragment {
7182 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7183 match self {
7184 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
7185 LineFragment::Element { size, len, .. } => f
7186 .debug_struct("Element")
7187 .field("size", size)
7188 .field("len", len)
7189 .finish(),
7190 }
7191 }
7192}
7193
7194impl LineWithInvisibles {
7195 fn from_chunks<'a>(
7196 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
7197 editor_style: &EditorStyle,
7198 max_line_len: usize,
7199 max_line_count: usize,
7200 editor_mode: &EditorMode,
7201 text_width: Pixels,
7202 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7203 window: &mut Window,
7204 cx: &mut App,
7205 ) -> Vec<Self> {
7206 let text_style = &editor_style.text;
7207 let mut layouts = Vec::with_capacity(max_line_count);
7208 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
7209 let mut line = String::new();
7210 let mut invisibles = Vec::new();
7211 let mut width = Pixels::ZERO;
7212 let mut len = 0;
7213 let mut styles = Vec::new();
7214 let mut non_whitespace_added = false;
7215 let mut row = 0;
7216 let mut line_exceeded_max_len = false;
7217 let font_size = text_style.font_size.to_pixels(window.rem_size());
7218
7219 let ellipsis = SharedString::from("⋯");
7220
7221 for highlighted_chunk in chunks.chain([HighlightedChunk {
7222 text: "\n",
7223 style: None,
7224 is_tab: false,
7225 is_inlay: false,
7226 replacement: None,
7227 }]) {
7228 if let Some(replacement) = highlighted_chunk.replacement {
7229 if !line.is_empty() {
7230 let shaped_line = window.text_system().shape_line(
7231 line.clone().into(),
7232 font_size,
7233 &styles,
7234 None,
7235 );
7236 width += shaped_line.width;
7237 len += shaped_line.len;
7238 fragments.push(LineFragment::Text(shaped_line));
7239 line.clear();
7240 styles.clear();
7241 }
7242
7243 match replacement {
7244 ChunkReplacement::Renderer(renderer) => {
7245 let available_width = if renderer.constrain_width {
7246 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
7247 ellipsis.clone()
7248 } else {
7249 SharedString::from(Arc::from(highlighted_chunk.text))
7250 };
7251 let shaped_line = window.text_system().shape_line(
7252 chunk,
7253 font_size,
7254 &[text_style.to_run(highlighted_chunk.text.len())],
7255 None,
7256 );
7257 AvailableSpace::Definite(shaped_line.width)
7258 } else {
7259 AvailableSpace::MinContent
7260 };
7261
7262 let mut element = (renderer.render)(&mut ChunkRendererContext {
7263 context: cx,
7264 window,
7265 max_width: text_width,
7266 });
7267 let line_height = text_style.line_height_in_pixels(window.rem_size());
7268 let size = element.layout_as_root(
7269 size(available_width, AvailableSpace::Definite(line_height)),
7270 window,
7271 cx,
7272 );
7273
7274 width += size.width;
7275 len += highlighted_chunk.text.len();
7276 fragments.push(LineFragment::Element {
7277 id: renderer.id,
7278 element: Some(element),
7279 size,
7280 len: highlighted_chunk.text.len(),
7281 });
7282 }
7283 ChunkReplacement::Str(x) => {
7284 let text_style = if let Some(style) = highlighted_chunk.style {
7285 Cow::Owned(text_style.clone().highlight(style))
7286 } else {
7287 Cow::Borrowed(text_style)
7288 };
7289
7290 let run = TextRun {
7291 len: x.len(),
7292 font: text_style.font(),
7293 color: text_style.color,
7294 background_color: text_style.background_color,
7295 underline: text_style.underline,
7296 strikethrough: text_style.strikethrough,
7297 };
7298 let line_layout = window
7299 .text_system()
7300 .shape_line(x, font_size, &[run], None)
7301 .with_len(highlighted_chunk.text.len());
7302
7303 width += line_layout.width;
7304 len += highlighted_chunk.text.len();
7305 fragments.push(LineFragment::Text(line_layout))
7306 }
7307 }
7308 } else {
7309 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
7310 if ix > 0 {
7311 let shaped_line = window.text_system().shape_line(
7312 line.clone().into(),
7313 font_size,
7314 &styles,
7315 None,
7316 );
7317 width += shaped_line.width;
7318 len += shaped_line.len;
7319 fragments.push(LineFragment::Text(shaped_line));
7320 layouts.push(Self {
7321 width: mem::take(&mut width),
7322 len: mem::take(&mut len),
7323 fragments: mem::take(&mut fragments),
7324 invisibles: std::mem::take(&mut invisibles),
7325 font_size,
7326 });
7327
7328 line.clear();
7329 styles.clear();
7330 row += 1;
7331 line_exceeded_max_len = false;
7332 non_whitespace_added = false;
7333 if row == max_line_count {
7334 return layouts;
7335 }
7336 }
7337
7338 if !line_chunk.is_empty() && !line_exceeded_max_len {
7339 let text_style = if let Some(style) = highlighted_chunk.style {
7340 Cow::Owned(text_style.clone().highlight(style))
7341 } else {
7342 Cow::Borrowed(text_style)
7343 };
7344
7345 if line.len() + line_chunk.len() > max_line_len {
7346 let mut chunk_len = max_line_len - line.len();
7347 while !line_chunk.is_char_boundary(chunk_len) {
7348 chunk_len -= 1;
7349 }
7350 line_chunk = &line_chunk[..chunk_len];
7351 line_exceeded_max_len = true;
7352 }
7353
7354 styles.push(TextRun {
7355 len: line_chunk.len(),
7356 font: text_style.font(),
7357 color: text_style.color,
7358 background_color: text_style.background_color,
7359 underline: text_style.underline,
7360 strikethrough: text_style.strikethrough,
7361 });
7362
7363 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
7364 // Line wrap pads its contents with fake whitespaces,
7365 // avoid printing them
7366 let is_soft_wrapped = is_row_soft_wrapped(row);
7367 if highlighted_chunk.is_tab {
7368 if non_whitespace_added || !is_soft_wrapped {
7369 invisibles.push(Invisible::Tab {
7370 line_start_offset: line.len(),
7371 line_end_offset: line.len() + line_chunk.len(),
7372 });
7373 }
7374 } else {
7375 invisibles.extend(line_chunk.char_indices().filter_map(
7376 |(index, c)| {
7377 let is_whitespace = c.is_whitespace();
7378 non_whitespace_added |= !is_whitespace;
7379 if is_whitespace
7380 && (non_whitespace_added || !is_soft_wrapped)
7381 {
7382 Some(Invisible::Whitespace {
7383 line_offset: line.len() + index,
7384 })
7385 } else {
7386 None
7387 }
7388 },
7389 ))
7390 }
7391 }
7392
7393 line.push_str(line_chunk);
7394 }
7395 }
7396 }
7397 }
7398
7399 layouts
7400 }
7401
7402 fn prepaint(
7403 &mut self,
7404 line_height: Pixels,
7405 scroll_pixel_position: gpui::Point<Pixels>,
7406 row: DisplayRow,
7407 content_origin: gpui::Point<Pixels>,
7408 line_elements: &mut SmallVec<[AnyElement; 1]>,
7409 window: &mut Window,
7410 cx: &mut App,
7411 ) {
7412 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
7413 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
7414 for fragment in &mut self.fragments {
7415 match fragment {
7416 LineFragment::Text(line) => {
7417 fragment_origin.x += line.width;
7418 }
7419 LineFragment::Element { element, size, .. } => {
7420 let mut element = element
7421 .take()
7422 .expect("you can't prepaint LineWithInvisibles twice");
7423
7424 // Center the element vertically within the line.
7425 let mut element_origin = fragment_origin;
7426 element_origin.y += (line_height - size.height) / 2.;
7427 element.prepaint_at(element_origin, window, cx);
7428 line_elements.push(element);
7429
7430 fragment_origin.x += size.width;
7431 }
7432 }
7433 }
7434 }
7435
7436 fn draw(
7437 &self,
7438 layout: &EditorLayout,
7439 row: DisplayRow,
7440 content_origin: gpui::Point<Pixels>,
7441 whitespace_setting: ShowWhitespaceSetting,
7442 selection_ranges: &[Range<DisplayPoint>],
7443 window: &mut Window,
7444 cx: &mut App,
7445 ) {
7446 let line_height = layout.position_map.line_height;
7447 let line_y = line_height
7448 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7449
7450 let mut fragment_origin =
7451 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7452
7453 for fragment in &self.fragments {
7454 match fragment {
7455 LineFragment::Text(line) => {
7456 line.paint(fragment_origin, line_height, window, cx)
7457 .log_err();
7458 fragment_origin.x += line.width;
7459 }
7460 LineFragment::Element { size, .. } => {
7461 fragment_origin.x += size.width;
7462 }
7463 }
7464 }
7465
7466 self.draw_invisibles(
7467 selection_ranges,
7468 layout,
7469 content_origin,
7470 line_y,
7471 row,
7472 line_height,
7473 whitespace_setting,
7474 window,
7475 cx,
7476 );
7477 }
7478
7479 fn draw_background(
7480 &self,
7481 layout: &EditorLayout,
7482 row: DisplayRow,
7483 content_origin: gpui::Point<Pixels>,
7484 window: &mut Window,
7485 cx: &mut App,
7486 ) {
7487 let line_height = layout.position_map.line_height;
7488 let line_y = line_height
7489 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7490
7491 let mut fragment_origin =
7492 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7493
7494 for fragment in &self.fragments {
7495 match fragment {
7496 LineFragment::Text(line) => {
7497 line.paint_background(fragment_origin, line_height, window, cx)
7498 .log_err();
7499 fragment_origin.x += line.width;
7500 }
7501 LineFragment::Element { size, .. } => {
7502 fragment_origin.x += size.width;
7503 }
7504 }
7505 }
7506 }
7507
7508 fn draw_invisibles(
7509 &self,
7510 selection_ranges: &[Range<DisplayPoint>],
7511 layout: &EditorLayout,
7512 content_origin: gpui::Point<Pixels>,
7513 line_y: Pixels,
7514 row: DisplayRow,
7515 line_height: Pixels,
7516 whitespace_setting: ShowWhitespaceSetting,
7517 window: &mut Window,
7518 cx: &mut App,
7519 ) {
7520 let extract_whitespace_info = |invisible: &Invisible| {
7521 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
7522 Invisible::Tab {
7523 line_start_offset,
7524 line_end_offset,
7525 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
7526 Invisible::Whitespace { line_offset } => {
7527 (*line_offset, line_offset + 1, &layout.space_invisible)
7528 }
7529 };
7530
7531 let x_offset = self.x_for_index(token_offset);
7532 let invisible_offset =
7533 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
7534 let origin = content_origin
7535 + gpui::point(
7536 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
7537 line_y,
7538 );
7539
7540 (
7541 [token_offset, token_end_offset],
7542 Box::new(move |window: &mut Window, cx: &mut App| {
7543 invisible_symbol
7544 .paint(origin, line_height, window, cx)
7545 .log_err();
7546 }),
7547 )
7548 };
7549
7550 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
7551 match whitespace_setting {
7552 ShowWhitespaceSetting::None => (),
7553 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
7554 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
7555 let invisible_point = DisplayPoint::new(row, start as u32);
7556 if !selection_ranges
7557 .iter()
7558 .any(|region| region.start <= invisible_point && invisible_point < region.end)
7559 {
7560 return;
7561 }
7562
7563 paint(window, cx);
7564 }),
7565
7566 ShowWhitespaceSetting::Trailing => {
7567 let mut previous_start = self.len;
7568 for ([start, end], paint) in invisible_iter.rev() {
7569 if previous_start != end {
7570 break;
7571 }
7572 previous_start = start;
7573 paint(window, cx);
7574 }
7575 }
7576
7577 // For a whitespace to be on a boundary, any of the following conditions need to be met:
7578 // - It is a tab
7579 // - It is adjacent to an edge (start or end)
7580 // - It is adjacent to a whitespace (left or right)
7581 ShowWhitespaceSetting::Boundary => {
7582 // 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
7583 // the above cases.
7584 // Note: We zip in the original `invisibles` to check for tab equality
7585 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
7586 for (([start, end], paint), invisible) in
7587 invisible_iter.zip_eq(self.invisibles.iter())
7588 {
7589 let should_render = match (&last_seen, invisible) {
7590 (_, Invisible::Tab { .. }) => true,
7591 (Some((_, last_end, _)), _) => *last_end == start,
7592 _ => false,
7593 };
7594
7595 if should_render || start == 0 || end == self.len {
7596 paint(window, cx);
7597
7598 // Since we are scanning from the left, we will skip over the first available whitespace that is part
7599 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
7600 if let Some((should_render_last, last_end, paint_last)) = last_seen {
7601 // Note that we need to make sure that the last one is actually adjacent
7602 if !should_render_last && last_end == start {
7603 paint_last(window, cx);
7604 }
7605 }
7606 }
7607
7608 // Manually render anything within a selection
7609 let invisible_point = DisplayPoint::new(row, start as u32);
7610 if selection_ranges.iter().any(|region| {
7611 region.start <= invisible_point && invisible_point < region.end
7612 }) {
7613 paint(window, cx);
7614 }
7615
7616 last_seen = Some((should_render, end, paint));
7617 }
7618 }
7619 }
7620 }
7621
7622 pub fn x_for_index(&self, index: usize) -> Pixels {
7623 let mut fragment_start_x = Pixels::ZERO;
7624 let mut fragment_start_index = 0;
7625
7626 for fragment in &self.fragments {
7627 match fragment {
7628 LineFragment::Text(shaped_line) => {
7629 let fragment_end_index = fragment_start_index + shaped_line.len;
7630 if index < fragment_end_index {
7631 return fragment_start_x
7632 + shaped_line.x_for_index(index - fragment_start_index);
7633 }
7634 fragment_start_x += shaped_line.width;
7635 fragment_start_index = fragment_end_index;
7636 }
7637 LineFragment::Element { len, size, .. } => {
7638 let fragment_end_index = fragment_start_index + len;
7639 if index < fragment_end_index {
7640 return fragment_start_x;
7641 }
7642 fragment_start_x += size.width;
7643 fragment_start_index = fragment_end_index;
7644 }
7645 }
7646 }
7647
7648 fragment_start_x
7649 }
7650
7651 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
7652 let mut fragment_start_x = Pixels::ZERO;
7653 let mut fragment_start_index = 0;
7654
7655 for fragment in &self.fragments {
7656 match fragment {
7657 LineFragment::Text(shaped_line) => {
7658 let fragment_end_x = fragment_start_x + shaped_line.width;
7659 if x < fragment_end_x {
7660 return Some(
7661 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
7662 );
7663 }
7664 fragment_start_x = fragment_end_x;
7665 fragment_start_index += shaped_line.len;
7666 }
7667 LineFragment::Element { len, size, .. } => {
7668 let fragment_end_x = fragment_start_x + size.width;
7669 if x < fragment_end_x {
7670 return Some(fragment_start_index);
7671 }
7672 fragment_start_index += len;
7673 fragment_start_x = fragment_end_x;
7674 }
7675 }
7676 }
7677
7678 None
7679 }
7680
7681 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
7682 let mut fragment_start_index = 0;
7683
7684 for fragment in &self.fragments {
7685 match fragment {
7686 LineFragment::Text(shaped_line) => {
7687 let fragment_end_index = fragment_start_index + shaped_line.len;
7688 if index < fragment_end_index {
7689 return shaped_line.font_id_for_index(index - fragment_start_index);
7690 }
7691 fragment_start_index = fragment_end_index;
7692 }
7693 LineFragment::Element { len, .. } => {
7694 let fragment_end_index = fragment_start_index + len;
7695 if index < fragment_end_index {
7696 return None;
7697 }
7698 fragment_start_index = fragment_end_index;
7699 }
7700 }
7701 }
7702
7703 None
7704 }
7705}
7706
7707#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7708enum Invisible {
7709 /// A tab character
7710 ///
7711 /// A tab character is internally represented by spaces (configured by the user's tab width)
7712 /// aligned to the nearest column, so it's necessary to store the start and end offset for
7713 /// adjacency checks.
7714 Tab {
7715 line_start_offset: usize,
7716 line_end_offset: usize,
7717 },
7718 Whitespace {
7719 line_offset: usize,
7720 },
7721}
7722
7723impl EditorElement {
7724 /// Returns the rem size to use when rendering the [`EditorElement`].
7725 ///
7726 /// This allows UI elements to scale based on the `buffer_font_size`.
7727 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
7728 match self.editor.read(cx).mode {
7729 EditorMode::Full {
7730 scale_ui_elements_with_buffer_font_size: true,
7731 ..
7732 }
7733 | EditorMode::Minimap { .. } => {
7734 let buffer_font_size = self.style.text.font_size;
7735 match buffer_font_size {
7736 AbsoluteLength::Pixels(pixels) => {
7737 let rem_size_scale = {
7738 // Our default UI font size is 14px on a 16px base scale.
7739 // This means the default UI font size is 0.875rems.
7740 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
7741
7742 // We then determine the delta between a single rem and the default font
7743 // size scale.
7744 let default_font_size_delta = 1. - default_font_size_scale;
7745
7746 // Finally, we add this delta to 1rem to get the scale factor that
7747 // should be used to scale up the UI.
7748 1. + default_font_size_delta
7749 };
7750
7751 Some(pixels * rem_size_scale)
7752 }
7753 AbsoluteLength::Rems(rems) => {
7754 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
7755 }
7756 }
7757 }
7758 // We currently use single-line and auto-height editors in UI contexts,
7759 // so we don't want to scale everything with the buffer font size, as it
7760 // ends up looking off.
7761 _ => None,
7762 }
7763 }
7764
7765 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
7766 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
7767 parent.upgrade()
7768 } else {
7769 Some(self.editor.clone())
7770 }
7771 }
7772}
7773
7774impl Element for EditorElement {
7775 type RequestLayoutState = ();
7776 type PrepaintState = EditorLayout;
7777
7778 fn id(&self) -> Option<ElementId> {
7779 None
7780 }
7781
7782 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
7783 None
7784 }
7785
7786 fn request_layout(
7787 &mut self,
7788 _: Option<&GlobalElementId>,
7789 _inspector_id: Option<&gpui::InspectorElementId>,
7790 window: &mut Window,
7791 cx: &mut App,
7792 ) -> (gpui::LayoutId, ()) {
7793 let rem_size = self.rem_size(cx);
7794 window.with_rem_size(rem_size, |window| {
7795 self.editor.update(cx, |editor, cx| {
7796 editor.set_style(self.style.clone(), window, cx);
7797
7798 let layout_id = match editor.mode {
7799 EditorMode::SingleLine => {
7800 let rem_size = window.rem_size();
7801 let height = self.style.text.line_height_in_pixels(rem_size);
7802 let mut style = Style::default();
7803 style.size.height = height.into();
7804 style.size.width = relative(1.).into();
7805 window.request_layout(style, None, cx)
7806 }
7807 EditorMode::AutoHeight {
7808 min_lines,
7809 max_lines,
7810 } => {
7811 let editor_handle = cx.entity().clone();
7812 let max_line_number_width =
7813 self.max_line_number_width(&editor.snapshot(window, cx), window);
7814 window.request_measured_layout(
7815 Style::default(),
7816 move |known_dimensions, available_space, window, cx| {
7817 editor_handle
7818 .update(cx, |editor, cx| {
7819 compute_auto_height_layout(
7820 editor,
7821 min_lines,
7822 max_lines,
7823 max_line_number_width,
7824 known_dimensions,
7825 available_space.width,
7826 window,
7827 cx,
7828 )
7829 })
7830 .unwrap_or_default()
7831 },
7832 )
7833 }
7834 EditorMode::Minimap { .. } => {
7835 let mut style = Style::default();
7836 style.size.width = relative(1.).into();
7837 style.size.height = relative(1.).into();
7838 window.request_layout(style, None, cx)
7839 }
7840 EditorMode::Full {
7841 sized_by_content, ..
7842 } => {
7843 let mut style = Style::default();
7844 style.size.width = relative(1.).into();
7845 if sized_by_content {
7846 let snapshot = editor.snapshot(window, cx);
7847 let line_height =
7848 self.style.text.line_height_in_pixels(window.rem_size());
7849 let scroll_height =
7850 (snapshot.max_point().row().next_row().0 as f32) * line_height;
7851 style.size.height = scroll_height.into();
7852 } else {
7853 style.size.height = relative(1.).into();
7854 }
7855 window.request_layout(style, None, cx)
7856 }
7857 };
7858
7859 (layout_id, ())
7860 })
7861 })
7862 }
7863
7864 fn prepaint(
7865 &mut self,
7866 _: Option<&GlobalElementId>,
7867 _inspector_id: Option<&gpui::InspectorElementId>,
7868 bounds: Bounds<Pixels>,
7869 _: &mut Self::RequestLayoutState,
7870 window: &mut Window,
7871 cx: &mut App,
7872 ) -> Self::PrepaintState {
7873 let text_style = TextStyleRefinement {
7874 font_size: Some(self.style.text.font_size),
7875 line_height: Some(self.style.text.line_height),
7876 ..Default::default()
7877 };
7878
7879 let is_minimap = self.editor.read(cx).mode.is_minimap();
7880
7881 if !is_minimap {
7882 let focus_handle = self.editor.focus_handle(cx);
7883 window.set_view_id(self.editor.entity_id());
7884 window.set_focus_handle(&focus_handle, cx);
7885 }
7886
7887 let rem_size = self.rem_size(cx);
7888 window.with_rem_size(rem_size, |window| {
7889 window.with_text_style(Some(text_style), |window| {
7890 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7891 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
7892 (editor.snapshot(window, cx), editor.read_only(cx))
7893 });
7894 let style = self.style.clone();
7895
7896 let rem_size = window.rem_size();
7897 let font_id = window.text_system().resolve_font(&style.text.font());
7898 let font_size = style.text.font_size.to_pixels(rem_size);
7899 let line_height = style.text.line_height_in_pixels(rem_size);
7900 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
7901 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
7902 let glyph_grid_cell = size(em_advance, line_height);
7903
7904 let gutter_dimensions = snapshot
7905 .gutter_dimensions(
7906 font_id,
7907 font_size,
7908 self.max_line_number_width(&snapshot, window),
7909 cx,
7910 )
7911 .or_else(|| {
7912 self.editor.read(cx).offset_content.then(|| {
7913 GutterDimensions::default_with_margin(font_id, font_size, cx)
7914 })
7915 })
7916 .unwrap_or_default();
7917 let text_width = bounds.size.width - gutter_dimensions.width;
7918
7919 let settings = EditorSettings::get_global(cx);
7920 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
7921 let vertical_scrollbar_width = (scrollbars_shown
7922 && settings.scrollbar.axes.vertical
7923 && self.editor.read(cx).show_scrollbars.vertical)
7924 .then_some(style.scrollbar_width)
7925 .unwrap_or_default();
7926 let minimap_width = self
7927 .get_minimap_width(
7928 &settings.minimap,
7929 scrollbars_shown,
7930 text_width,
7931 em_width,
7932 font_size,
7933 rem_size,
7934 cx,
7935 )
7936 .unwrap_or_default();
7937
7938 let right_margin = minimap_width + vertical_scrollbar_width;
7939
7940 let editor_width =
7941 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
7942 let editor_margins = EditorMargins {
7943 gutter: gutter_dimensions,
7944 right: right_margin,
7945 };
7946
7947 snapshot = self.editor.update(cx, |editor, cx| {
7948 editor.last_bounds = Some(bounds);
7949 editor.gutter_dimensions = gutter_dimensions;
7950 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
7951 editor.set_visible_column_count(editor_width / em_advance);
7952
7953 if matches!(
7954 editor.mode,
7955 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
7956 ) {
7957 snapshot
7958 } else {
7959 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
7960 let wrap_width = match editor.soft_wrap_mode(cx) {
7961 SoftWrap::GitDiff => None,
7962 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
7963 SoftWrap::EditorWidth => Some(editor_width),
7964 SoftWrap::Column(column) => Some(wrap_width_for(column)),
7965 SoftWrap::Bounded(column) => {
7966 Some(editor_width.min(wrap_width_for(column)))
7967 }
7968 };
7969
7970 if editor.set_wrap_width(wrap_width, cx) {
7971 editor.snapshot(window, cx)
7972 } else {
7973 snapshot
7974 }
7975 }
7976 });
7977
7978 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
7979 let gutter_hitbox = window.insert_hitbox(
7980 gutter_bounds(bounds, gutter_dimensions),
7981 HitboxBehavior::Normal,
7982 );
7983 let text_hitbox = window.insert_hitbox(
7984 Bounds {
7985 origin: gutter_hitbox.top_right(),
7986 size: size(text_width, bounds.size.height),
7987 },
7988 HitboxBehavior::Normal,
7989 );
7990
7991 // Offset the content_bounds from the text_bounds by the gutter margin (which
7992 // is roughly half a character wide) to make hit testing work more like how we want.
7993 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
7994 let content_origin = text_hitbox.origin + content_offset;
7995
7996 let height_in_lines = bounds.size.height / line_height;
7997 let max_row = snapshot.max_point().row().as_f32();
7998
7999 // The max scroll position for the top of the window
8000 let max_scroll_top = if matches!(
8001 snapshot.mode,
8002 EditorMode::SingleLine { .. }
8003 | EditorMode::AutoHeight { .. }
8004 | EditorMode::Full {
8005 sized_by_content: true,
8006 ..
8007 }
8008 ) {
8009 (max_row - height_in_lines + 1.).max(0.)
8010 } else {
8011 let settings = EditorSettings::get_global(cx);
8012 match settings.scroll_beyond_last_line {
8013 ScrollBeyondLastLine::OnePage => max_row,
8014 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
8015 ScrollBeyondLastLine::VerticalScrollMargin => {
8016 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
8017 .max(0.)
8018 }
8019 }
8020 };
8021
8022 let (
8023 autoscroll_request,
8024 autoscroll_containing_element,
8025 needs_horizontal_autoscroll,
8026 ) = self.editor.update(cx, |editor, cx| {
8027 let autoscroll_request = editor.autoscroll_request();
8028 let autoscroll_containing_element =
8029 autoscroll_request.is_some() || editor.has_pending_selection();
8030
8031 let (needs_horizontal_autoscroll, was_scrolled) = editor
8032 .autoscroll_vertically(bounds, line_height, max_scroll_top, window, cx);
8033 if was_scrolled.0 {
8034 snapshot = editor.snapshot(window, cx);
8035 }
8036 (
8037 autoscroll_request,
8038 autoscroll_containing_element,
8039 needs_horizontal_autoscroll,
8040 )
8041 });
8042
8043 let mut scroll_position = snapshot.scroll_position();
8044 // The scroll position is a fractional point, the whole number of which represents
8045 // the top of the window in terms of display rows.
8046 let start_row = DisplayRow(scroll_position.y as u32);
8047 let max_row = snapshot.max_point().row();
8048 let end_row = cmp::min(
8049 (scroll_position.y + height_in_lines).ceil() as u32,
8050 max_row.next_row().0,
8051 );
8052 let end_row = DisplayRow(end_row);
8053
8054 let row_infos = snapshot
8055 .row_infos(start_row)
8056 .take((start_row..end_row).len())
8057 .collect::<Vec<RowInfo>>();
8058 let is_row_soft_wrapped = |row: usize| {
8059 row_infos
8060 .get(row)
8061 .map_or(true, |info| info.buffer_row.is_none())
8062 };
8063
8064 let start_anchor = if start_row == Default::default() {
8065 Anchor::min()
8066 } else {
8067 snapshot.buffer_snapshot.anchor_before(
8068 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
8069 )
8070 };
8071 let end_anchor = if end_row > max_row {
8072 Anchor::max()
8073 } else {
8074 snapshot.buffer_snapshot.anchor_before(
8075 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
8076 )
8077 };
8078
8079 let mut highlighted_rows = self
8080 .editor
8081 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
8082
8083 let is_light = cx.theme().appearance().is_light();
8084
8085 for (ix, row_info) in row_infos.iter().enumerate() {
8086 let Some(diff_status) = row_info.diff_status else {
8087 continue;
8088 };
8089
8090 let background_color = match diff_status.kind {
8091 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
8092 DiffHunkStatusKind::Deleted => {
8093 cx.theme().colors().version_control_deleted
8094 }
8095 DiffHunkStatusKind::Modified => {
8096 debug_panic!("modified diff status for row info");
8097 continue;
8098 }
8099 };
8100
8101 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
8102
8103 let hollow_highlight = LineHighlight {
8104 background: (background_color.opacity(if is_light {
8105 0.08
8106 } else {
8107 0.06
8108 }))
8109 .into(),
8110 border: Some(if is_light {
8111 background_color.opacity(0.48)
8112 } else {
8113 background_color.opacity(0.36)
8114 }),
8115 include_gutter: true,
8116 type_id: None,
8117 };
8118
8119 let filled_highlight = LineHighlight {
8120 background: solid_background(background_color.opacity(hunk_opacity)),
8121 border: None,
8122 include_gutter: true,
8123 type_id: None,
8124 };
8125
8126 let background = if Self::diff_hunk_hollow(diff_status, cx) {
8127 hollow_highlight
8128 } else {
8129 filled_highlight
8130 };
8131
8132 highlighted_rows
8133 .entry(start_row + DisplayRow(ix as u32))
8134 .or_insert(background);
8135 }
8136
8137 let highlighted_ranges = self
8138 .editor_with_selections(cx)
8139 .map(|editor| {
8140 editor.read(cx).background_highlights_in_range(
8141 start_anchor..end_anchor,
8142 &snapshot.display_snapshot,
8143 cx.theme(),
8144 )
8145 })
8146 .unwrap_or_default();
8147 let highlighted_gutter_ranges =
8148 self.editor.read(cx).gutter_highlights_in_range(
8149 start_anchor..end_anchor,
8150 &snapshot.display_snapshot,
8151 cx,
8152 );
8153
8154 let document_colors = self
8155 .editor
8156 .read(cx)
8157 .colors
8158 .as_ref()
8159 .map(|colors| colors.editor_display_highlights(&snapshot));
8160 let redacted_ranges = self.editor.read(cx).redacted_ranges(
8161 start_anchor..end_anchor,
8162 &snapshot.display_snapshot,
8163 cx,
8164 );
8165
8166 let (local_selections, selected_buffer_ids): (
8167 Vec<Selection<Point>>,
8168 Vec<BufferId>,
8169 ) = self
8170 .editor_with_selections(cx)
8171 .map(|editor| {
8172 editor.update(cx, |editor, cx| {
8173 let all_selections = editor.selections.all::<Point>(cx);
8174 let selected_buffer_ids = if editor.is_singleton(cx) {
8175 Vec::new()
8176 } else {
8177 let mut selected_buffer_ids =
8178 Vec::with_capacity(all_selections.len());
8179
8180 for selection in all_selections {
8181 for buffer_id in snapshot
8182 .buffer_snapshot
8183 .buffer_ids_for_range(selection.range())
8184 {
8185 if selected_buffer_ids.last() != Some(&buffer_id) {
8186 selected_buffer_ids.push(buffer_id);
8187 }
8188 }
8189 }
8190
8191 selected_buffer_ids
8192 };
8193
8194 let mut selections = editor
8195 .selections
8196 .disjoint_in_range(start_anchor..end_anchor, cx);
8197 selections.extend(editor.selections.pending(cx));
8198
8199 (selections, selected_buffer_ids)
8200 })
8201 })
8202 .unwrap_or_default();
8203
8204 let (selections, mut active_rows, newest_selection_head) = self
8205 .layout_selections(
8206 start_anchor,
8207 end_anchor,
8208 &local_selections,
8209 &snapshot,
8210 start_row,
8211 end_row,
8212 window,
8213 cx,
8214 );
8215 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
8216 editor.active_breakpoints(start_row..end_row, window, cx)
8217 });
8218 for (display_row, (_, bp, state)) in &breakpoint_rows {
8219 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
8220 active_rows.entry(*display_row).or_default().breakpoint = true;
8221 }
8222 }
8223
8224 let line_numbers = self.layout_line_numbers(
8225 Some(&gutter_hitbox),
8226 gutter_dimensions,
8227 line_height,
8228 scroll_position,
8229 start_row..end_row,
8230 &row_infos,
8231 &active_rows,
8232 newest_selection_head,
8233 &snapshot,
8234 window,
8235 cx,
8236 );
8237
8238 // We add the gutter breakpoint indicator to breakpoint_rows after painting
8239 // line numbers so we don't paint a line number debug accent color if a user
8240 // has their mouse over that line when a breakpoint isn't there
8241 self.editor.update(cx, |editor, _| {
8242 if let Some(phantom_breakpoint) = &mut editor
8243 .gutter_breakpoint_indicator
8244 .0
8245 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
8246 {
8247 // Is there a non-phantom breakpoint on this line?
8248 phantom_breakpoint.collides_with_existing_breakpoint = true;
8249 breakpoint_rows
8250 .entry(phantom_breakpoint.display_row)
8251 .or_insert_with(|| {
8252 let position = snapshot.display_point_to_anchor(
8253 DisplayPoint::new(phantom_breakpoint.display_row, 0),
8254 Bias::Right,
8255 );
8256 let breakpoint = Breakpoint::new_standard();
8257 phantom_breakpoint.collides_with_existing_breakpoint = false;
8258 (position, breakpoint, None)
8259 });
8260 }
8261 });
8262
8263 let mut expand_toggles =
8264 window.with_element_namespace("expand_toggles", |window| {
8265 self.layout_expand_toggles(
8266 &gutter_hitbox,
8267 gutter_dimensions,
8268 em_width,
8269 line_height,
8270 scroll_position,
8271 &row_infos,
8272 window,
8273 cx,
8274 )
8275 });
8276
8277 let mut crease_toggles =
8278 window.with_element_namespace("crease_toggles", |window| {
8279 self.layout_crease_toggles(
8280 start_row..end_row,
8281 &row_infos,
8282 &active_rows,
8283 &snapshot,
8284 window,
8285 cx,
8286 )
8287 });
8288 let crease_trailers =
8289 window.with_element_namespace("crease_trailers", |window| {
8290 self.layout_crease_trailers(
8291 row_infos.iter().copied(),
8292 &snapshot,
8293 window,
8294 cx,
8295 )
8296 });
8297
8298 let display_hunks = self.layout_gutter_diff_hunks(
8299 line_height,
8300 &gutter_hitbox,
8301 start_row..end_row,
8302 &snapshot,
8303 window,
8304 cx,
8305 );
8306
8307 let mut line_layouts = Self::layout_lines(
8308 start_row..end_row,
8309 &snapshot,
8310 &self.style,
8311 editor_width,
8312 is_row_soft_wrapped,
8313 window,
8314 cx,
8315 );
8316 let new_renderer_widths = (!is_minimap).then(|| {
8317 line_layouts
8318 .iter()
8319 .flat_map(|layout| &layout.fragments)
8320 .filter_map(|fragment| {
8321 if let LineFragment::Element { id, size, .. } = fragment {
8322 Some((*id, size.width))
8323 } else {
8324 None
8325 }
8326 })
8327 });
8328 if new_renderer_widths.is_some_and(|new_renderer_widths| {
8329 self.editor.update(cx, |editor, cx| {
8330 editor.update_renderer_widths(new_renderer_widths, cx)
8331 })
8332 }) {
8333 // If the fold widths have changed, we need to prepaint
8334 // the element again to account for any changes in
8335 // wrapping.
8336 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8337 }
8338
8339 let longest_line_blame_width = self
8340 .editor
8341 .update(cx, |editor, cx| {
8342 if !editor.show_git_blame_inline {
8343 return None;
8344 }
8345 let blame = editor.blame.as_ref()?;
8346 let blame_entry = blame
8347 .update(cx, |blame, cx| {
8348 let row_infos =
8349 snapshot.row_infos(snapshot.longest_row()).next()?;
8350 blame.blame_for_rows(&[row_infos], cx).next()
8351 })
8352 .flatten()?;
8353 let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
8354 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
8355 Some(
8356 element
8357 .layout_as_root(AvailableSpace::min_size(), window, cx)
8358 .width
8359 + inline_blame_padding,
8360 )
8361 })
8362 .unwrap_or(Pixels::ZERO);
8363
8364 let longest_line_width = layout_line(
8365 snapshot.longest_row(),
8366 &snapshot,
8367 &style,
8368 editor_width,
8369 is_row_soft_wrapped,
8370 window,
8371 cx,
8372 )
8373 .width;
8374
8375 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
8376 text_hitbox.bounds,
8377 glyph_grid_cell,
8378 size(longest_line_width, max_row.as_f32() * line_height),
8379 longest_line_blame_width,
8380 EditorSettings::get_global(cx),
8381 );
8382
8383 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
8384
8385 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
8386 snapshot.sticky_header_excerpt(scroll_position.y)
8387 } else {
8388 None
8389 };
8390 let sticky_header_excerpt_id =
8391 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
8392
8393 let blocks = (!is_minimap)
8394 .then(|| {
8395 window.with_element_namespace("blocks", |window| {
8396 self.render_blocks(
8397 start_row..end_row,
8398 &snapshot,
8399 &hitbox,
8400 &text_hitbox,
8401 editor_width,
8402 &mut scroll_width,
8403 &editor_margins,
8404 em_width,
8405 gutter_dimensions.full_width(),
8406 line_height,
8407 &mut line_layouts,
8408 &local_selections,
8409 &selected_buffer_ids,
8410 is_row_soft_wrapped,
8411 sticky_header_excerpt_id,
8412 window,
8413 cx,
8414 )
8415 })
8416 })
8417 .unwrap_or_else(|| Ok((Vec::default(), HashMap::default())));
8418 let (mut blocks, row_block_types) = match blocks {
8419 Ok(blocks) => blocks,
8420 Err(resized_blocks) => {
8421 self.editor.update(cx, |editor, cx| {
8422 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
8423 });
8424 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8425 }
8426 };
8427
8428 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
8429 window.with_element_namespace("blocks", |window| {
8430 self.layout_sticky_buffer_header(
8431 sticky_header_excerpt,
8432 scroll_position.y,
8433 line_height,
8434 right_margin,
8435 &snapshot,
8436 &hitbox,
8437 &selected_buffer_ids,
8438 &blocks,
8439 window,
8440 cx,
8441 )
8442 })
8443 });
8444
8445 let start_buffer_row =
8446 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
8447 let end_buffer_row =
8448 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
8449
8450 let scroll_max = point(
8451 ((scroll_width - editor_width) / em_advance).max(0.0),
8452 max_scroll_top,
8453 );
8454
8455 self.editor.update(cx, |editor, cx| {
8456 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
8457 scroll_position.x = scroll_position.x.min(scroll_max.x);
8458 }
8459
8460 if needs_horizontal_autoscroll.0
8461 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
8462 start_row,
8463 editor_width,
8464 scroll_width,
8465 em_advance,
8466 &line_layouts,
8467 window,
8468 cx,
8469 )
8470 {
8471 scroll_position = new_scroll_position;
8472 }
8473 });
8474
8475 let scroll_pixel_position = point(
8476 scroll_position.x * em_advance,
8477 scroll_position.y * line_height,
8478 );
8479 let indent_guides = self.layout_indent_guides(
8480 content_origin,
8481 text_hitbox.origin,
8482 start_buffer_row..end_buffer_row,
8483 scroll_pixel_position,
8484 line_height,
8485 &snapshot,
8486 window,
8487 cx,
8488 );
8489
8490 let crease_trailers =
8491 window.with_element_namespace("crease_trailers", |window| {
8492 self.prepaint_crease_trailers(
8493 crease_trailers,
8494 &line_layouts,
8495 line_height,
8496 content_origin,
8497 scroll_pixel_position,
8498 em_width,
8499 window,
8500 cx,
8501 )
8502 });
8503
8504 let (inline_completion_popover, inline_completion_popover_origin) = self
8505 .editor
8506 .update(cx, |editor, cx| {
8507 editor.render_edit_prediction_popover(
8508 &text_hitbox.bounds,
8509 content_origin,
8510 right_margin,
8511 &snapshot,
8512 start_row..end_row,
8513 scroll_position.y,
8514 scroll_position.y + height_in_lines,
8515 &line_layouts,
8516 line_height,
8517 scroll_pixel_position,
8518 newest_selection_head,
8519 editor_width,
8520 &style,
8521 window,
8522 cx,
8523 )
8524 })
8525 .unzip();
8526
8527 let mut inline_diagnostics = self.layout_inline_diagnostics(
8528 &line_layouts,
8529 &crease_trailers,
8530 &row_block_types,
8531 content_origin,
8532 scroll_pixel_position,
8533 inline_completion_popover_origin,
8534 start_row,
8535 end_row,
8536 line_height,
8537 em_width,
8538 &style,
8539 window,
8540 cx,
8541 );
8542
8543 let mut inline_blame_layout = None;
8544 let mut inline_code_actions = None;
8545 if let Some(newest_selection_head) = newest_selection_head {
8546 let display_row = newest_selection_head.row();
8547 if (start_row..end_row).contains(&display_row)
8548 && !row_block_types.contains_key(&display_row)
8549 {
8550 inline_code_actions = self.layout_inline_code_actions(
8551 newest_selection_head,
8552 content_origin,
8553 scroll_pixel_position,
8554 line_height,
8555 &snapshot,
8556 window,
8557 cx,
8558 );
8559
8560 let line_ix = display_row.minus(start_row) as usize;
8561 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
8562 row_infos.get(line_ix),
8563 line_layouts.get(line_ix),
8564 crease_trailers.get(line_ix),
8565 ) {
8566 let crease_trailer_layout = crease_trailer.as_ref();
8567 if let Some(layout) = self.layout_inline_blame(
8568 display_row,
8569 row_info,
8570 line_layout,
8571 crease_trailer_layout,
8572 em_width,
8573 content_origin,
8574 scroll_pixel_position,
8575 line_height,
8576 &text_hitbox,
8577 window,
8578 cx,
8579 ) {
8580 inline_blame_layout = Some(layout);
8581 // Blame overrides inline diagnostics
8582 inline_diagnostics.remove(&display_row);
8583 }
8584 } else {
8585 log::error!(
8586 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
8587 line_layouts.len(): {}, \
8588 crease_trailers.len(): {}",
8589 line_ix,
8590 row_infos.len(),
8591 line_layouts.len(),
8592 crease_trailers.len(),
8593 );
8594 }
8595 }
8596 }
8597
8598 let blamed_display_rows = self.layout_blame_entries(
8599 &row_infos,
8600 em_width,
8601 scroll_position,
8602 line_height,
8603 &gutter_hitbox,
8604 gutter_dimensions.git_blame_entries_width,
8605 window,
8606 cx,
8607 );
8608
8609 let line_elements = self.prepaint_lines(
8610 start_row,
8611 &mut line_layouts,
8612 line_height,
8613 scroll_pixel_position,
8614 content_origin,
8615 window,
8616 cx,
8617 );
8618
8619 window.with_element_namespace("blocks", |window| {
8620 self.layout_blocks(
8621 &mut blocks,
8622 &hitbox,
8623 line_height,
8624 scroll_pixel_position,
8625 window,
8626 cx,
8627 );
8628 });
8629
8630 let cursors = self.collect_cursors(&snapshot, cx);
8631 let visible_row_range = start_row..end_row;
8632 let non_visible_cursors = cursors
8633 .iter()
8634 .any(|c| !visible_row_range.contains(&c.0.row()));
8635
8636 let visible_cursors = self.layout_visible_cursors(
8637 &snapshot,
8638 &selections,
8639 &row_block_types,
8640 start_row..end_row,
8641 &line_layouts,
8642 &text_hitbox,
8643 content_origin,
8644 scroll_position,
8645 scroll_pixel_position,
8646 line_height,
8647 em_width,
8648 em_advance,
8649 autoscroll_containing_element,
8650 window,
8651 cx,
8652 );
8653
8654 let scrollbars_layout = self.layout_scrollbars(
8655 &snapshot,
8656 &scrollbar_layout_information,
8657 content_offset,
8658 scroll_position,
8659 non_visible_cursors,
8660 right_margin,
8661 editor_width,
8662 window,
8663 cx,
8664 );
8665
8666 let gutter_settings = EditorSettings::get_global(cx).gutter;
8667
8668 let context_menu_layout =
8669 if let Some(newest_selection_head) = newest_selection_head {
8670 let newest_selection_point =
8671 newest_selection_head.to_point(&snapshot.display_snapshot);
8672 if (start_row..end_row).contains(&newest_selection_head.row()) {
8673 self.layout_cursor_popovers(
8674 line_height,
8675 &text_hitbox,
8676 content_origin,
8677 right_margin,
8678 start_row,
8679 scroll_pixel_position,
8680 &line_layouts,
8681 newest_selection_head,
8682 newest_selection_point,
8683 &style,
8684 window,
8685 cx,
8686 )
8687 } else {
8688 None
8689 }
8690 } else {
8691 None
8692 };
8693
8694 self.layout_gutter_menu(
8695 line_height,
8696 &text_hitbox,
8697 content_origin,
8698 right_margin,
8699 scroll_pixel_position,
8700 gutter_dimensions.width - gutter_dimensions.left_padding,
8701 window,
8702 cx,
8703 );
8704
8705 let test_indicators = if gutter_settings.runnables {
8706 self.layout_run_indicators(
8707 line_height,
8708 start_row..end_row,
8709 &row_infos,
8710 scroll_pixel_position,
8711 &gutter_dimensions,
8712 &gutter_hitbox,
8713 &display_hunks,
8714 &snapshot,
8715 &mut breakpoint_rows,
8716 window,
8717 cx,
8718 )
8719 } else {
8720 Vec::new()
8721 };
8722
8723 let show_breakpoints = snapshot
8724 .show_breakpoints
8725 .unwrap_or(gutter_settings.breakpoints);
8726 let breakpoints = if show_breakpoints {
8727 self.layout_breakpoints(
8728 line_height,
8729 start_row..end_row,
8730 scroll_pixel_position,
8731 &gutter_dimensions,
8732 &gutter_hitbox,
8733 &display_hunks,
8734 &snapshot,
8735 breakpoint_rows,
8736 &row_infos,
8737 window,
8738 cx,
8739 )
8740 } else {
8741 Vec::new()
8742 };
8743
8744 self.layout_signature_help(
8745 &hitbox,
8746 content_origin,
8747 scroll_pixel_position,
8748 newest_selection_head,
8749 start_row,
8750 &line_layouts,
8751 line_height,
8752 em_width,
8753 context_menu_layout,
8754 window,
8755 cx,
8756 );
8757
8758 if !cx.has_active_drag() {
8759 self.layout_hover_popovers(
8760 &snapshot,
8761 &hitbox,
8762 start_row..end_row,
8763 content_origin,
8764 scroll_pixel_position,
8765 &line_layouts,
8766 line_height,
8767 em_width,
8768 context_menu_layout,
8769 window,
8770 cx,
8771 );
8772 }
8773
8774 let mouse_context_menu = self.layout_mouse_context_menu(
8775 &snapshot,
8776 start_row..end_row,
8777 content_origin,
8778 window,
8779 cx,
8780 );
8781
8782 window.with_element_namespace("crease_toggles", |window| {
8783 self.prepaint_crease_toggles(
8784 &mut crease_toggles,
8785 line_height,
8786 &gutter_dimensions,
8787 gutter_settings,
8788 scroll_pixel_position,
8789 &gutter_hitbox,
8790 window,
8791 cx,
8792 )
8793 });
8794
8795 window.with_element_namespace("expand_toggles", |window| {
8796 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
8797 });
8798
8799 let wrap_guides = self.layout_wrap_guides(
8800 em_advance,
8801 scroll_position,
8802 content_origin,
8803 scrollbars_layout.as_ref(),
8804 vertical_scrollbar_width,
8805 &hitbox,
8806 window,
8807 cx,
8808 );
8809
8810 let minimap = window.with_element_namespace("minimap", |window| {
8811 self.layout_minimap(
8812 &snapshot,
8813 minimap_width,
8814 scroll_position,
8815 &scrollbar_layout_information,
8816 scrollbars_layout.as_ref(),
8817 window,
8818 cx,
8819 )
8820 });
8821
8822 let invisible_symbol_font_size = font_size / 2.;
8823 let tab_invisible = window.text_system().shape_line(
8824 "→".into(),
8825 invisible_symbol_font_size,
8826 &[TextRun {
8827 len: "→".len(),
8828 font: self.style.text.font(),
8829 color: cx.theme().colors().editor_invisible,
8830 background_color: None,
8831 underline: None,
8832 strikethrough: None,
8833 }],
8834 None,
8835 );
8836 let space_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
8850 let mode = snapshot.mode.clone();
8851
8852 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
8853 (vec![], vec![])
8854 } else {
8855 self.layout_diff_hunk_controls(
8856 start_row..end_row,
8857 &row_infos,
8858 &text_hitbox,
8859 newest_selection_head,
8860 line_height,
8861 right_margin,
8862 scroll_pixel_position,
8863 &display_hunks,
8864 &highlighted_rows,
8865 self.editor.clone(),
8866 window,
8867 cx,
8868 )
8869 };
8870
8871 let position_map = Rc::new(PositionMap {
8872 size: bounds.size,
8873 visible_row_range,
8874 scroll_pixel_position,
8875 scroll_max,
8876 line_layouts,
8877 line_height,
8878 em_width,
8879 em_advance,
8880 snapshot,
8881 gutter_hitbox: gutter_hitbox.clone(),
8882 text_hitbox: text_hitbox.clone(),
8883 inline_blame_bounds: inline_blame_layout
8884 .as_ref()
8885 .map(|layout| (layout.bounds, layout.entry.clone())),
8886 display_hunks: display_hunks.clone(),
8887 diff_hunk_control_bounds: diff_hunk_control_bounds.clone(),
8888 });
8889
8890 self.editor.update(cx, |editor, _| {
8891 editor.last_position_map = Some(position_map.clone())
8892 });
8893
8894 EditorLayout {
8895 mode,
8896 position_map,
8897 visible_display_row_range: start_row..end_row,
8898 wrap_guides,
8899 indent_guides,
8900 hitbox,
8901 gutter_hitbox,
8902 display_hunks,
8903 content_origin,
8904 scrollbars_layout,
8905 minimap,
8906 active_rows,
8907 highlighted_rows,
8908 highlighted_ranges,
8909 highlighted_gutter_ranges,
8910 redacted_ranges,
8911 document_colors,
8912 line_elements,
8913 line_numbers,
8914 blamed_display_rows,
8915 inline_diagnostics,
8916 inline_blame_layout,
8917 inline_code_actions,
8918 blocks,
8919 cursors,
8920 visible_cursors,
8921 selections,
8922 inline_completion_popover,
8923 diff_hunk_controls,
8924 mouse_context_menu,
8925 test_indicators,
8926 breakpoints,
8927 crease_toggles,
8928 crease_trailers,
8929 tab_invisible,
8930 space_invisible,
8931 sticky_buffer_header,
8932 expand_toggles,
8933 }
8934 })
8935 })
8936 })
8937 }
8938
8939 fn paint(
8940 &mut self,
8941 _: Option<&GlobalElementId>,
8942 _inspector_id: Option<&gpui::InspectorElementId>,
8943 bounds: Bounds<gpui::Pixels>,
8944 _: &mut Self::RequestLayoutState,
8945 layout: &mut Self::PrepaintState,
8946 window: &mut Window,
8947 cx: &mut App,
8948 ) {
8949 if !layout.mode.is_minimap() {
8950 let focus_handle = self.editor.focus_handle(cx);
8951 let key_context = self
8952 .editor
8953 .update(cx, |editor, cx| editor.key_context(window, cx));
8954
8955 window.set_key_context(key_context);
8956 window.handle_input(
8957 &focus_handle,
8958 ElementInputHandler::new(bounds, self.editor.clone()),
8959 cx,
8960 );
8961 self.register_actions(window, cx);
8962 self.register_key_listeners(window, cx, layout);
8963 }
8964
8965 let text_style = TextStyleRefinement {
8966 font_size: Some(self.style.text.font_size),
8967 line_height: Some(self.style.text.line_height),
8968 ..Default::default()
8969 };
8970 let rem_size = self.rem_size(cx);
8971 window.with_rem_size(rem_size, |window| {
8972 window.with_text_style(Some(text_style), |window| {
8973 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8974 self.paint_mouse_listeners(layout, window, cx);
8975 self.paint_background(layout, window, cx);
8976 self.paint_indent_guides(layout, window, cx);
8977
8978 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8979 self.paint_blamed_display_rows(layout, window, cx);
8980 self.paint_line_numbers(layout, window, cx);
8981 }
8982
8983 self.paint_text(layout, window, cx);
8984
8985 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8986 self.paint_gutter_highlights(layout, window, cx);
8987 self.paint_gutter_indicators(layout, window, cx);
8988 }
8989
8990 if !layout.blocks.is_empty() {
8991 window.with_element_namespace("blocks", |window| {
8992 self.paint_blocks(layout, window, cx);
8993 });
8994 }
8995
8996 window.with_element_namespace("blocks", |window| {
8997 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
8998 sticky_header.paint(window, cx)
8999 }
9000 });
9001
9002 self.paint_minimap(layout, window, cx);
9003 self.paint_scrollbars(layout, window, cx);
9004 self.paint_inline_completion_popover(layout, window, cx);
9005 self.paint_mouse_context_menu(layout, window, cx);
9006 });
9007 })
9008 })
9009 }
9010}
9011
9012pub(super) fn gutter_bounds(
9013 editor_bounds: Bounds<Pixels>,
9014 gutter_dimensions: GutterDimensions,
9015) -> Bounds<Pixels> {
9016 Bounds {
9017 origin: editor_bounds.origin,
9018 size: size(gutter_dimensions.width, editor_bounds.size.height),
9019 }
9020}
9021
9022#[derive(Clone, Copy)]
9023struct ContextMenuLayout {
9024 y_flipped: bool,
9025 bounds: Bounds<Pixels>,
9026}
9027
9028/// Holds information required for layouting the editor scrollbars.
9029struct ScrollbarLayoutInformation {
9030 /// The bounds of the editor area (excluding the content offset).
9031 editor_bounds: Bounds<Pixels>,
9032 /// The available range to scroll within the document.
9033 scroll_range: Size<Pixels>,
9034 /// The space available for one glyph in the editor.
9035 glyph_grid_cell: Size<Pixels>,
9036}
9037
9038impl ScrollbarLayoutInformation {
9039 pub fn new(
9040 editor_bounds: Bounds<Pixels>,
9041 glyph_grid_cell: Size<Pixels>,
9042 document_size: Size<Pixels>,
9043 longest_line_blame_width: Pixels,
9044 settings: &EditorSettings,
9045 ) -> Self {
9046 let vertical_overscroll = match settings.scroll_beyond_last_line {
9047 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
9048 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
9049 ScrollBeyondLastLine::VerticalScrollMargin => {
9050 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
9051 }
9052 };
9053
9054 let overscroll = size(longest_line_blame_width, vertical_overscroll);
9055
9056 ScrollbarLayoutInformation {
9057 editor_bounds,
9058 scroll_range: document_size + overscroll,
9059 glyph_grid_cell,
9060 }
9061 }
9062}
9063
9064impl IntoElement for EditorElement {
9065 type Element = Self;
9066
9067 fn into_element(self) -> Self::Element {
9068 self
9069 }
9070}
9071
9072pub struct EditorLayout {
9073 position_map: Rc<PositionMap>,
9074 hitbox: Hitbox,
9075 gutter_hitbox: Hitbox,
9076 content_origin: gpui::Point<Pixels>,
9077 scrollbars_layout: Option<EditorScrollbars>,
9078 minimap: Option<MinimapLayout>,
9079 mode: EditorMode,
9080 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
9081 indent_guides: Option<Vec<IndentGuideLayout>>,
9082 visible_display_row_range: Range<DisplayRow>,
9083 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
9084 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
9085 line_elements: SmallVec<[AnyElement; 1]>,
9086 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
9087 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9088 blamed_display_rows: Option<Vec<AnyElement>>,
9089 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
9090 inline_blame_layout: Option<InlineBlameLayout>,
9091 inline_code_actions: Option<AnyElement>,
9092 blocks: Vec<BlockLayout>,
9093 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9094 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9095 redacted_ranges: Vec<Range<DisplayPoint>>,
9096 cursors: Vec<(DisplayPoint, Hsla)>,
9097 visible_cursors: Vec<CursorLayout>,
9098 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
9099 test_indicators: Vec<AnyElement>,
9100 breakpoints: Vec<AnyElement>,
9101 crease_toggles: Vec<Option<AnyElement>>,
9102 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
9103 diff_hunk_controls: Vec<AnyElement>,
9104 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
9105 inline_completion_popover: Option<AnyElement>,
9106 mouse_context_menu: Option<AnyElement>,
9107 tab_invisible: ShapedLine,
9108 space_invisible: ShapedLine,
9109 sticky_buffer_header: Option<AnyElement>,
9110 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
9111}
9112
9113impl EditorLayout {
9114 fn line_end_overshoot(&self) -> Pixels {
9115 0.15 * self.position_map.line_height
9116 }
9117}
9118
9119struct LineNumberLayout {
9120 shaped_line: ShapedLine,
9121 hitbox: Option<Hitbox>,
9122}
9123
9124struct ColoredRange<T> {
9125 start: T,
9126 end: T,
9127 color: Hsla,
9128}
9129
9130impl Along for ScrollbarAxes {
9131 type Unit = bool;
9132
9133 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
9134 match axis {
9135 ScrollbarAxis::Horizontal => self.horizontal,
9136 ScrollbarAxis::Vertical => self.vertical,
9137 }
9138 }
9139
9140 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
9141 match axis {
9142 ScrollbarAxis::Horizontal => ScrollbarAxes {
9143 horizontal: f(self.horizontal),
9144 vertical: self.vertical,
9145 },
9146 ScrollbarAxis::Vertical => ScrollbarAxes {
9147 horizontal: self.horizontal,
9148 vertical: f(self.vertical),
9149 },
9150 }
9151 }
9152}
9153
9154#[derive(Clone)]
9155struct EditorScrollbars {
9156 pub vertical: Option<ScrollbarLayout>,
9157 pub horizontal: Option<ScrollbarLayout>,
9158 pub visible: bool,
9159}
9160
9161impl EditorScrollbars {
9162 pub fn from_scrollbar_axes(
9163 show_scrollbar: ScrollbarAxes,
9164 layout_information: &ScrollbarLayoutInformation,
9165 content_offset: gpui::Point<Pixels>,
9166 scroll_position: gpui::Point<f32>,
9167 scrollbar_width: Pixels,
9168 right_margin: Pixels,
9169 editor_width: Pixels,
9170 show_scrollbars: bool,
9171 scrollbar_state: Option<&ActiveScrollbarState>,
9172 window: &mut Window,
9173 ) -> Self {
9174 let ScrollbarLayoutInformation {
9175 editor_bounds,
9176 scroll_range,
9177 glyph_grid_cell,
9178 } = layout_information;
9179
9180 let viewport_size = size(editor_width, editor_bounds.size.height);
9181
9182 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
9183 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
9184 Corner::BottomLeft,
9185 editor_bounds.bottom_left(),
9186 size(
9187 // The horizontal viewport size differs from the space available for the
9188 // horizontal scrollbar, so we have to manually stich it together here.
9189 editor_bounds.size.width - right_margin,
9190 scrollbar_width,
9191 ),
9192 ),
9193 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
9194 Corner::TopRight,
9195 editor_bounds.top_right(),
9196 size(scrollbar_width, viewport_size.height),
9197 ),
9198 };
9199
9200 let mut create_scrollbar_layout = |axis| {
9201 let viewport_size = viewport_size.along(axis);
9202 let scroll_range = scroll_range.along(axis);
9203
9204 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
9205 (show_scrollbar.along(axis)
9206 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
9207 .then(|| {
9208 ScrollbarLayout::new(
9209 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
9210 viewport_size,
9211 scroll_range,
9212 glyph_grid_cell.along(axis),
9213 content_offset.along(axis),
9214 scroll_position.along(axis),
9215 show_scrollbars,
9216 axis,
9217 )
9218 .with_thumb_state(
9219 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
9220 )
9221 })
9222 };
9223
9224 Self {
9225 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
9226 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
9227 visible: show_scrollbars,
9228 }
9229 }
9230
9231 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
9232 [
9233 (&self.vertical, ScrollbarAxis::Vertical),
9234 (&self.horizontal, ScrollbarAxis::Horizontal),
9235 ]
9236 .into_iter()
9237 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
9238 }
9239
9240 /// Returns the currently hovered scrollbar axis, if any.
9241 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
9242 self.iter_scrollbars()
9243 .find(|s| s.0.hitbox.is_hovered(window))
9244 }
9245}
9246
9247#[derive(Clone)]
9248struct ScrollbarLayout {
9249 hitbox: Hitbox,
9250 visible_range: Range<f32>,
9251 text_unit_size: Pixels,
9252 thumb_bounds: Option<Bounds<Pixels>>,
9253 thumb_state: ScrollbarThumbState,
9254}
9255
9256impl ScrollbarLayout {
9257 const BORDER_WIDTH: Pixels = px(1.0);
9258 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
9259 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
9260 const MIN_THUMB_SIZE: Pixels = px(25.0);
9261
9262 fn new(
9263 scrollbar_track_hitbox: Hitbox,
9264 viewport_size: Pixels,
9265 scroll_range: Pixels,
9266 glyph_space: Pixels,
9267 content_offset: Pixels,
9268 scroll_position: f32,
9269 show_thumb: bool,
9270 axis: ScrollbarAxis,
9271 ) -> Self {
9272 let track_bounds = scrollbar_track_hitbox.bounds;
9273 // The length of the track available to the scrollbar thumb. We deliberately
9274 // exclude the content size here so that the thumb aligns with the content.
9275 let track_length = track_bounds.size.along(axis) - content_offset;
9276
9277 Self::new_with_hitbox_and_track_length(
9278 scrollbar_track_hitbox,
9279 track_length,
9280 viewport_size,
9281 scroll_range,
9282 glyph_space,
9283 content_offset,
9284 scroll_position,
9285 show_thumb,
9286 axis,
9287 )
9288 }
9289
9290 fn for_minimap(
9291 minimap_track_hitbox: Hitbox,
9292 visible_lines: f32,
9293 total_editor_lines: f32,
9294 minimap_line_height: Pixels,
9295 scroll_position: f32,
9296 minimap_scroll_top: f32,
9297 show_thumb: bool,
9298 ) -> Self {
9299 // The scrollbar thumb size is calculated as
9300 // (visible_content/total_content) × scrollbar_track_length.
9301 //
9302 // For the minimap's thumb layout, we leverage this by setting the
9303 // scrollbar track length to the entire document size (using minimap line
9304 // height). This creates a thumb that exactly represents the editor
9305 // viewport scaled to minimap proportions.
9306 //
9307 // We adjust the thumb position relative to `minimap_scroll_top` to
9308 // accommodate for the deliberately oversized track.
9309 //
9310 // This approach ensures that the minimap thumb accurately reflects the
9311 // editor's current scroll position whilst nicely synchronizing the minimap
9312 // thumb and scrollbar thumb.
9313 let scroll_range = total_editor_lines * minimap_line_height;
9314 let viewport_size = visible_lines * minimap_line_height;
9315
9316 let track_top_offset = -minimap_scroll_top * minimap_line_height;
9317
9318 Self::new_with_hitbox_and_track_length(
9319 minimap_track_hitbox,
9320 scroll_range,
9321 viewport_size,
9322 scroll_range,
9323 minimap_line_height,
9324 track_top_offset,
9325 scroll_position,
9326 show_thumb,
9327 ScrollbarAxis::Vertical,
9328 )
9329 }
9330
9331 fn new_with_hitbox_and_track_length(
9332 scrollbar_track_hitbox: Hitbox,
9333 track_length: Pixels,
9334 viewport_size: Pixels,
9335 scroll_range: Pixels,
9336 glyph_space: Pixels,
9337 content_offset: Pixels,
9338 scroll_position: f32,
9339 show_thumb: bool,
9340 axis: ScrollbarAxis,
9341 ) -> Self {
9342 let text_units_per_page = viewport_size / glyph_space;
9343 let visible_range = scroll_position..scroll_position + text_units_per_page;
9344 let total_text_units = scroll_range / glyph_space;
9345
9346 let thumb_percentage = text_units_per_page / total_text_units;
9347 let thumb_size = (track_length * thumb_percentage)
9348 .max(ScrollbarLayout::MIN_THUMB_SIZE)
9349 .min(track_length);
9350
9351 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
9352
9353 let content_larger_than_viewport = text_unit_divisor > 0.;
9354
9355 let text_unit_size = if content_larger_than_viewport {
9356 (track_length - thumb_size) / text_unit_divisor
9357 } else {
9358 glyph_space
9359 };
9360
9361 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
9362 Self::thumb_bounds(
9363 &scrollbar_track_hitbox,
9364 content_offset,
9365 visible_range.start,
9366 text_unit_size,
9367 thumb_size,
9368 axis,
9369 )
9370 });
9371
9372 ScrollbarLayout {
9373 hitbox: scrollbar_track_hitbox,
9374 visible_range,
9375 text_unit_size,
9376 thumb_bounds,
9377 thumb_state: Default::default(),
9378 }
9379 }
9380
9381 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
9382 if let Some(thumb_state) = thumb_state {
9383 Self {
9384 thumb_state,
9385 ..self
9386 }
9387 } else {
9388 self
9389 }
9390 }
9391
9392 fn thumb_bounds(
9393 scrollbar_track: &Hitbox,
9394 content_offset: Pixels,
9395 visible_range_start: f32,
9396 text_unit_size: Pixels,
9397 thumb_size: Pixels,
9398 axis: ScrollbarAxis,
9399 ) -> Bounds<Pixels> {
9400 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
9401 origin + content_offset + visible_range_start * text_unit_size
9402 });
9403 Bounds::new(
9404 thumb_origin,
9405 scrollbar_track.size.apply_along(axis, |_| thumb_size),
9406 )
9407 }
9408
9409 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
9410 self.thumb_bounds
9411 .is_some_and(|bounds| bounds.contains(position))
9412 }
9413
9414 fn marker_quads_for_ranges(
9415 &self,
9416 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
9417 column: Option<usize>,
9418 ) -> Vec<PaintQuad> {
9419 struct MinMax {
9420 min: Pixels,
9421 max: Pixels,
9422 }
9423 let (x_range, height_limit) = if let Some(column) = column {
9424 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
9425 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
9426 let end = start + column_width;
9427 (
9428 Range { start, end },
9429 MinMax {
9430 min: Self::MIN_MARKER_HEIGHT,
9431 max: px(f32::MAX),
9432 },
9433 )
9434 } else {
9435 (
9436 Range {
9437 start: Self::BORDER_WIDTH,
9438 end: self.hitbox.size.width,
9439 },
9440 MinMax {
9441 min: Self::LINE_MARKER_HEIGHT,
9442 max: Self::LINE_MARKER_HEIGHT,
9443 },
9444 )
9445 };
9446
9447 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
9448 let mut pixel_ranges = row_ranges
9449 .into_iter()
9450 .map(|range| {
9451 let start_y = row_to_y(range.start);
9452 let end_y = row_to_y(range.end)
9453 + self
9454 .text_unit_size
9455 .max(height_limit.min)
9456 .min(height_limit.max);
9457 ColoredRange {
9458 start: start_y,
9459 end: end_y,
9460 color: range.color,
9461 }
9462 })
9463 .peekable();
9464
9465 let mut quads = Vec::new();
9466 while let Some(mut pixel_range) = pixel_ranges.next() {
9467 while let Some(next_pixel_range) = pixel_ranges.peek() {
9468 if pixel_range.end >= next_pixel_range.start - px(1.0)
9469 && pixel_range.color == next_pixel_range.color
9470 {
9471 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
9472 pixel_ranges.next();
9473 } else {
9474 break;
9475 }
9476 }
9477
9478 let bounds = Bounds::from_corners(
9479 point(x_range.start, pixel_range.start),
9480 point(x_range.end, pixel_range.end),
9481 );
9482 quads.push(quad(
9483 bounds,
9484 Corners::default(),
9485 pixel_range.color,
9486 Edges::default(),
9487 Hsla::transparent_black(),
9488 BorderStyle::default(),
9489 ));
9490 }
9491
9492 quads
9493 }
9494}
9495
9496struct MinimapLayout {
9497 pub minimap: AnyElement,
9498 pub thumb_layout: ScrollbarLayout,
9499 pub minimap_scroll_top: f32,
9500 pub minimap_line_height: Pixels,
9501 pub thumb_border_style: MinimapThumbBorder,
9502 pub max_scroll_top: f32,
9503}
9504
9505impl MinimapLayout {
9506 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
9507 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
9508 /// The minimap width as a percentage of the editor width.
9509 const MINIMAP_WIDTH_PCT: f32 = 0.15;
9510 /// Calculates the scroll top offset the minimap editor has to have based on the
9511 /// current scroll progress.
9512 fn calculate_minimap_top_offset(
9513 document_lines: f32,
9514 visible_editor_lines: f32,
9515 visible_minimap_lines: f32,
9516 scroll_position: f32,
9517 ) -> f32 {
9518 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
9519 if non_visible_document_lines == 0. {
9520 0.
9521 } else {
9522 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
9523 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
9524 }
9525 }
9526}
9527
9528struct CreaseTrailerLayout {
9529 element: AnyElement,
9530 bounds: Bounds<Pixels>,
9531}
9532
9533pub(crate) struct PositionMap {
9534 pub size: Size<Pixels>,
9535 pub line_height: Pixels,
9536 pub scroll_pixel_position: gpui::Point<Pixels>,
9537 pub scroll_max: gpui::Point<f32>,
9538 pub em_width: Pixels,
9539 pub em_advance: Pixels,
9540 pub visible_row_range: Range<DisplayRow>,
9541 pub line_layouts: Vec<LineWithInvisibles>,
9542 pub snapshot: EditorSnapshot,
9543 pub text_hitbox: Hitbox,
9544 pub gutter_hitbox: Hitbox,
9545 pub inline_blame_bounds: Option<(Bounds<Pixels>, BlameEntry)>,
9546 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9547 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
9548}
9549
9550#[derive(Debug, Copy, Clone)]
9551pub struct PointForPosition {
9552 pub previous_valid: DisplayPoint,
9553 pub next_valid: DisplayPoint,
9554 pub exact_unclipped: DisplayPoint,
9555 pub column_overshoot_after_line_end: u32,
9556}
9557
9558impl PointForPosition {
9559 pub fn as_valid(&self) -> Option<DisplayPoint> {
9560 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
9561 Some(self.previous_valid)
9562 } else {
9563 None
9564 }
9565 }
9566
9567 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
9568 let Some(valid_point) = self.as_valid() else {
9569 return false;
9570 };
9571 let range = selection.range();
9572
9573 let candidate_row = valid_point.row();
9574 let candidate_col = valid_point.column();
9575
9576 let start_row = range.start.row();
9577 let start_col = range.start.column();
9578 let end_row = range.end.row();
9579 let end_col = range.end.column();
9580
9581 if candidate_row < start_row || candidate_row > end_row {
9582 false
9583 } else if start_row == end_row {
9584 candidate_col >= start_col && candidate_col < end_col
9585 } else {
9586 if candidate_row == start_row {
9587 candidate_col >= start_col
9588 } else if candidate_row == end_row {
9589 candidate_col < end_col
9590 } else {
9591 true
9592 }
9593 }
9594 }
9595}
9596
9597impl PositionMap {
9598 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
9599 let text_bounds = self.text_hitbox.bounds;
9600 let scroll_position = self.snapshot.scroll_position();
9601 let position = position - text_bounds.origin;
9602 let y = position.y.max(px(0.)).min(self.size.height);
9603 let x = position.x + (scroll_position.x * self.em_advance);
9604 let row = ((y / self.line_height) + scroll_position.y) as u32;
9605
9606 let (column, x_overshoot_after_line_end) = if let Some(line) = self
9607 .line_layouts
9608 .get(row as usize - scroll_position.y as usize)
9609 {
9610 if let Some(ix) = line.index_for_x(x) {
9611 (ix as u32, px(0.))
9612 } else {
9613 (line.len as u32, px(0.).max(x - line.width))
9614 }
9615 } else {
9616 (0, x)
9617 };
9618
9619 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
9620 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
9621 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
9622
9623 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
9624 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
9625 PointForPosition {
9626 previous_valid,
9627 next_valid,
9628 exact_unclipped,
9629 column_overshoot_after_line_end,
9630 }
9631 }
9632}
9633
9634struct BlockLayout {
9635 id: BlockId,
9636 x_offset: Pixels,
9637 row: Option<DisplayRow>,
9638 element: AnyElement,
9639 available_space: Size<AvailableSpace>,
9640 style: BlockStyle,
9641 overlaps_gutter: bool,
9642 is_buffer_header: bool,
9643}
9644
9645pub fn layout_line(
9646 row: DisplayRow,
9647 snapshot: &EditorSnapshot,
9648 style: &EditorStyle,
9649 text_width: Pixels,
9650 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
9651 window: &mut Window,
9652 cx: &mut App,
9653) -> LineWithInvisibles {
9654 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
9655 LineWithInvisibles::from_chunks(
9656 chunks,
9657 &style,
9658 MAX_LINE_LEN,
9659 1,
9660 &snapshot.mode,
9661 text_width,
9662 is_row_soft_wrapped,
9663 window,
9664 cx,
9665 )
9666 .pop()
9667 .unwrap()
9668}
9669
9670#[derive(Debug)]
9671pub struct IndentGuideLayout {
9672 origin: gpui::Point<Pixels>,
9673 length: Pixels,
9674 single_indent_width: Pixels,
9675 depth: u32,
9676 active: bool,
9677 settings: IndentGuideSettings,
9678}
9679
9680pub struct CursorLayout {
9681 origin: gpui::Point<Pixels>,
9682 block_width: Pixels,
9683 line_height: Pixels,
9684 color: Hsla,
9685 shape: CursorShape,
9686 block_text: Option<ShapedLine>,
9687 cursor_name: Option<AnyElement>,
9688}
9689
9690#[derive(Debug)]
9691pub struct CursorName {
9692 string: SharedString,
9693 color: Hsla,
9694 is_top_row: bool,
9695}
9696
9697impl CursorLayout {
9698 pub fn new(
9699 origin: gpui::Point<Pixels>,
9700 block_width: Pixels,
9701 line_height: Pixels,
9702 color: Hsla,
9703 shape: CursorShape,
9704 block_text: Option<ShapedLine>,
9705 ) -> CursorLayout {
9706 CursorLayout {
9707 origin,
9708 block_width,
9709 line_height,
9710 color,
9711 shape,
9712 block_text,
9713 cursor_name: None,
9714 }
9715 }
9716
9717 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
9718 Bounds {
9719 origin: self.origin + origin,
9720 size: size(self.block_width, self.line_height),
9721 }
9722 }
9723
9724 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
9725 match self.shape {
9726 CursorShape::Bar => Bounds {
9727 origin: self.origin + origin,
9728 size: size(px(2.0), self.line_height),
9729 },
9730 CursorShape::Block | CursorShape::Hollow => Bounds {
9731 origin: self.origin + origin,
9732 size: size(self.block_width, self.line_height),
9733 },
9734 CursorShape::Underline => Bounds {
9735 origin: self.origin
9736 + origin
9737 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
9738 size: size(self.block_width, px(2.0)),
9739 },
9740 }
9741 }
9742
9743 pub fn layout(
9744 &mut self,
9745 origin: gpui::Point<Pixels>,
9746 cursor_name: Option<CursorName>,
9747 window: &mut Window,
9748 cx: &mut App,
9749 ) {
9750 if let Some(cursor_name) = cursor_name {
9751 let bounds = self.bounds(origin);
9752 let text_size = self.line_height / 1.5;
9753
9754 let name_origin = if cursor_name.is_top_row {
9755 point(bounds.right() - px(1.), bounds.top())
9756 } else {
9757 match self.shape {
9758 CursorShape::Bar => point(
9759 bounds.right() - px(2.),
9760 bounds.top() - text_size / 2. - px(1.),
9761 ),
9762 _ => point(
9763 bounds.right() - px(1.),
9764 bounds.top() - text_size / 2. - px(1.),
9765 ),
9766 }
9767 };
9768 let mut name_element = div()
9769 .bg(self.color)
9770 .text_size(text_size)
9771 .px_0p5()
9772 .line_height(text_size + px(2.))
9773 .text_color(cursor_name.color)
9774 .child(cursor_name.string.clone())
9775 .into_any_element();
9776
9777 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
9778
9779 self.cursor_name = Some(name_element);
9780 }
9781 }
9782
9783 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
9784 let bounds = self.bounds(origin);
9785
9786 //Draw background or border quad
9787 let cursor = if matches!(self.shape, CursorShape::Hollow) {
9788 outline(bounds, self.color, BorderStyle::Solid)
9789 } else {
9790 fill(bounds, self.color)
9791 };
9792
9793 if let Some(name) = &mut self.cursor_name {
9794 name.paint(window, cx);
9795 }
9796
9797 window.paint_quad(cursor);
9798
9799 if let Some(block_text) = &self.block_text {
9800 block_text
9801 .paint(self.origin + origin, self.line_height, window, cx)
9802 .log_err();
9803 }
9804 }
9805
9806 pub fn shape(&self) -> CursorShape {
9807 self.shape
9808 }
9809}
9810
9811#[derive(Debug)]
9812pub struct HighlightedRange {
9813 pub start_y: Pixels,
9814 pub line_height: Pixels,
9815 pub lines: Vec<HighlightedRangeLine>,
9816 pub color: Hsla,
9817 pub corner_radius: Pixels,
9818}
9819
9820#[derive(Debug)]
9821pub struct HighlightedRangeLine {
9822 pub start_x: Pixels,
9823 pub end_x: Pixels,
9824}
9825
9826impl HighlightedRange {
9827 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
9828 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
9829 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
9830 self.paint_lines(
9831 self.start_y + self.line_height,
9832 &self.lines[1..],
9833 fill,
9834 bounds,
9835 window,
9836 );
9837 } else {
9838 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
9839 }
9840 }
9841
9842 fn paint_lines(
9843 &self,
9844 start_y: Pixels,
9845 lines: &[HighlightedRangeLine],
9846 fill: bool,
9847 _bounds: Bounds<Pixels>,
9848 window: &mut Window,
9849 ) {
9850 if lines.is_empty() {
9851 return;
9852 }
9853
9854 let first_line = lines.first().unwrap();
9855 let last_line = lines.last().unwrap();
9856
9857 let first_top_left = point(first_line.start_x, start_y);
9858 let first_top_right = point(first_line.end_x, start_y);
9859
9860 let curve_height = point(Pixels::ZERO, self.corner_radius);
9861 let curve_width = |start_x: Pixels, end_x: Pixels| {
9862 let max = (end_x - start_x) / 2.;
9863 let width = if max < self.corner_radius {
9864 max
9865 } else {
9866 self.corner_radius
9867 };
9868
9869 point(width, Pixels::ZERO)
9870 };
9871
9872 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
9873 let mut builder = if fill {
9874 gpui::PathBuilder::fill()
9875 } else {
9876 gpui::PathBuilder::stroke(px(1.))
9877 };
9878 builder.move_to(first_top_right - top_curve_width);
9879 builder.curve_to(first_top_right + curve_height, first_top_right);
9880
9881 let mut iter = lines.iter().enumerate().peekable();
9882 while let Some((ix, line)) = iter.next() {
9883 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
9884
9885 if let Some((_, next_line)) = iter.peek() {
9886 let next_top_right = point(next_line.end_x, bottom_right.y);
9887
9888 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
9889 Ordering::Equal => {
9890 builder.line_to(bottom_right);
9891 }
9892 Ordering::Less => {
9893 let curve_width = curve_width(next_top_right.x, bottom_right.x);
9894 builder.line_to(bottom_right - curve_height);
9895 if self.corner_radius > Pixels::ZERO {
9896 builder.curve_to(bottom_right - curve_width, bottom_right);
9897 }
9898 builder.line_to(next_top_right + curve_width);
9899 if self.corner_radius > Pixels::ZERO {
9900 builder.curve_to(next_top_right + curve_height, next_top_right);
9901 }
9902 }
9903 Ordering::Greater => {
9904 let curve_width = curve_width(bottom_right.x, next_top_right.x);
9905 builder.line_to(bottom_right - curve_height);
9906 if self.corner_radius > Pixels::ZERO {
9907 builder.curve_to(bottom_right + curve_width, bottom_right);
9908 }
9909 builder.line_to(next_top_right - curve_width);
9910 if self.corner_radius > Pixels::ZERO {
9911 builder.curve_to(next_top_right + curve_height, next_top_right);
9912 }
9913 }
9914 }
9915 } else {
9916 let curve_width = curve_width(line.start_x, line.end_x);
9917 builder.line_to(bottom_right - curve_height);
9918 if self.corner_radius > Pixels::ZERO {
9919 builder.curve_to(bottom_right - curve_width, bottom_right);
9920 }
9921
9922 let bottom_left = point(line.start_x, bottom_right.y);
9923 builder.line_to(bottom_left + curve_width);
9924 if self.corner_radius > Pixels::ZERO {
9925 builder.curve_to(bottom_left - curve_height, bottom_left);
9926 }
9927 }
9928 }
9929
9930 if first_line.start_x > last_line.start_x {
9931 let curve_width = curve_width(last_line.start_x, first_line.start_x);
9932 let second_top_left = point(last_line.start_x, start_y + self.line_height);
9933 builder.line_to(second_top_left + curve_height);
9934 if self.corner_radius > Pixels::ZERO {
9935 builder.curve_to(second_top_left + curve_width, second_top_left);
9936 }
9937 let first_bottom_left = point(first_line.start_x, second_top_left.y);
9938 builder.line_to(first_bottom_left - curve_width);
9939 if self.corner_radius > Pixels::ZERO {
9940 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
9941 }
9942 }
9943
9944 builder.line_to(first_top_left + curve_height);
9945 if self.corner_radius > Pixels::ZERO {
9946 builder.curve_to(first_top_left + top_curve_width, first_top_left);
9947 }
9948 builder.line_to(first_top_right - top_curve_width);
9949
9950 if let Ok(path) = builder.build() {
9951 window.paint_path(path, self.color);
9952 }
9953 }
9954}
9955
9956enum CursorPopoverType {
9957 CodeContextMenu,
9958 EditPrediction,
9959}
9960
9961pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9962 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
9963}
9964
9965fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9966 (delta.pow(1.2) / 300.0).into()
9967}
9968
9969pub fn register_action<T: Action>(
9970 editor: &Entity<Editor>,
9971 window: &mut Window,
9972 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
9973) {
9974 let editor = editor.clone();
9975 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
9976 let action = action.downcast_ref().unwrap();
9977 if phase == DispatchPhase::Bubble {
9978 editor.update(cx, |editor, cx| {
9979 listener(editor, action, window, cx);
9980 })
9981 }
9982 })
9983}
9984
9985fn compute_auto_height_layout(
9986 editor: &mut Editor,
9987 min_lines: usize,
9988 max_lines: Option<usize>,
9989 max_line_number_width: Pixels,
9990 known_dimensions: Size<Option<Pixels>>,
9991 available_width: AvailableSpace,
9992 window: &mut Window,
9993 cx: &mut Context<Editor>,
9994) -> Option<Size<Pixels>> {
9995 let width = known_dimensions.width.or({
9996 if let AvailableSpace::Definite(available_width) = available_width {
9997 Some(available_width)
9998 } else {
9999 None
10000 }
10001 })?;
10002 if let Some(height) = known_dimensions.height {
10003 return Some(size(width, height));
10004 }
10005
10006 let style = editor.style.as_ref().unwrap();
10007 let font_id = window.text_system().resolve_font(&style.text.font());
10008 let font_size = style.text.font_size.to_pixels(window.rem_size());
10009 let line_height = style.text.line_height_in_pixels(window.rem_size());
10010 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10011
10012 let mut snapshot = editor.snapshot(window, cx);
10013 let gutter_dimensions = snapshot
10014 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10015 .or_else(|| {
10016 editor
10017 .offset_content
10018 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10019 })
10020 .unwrap_or_default();
10021
10022 editor.gutter_dimensions = gutter_dimensions;
10023 let text_width = width - gutter_dimensions.width;
10024 let overscroll = size(em_width, px(0.));
10025
10026 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10027 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
10028 if editor.set_wrap_width(Some(editor_width), cx) {
10029 snapshot = editor.snapshot(window, cx);
10030 }
10031 }
10032
10033 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10034
10035 let min_height = line_height * min_lines as f32;
10036 let content_height = scroll_height.max(min_height);
10037
10038 let final_height = if let Some(max_lines) = max_lines {
10039 let max_height = line_height * max_lines as f32;
10040 content_height.min(max_height)
10041 } else {
10042 content_height
10043 };
10044
10045 Some(size(width, final_height))
10046}
10047
10048#[cfg(test)]
10049mod tests {
10050 use super::*;
10051 use crate::{
10052 Editor, MultiBuffer, SelectionEffects,
10053 display_map::{BlockPlacement, BlockProperties},
10054 editor_tests::{init_test, update_test_language_settings},
10055 };
10056 use gpui::{TestAppContext, VisualTestContext};
10057 use language::language_settings;
10058 use log::info;
10059 use std::num::NonZeroU32;
10060 use util::test::sample_text;
10061
10062 #[gpui::test]
10063 fn test_shape_line_numbers(cx: &mut TestAppContext) {
10064 init_test(cx, |_| {});
10065 let window = cx.add_window(|window, cx| {
10066 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10067 Editor::new(EditorMode::full(), buffer, None, window, cx)
10068 });
10069
10070 let editor = window.root(cx).unwrap();
10071 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10072 let line_height = window
10073 .update(cx, |_, window, _| {
10074 style.text.line_height_in_pixels(window.rem_size())
10075 })
10076 .unwrap();
10077 let element = EditorElement::new(&editor, style);
10078 let snapshot = window
10079 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10080 .unwrap();
10081
10082 let layouts = cx
10083 .update_window(*window, |_, window, cx| {
10084 element.layout_line_numbers(
10085 None,
10086 GutterDimensions {
10087 left_padding: Pixels::ZERO,
10088 right_padding: Pixels::ZERO,
10089 width: px(30.0),
10090 margin: Pixels::ZERO,
10091 git_blame_entries_width: None,
10092 },
10093 line_height,
10094 gpui::Point::default(),
10095 DisplayRow(0)..DisplayRow(6),
10096 &(0..6)
10097 .map(|row| RowInfo {
10098 buffer_row: Some(row),
10099 ..Default::default()
10100 })
10101 .collect::<Vec<_>>(),
10102 &BTreeMap::default(),
10103 Some(DisplayPoint::new(DisplayRow(0), 0)),
10104 &snapshot,
10105 window,
10106 cx,
10107 )
10108 })
10109 .unwrap();
10110 assert_eq!(layouts.len(), 6);
10111
10112 let relative_rows = window
10113 .update(cx, |editor, window, cx| {
10114 let snapshot = editor.snapshot(window, cx);
10115 element.calculate_relative_line_numbers(
10116 &snapshot,
10117 &(DisplayRow(0)..DisplayRow(6)),
10118 Some(DisplayRow(3)),
10119 )
10120 })
10121 .unwrap();
10122 assert_eq!(relative_rows[&DisplayRow(0)], 3);
10123 assert_eq!(relative_rows[&DisplayRow(1)], 2);
10124 assert_eq!(relative_rows[&DisplayRow(2)], 1);
10125 // current line has no relative number
10126 assert_eq!(relative_rows[&DisplayRow(4)], 1);
10127 assert_eq!(relative_rows[&DisplayRow(5)], 2);
10128
10129 // works if cursor is before screen
10130 let relative_rows = window
10131 .update(cx, |editor, window, cx| {
10132 let snapshot = editor.snapshot(window, cx);
10133 element.calculate_relative_line_numbers(
10134 &snapshot,
10135 &(DisplayRow(3)..DisplayRow(6)),
10136 Some(DisplayRow(1)),
10137 )
10138 })
10139 .unwrap();
10140 assert_eq!(relative_rows.len(), 3);
10141 assert_eq!(relative_rows[&DisplayRow(3)], 2);
10142 assert_eq!(relative_rows[&DisplayRow(4)], 3);
10143 assert_eq!(relative_rows[&DisplayRow(5)], 4);
10144
10145 // works if cursor is after screen
10146 let relative_rows = window
10147 .update(cx, |editor, window, cx| {
10148 let snapshot = editor.snapshot(window, cx);
10149 element.calculate_relative_line_numbers(
10150 &snapshot,
10151 &(DisplayRow(0)..DisplayRow(3)),
10152 Some(DisplayRow(6)),
10153 )
10154 })
10155 .unwrap();
10156 assert_eq!(relative_rows.len(), 3);
10157 assert_eq!(relative_rows[&DisplayRow(0)], 5);
10158 assert_eq!(relative_rows[&DisplayRow(1)], 4);
10159 assert_eq!(relative_rows[&DisplayRow(2)], 3);
10160 }
10161
10162 #[gpui::test]
10163 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10164 init_test(cx, |_| {});
10165
10166 let window = cx.add_window(|window, cx| {
10167 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10168 Editor::new(EditorMode::full(), buffer, None, window, cx)
10169 });
10170 let cx = &mut VisualTestContext::from_window(*window, cx);
10171 let editor = window.root(cx).unwrap();
10172 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10173
10174 window
10175 .update(cx, |editor, window, cx| {
10176 editor.cursor_shape = CursorShape::Block;
10177 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10178 s.select_ranges([
10179 Point::new(0, 0)..Point::new(1, 0),
10180 Point::new(3, 2)..Point::new(3, 3),
10181 Point::new(5, 6)..Point::new(6, 0),
10182 ]);
10183 });
10184 })
10185 .unwrap();
10186
10187 let (_, state) = cx.draw(
10188 point(px(500.), px(500.)),
10189 size(px(500.), px(500.)),
10190 |_, _| EditorElement::new(&editor, style),
10191 );
10192
10193 assert_eq!(state.selections.len(), 1);
10194 let local_selections = &state.selections[0].1;
10195 assert_eq!(local_selections.len(), 3);
10196 // moves cursor back one line
10197 assert_eq!(
10198 local_selections[0].head,
10199 DisplayPoint::new(DisplayRow(0), 6)
10200 );
10201 assert_eq!(
10202 local_selections[0].range,
10203 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10204 );
10205
10206 // moves cursor back one column
10207 assert_eq!(
10208 local_selections[1].range,
10209 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10210 );
10211 assert_eq!(
10212 local_selections[1].head,
10213 DisplayPoint::new(DisplayRow(3), 2)
10214 );
10215
10216 // leaves cursor on the max point
10217 assert_eq!(
10218 local_selections[2].range,
10219 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10220 );
10221 assert_eq!(
10222 local_selections[2].head,
10223 DisplayPoint::new(DisplayRow(6), 0)
10224 );
10225
10226 // active lines does not include 1 (even though the range of the selection does)
10227 assert_eq!(
10228 state.active_rows.keys().cloned().collect::<Vec<_>>(),
10229 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10230 );
10231 }
10232
10233 #[gpui::test]
10234 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10235 init_test(cx, |_| {});
10236
10237 let window = cx.add_window(|window, cx| {
10238 let buffer = MultiBuffer::build_simple("", cx);
10239 Editor::new(EditorMode::full(), buffer, None, window, cx)
10240 });
10241 let cx = &mut VisualTestContext::from_window(*window, cx);
10242 let editor = window.root(cx).unwrap();
10243 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10244 window
10245 .update(cx, |editor, window, cx| {
10246 editor.set_placeholder_text("hello", cx);
10247 editor.insert_blocks(
10248 [BlockProperties {
10249 style: BlockStyle::Fixed,
10250 placement: BlockPlacement::Above(Anchor::min()),
10251 height: Some(3),
10252 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10253 priority: 0,
10254 }],
10255 None,
10256 cx,
10257 );
10258
10259 // Blur the editor so that it displays placeholder text.
10260 window.blur();
10261 })
10262 .unwrap();
10263
10264 let (_, state) = cx.draw(
10265 point(px(500.), px(500.)),
10266 size(px(500.), px(500.)),
10267 |_, _| EditorElement::new(&editor, style),
10268 );
10269 assert_eq!(state.position_map.line_layouts.len(), 4);
10270 assert_eq!(state.line_numbers.len(), 1);
10271 assert_eq!(
10272 state
10273 .line_numbers
10274 .get(&MultiBufferRow(0))
10275 .map(|line_number| line_number.shaped_line.text.as_ref()),
10276 Some("1")
10277 );
10278 }
10279
10280 #[gpui::test]
10281 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10282 const TAB_SIZE: u32 = 4;
10283
10284 let input_text = "\t \t|\t| a b";
10285 let expected_invisibles = vec![
10286 Invisible::Tab {
10287 line_start_offset: 0,
10288 line_end_offset: TAB_SIZE as usize,
10289 },
10290 Invisible::Whitespace {
10291 line_offset: TAB_SIZE as usize,
10292 },
10293 Invisible::Tab {
10294 line_start_offset: TAB_SIZE as usize + 1,
10295 line_end_offset: TAB_SIZE as usize * 2,
10296 },
10297 Invisible::Tab {
10298 line_start_offset: TAB_SIZE as usize * 2 + 1,
10299 line_end_offset: TAB_SIZE as usize * 3,
10300 },
10301 Invisible::Whitespace {
10302 line_offset: TAB_SIZE as usize * 3 + 1,
10303 },
10304 Invisible::Whitespace {
10305 line_offset: TAB_SIZE as usize * 3 + 3,
10306 },
10307 ];
10308 assert_eq!(
10309 expected_invisibles.len(),
10310 input_text
10311 .chars()
10312 .filter(|initial_char| initial_char.is_whitespace())
10313 .count(),
10314 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10315 );
10316
10317 for show_line_numbers in [true, false] {
10318 init_test(cx, |s| {
10319 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10320 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10321 });
10322
10323 let actual_invisibles = collect_invisibles_from_new_editor(
10324 cx,
10325 EditorMode::full(),
10326 input_text,
10327 px(500.0),
10328 show_line_numbers,
10329 );
10330
10331 assert_eq!(expected_invisibles, actual_invisibles);
10332 }
10333 }
10334
10335 #[gpui::test]
10336 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10337 init_test(cx, |s| {
10338 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10339 s.defaults.tab_size = NonZeroU32::new(4);
10340 });
10341
10342 for editor_mode_without_invisibles in [
10343 EditorMode::SingleLine,
10344 EditorMode::AutoHeight {
10345 min_lines: 1,
10346 max_lines: Some(100),
10347 },
10348 ] {
10349 for show_line_numbers in [true, false] {
10350 let invisibles = collect_invisibles_from_new_editor(
10351 cx,
10352 editor_mode_without_invisibles.clone(),
10353 "\t\t\t| | a b",
10354 px(500.0),
10355 show_line_numbers,
10356 );
10357 assert!(
10358 invisibles.is_empty(),
10359 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10360 );
10361 }
10362 }
10363 }
10364
10365 #[gpui::test]
10366 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10367 let tab_size = 4;
10368 let input_text = "a\tbcd ".repeat(9);
10369 let repeated_invisibles = [
10370 Invisible::Tab {
10371 line_start_offset: 1,
10372 line_end_offset: tab_size as usize,
10373 },
10374 Invisible::Whitespace {
10375 line_offset: tab_size as usize + 3,
10376 },
10377 Invisible::Whitespace {
10378 line_offset: tab_size as usize + 4,
10379 },
10380 Invisible::Whitespace {
10381 line_offset: tab_size as usize + 5,
10382 },
10383 Invisible::Whitespace {
10384 line_offset: tab_size as usize + 6,
10385 },
10386 Invisible::Whitespace {
10387 line_offset: tab_size as usize + 7,
10388 },
10389 ];
10390 let expected_invisibles = std::iter::once(repeated_invisibles)
10391 .cycle()
10392 .take(9)
10393 .flatten()
10394 .collect::<Vec<_>>();
10395 assert_eq!(
10396 expected_invisibles.len(),
10397 input_text
10398 .chars()
10399 .filter(|initial_char| initial_char.is_whitespace())
10400 .count(),
10401 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10402 );
10403 info!("Expected invisibles: {expected_invisibles:?}");
10404
10405 init_test(cx, |_| {});
10406
10407 // Put the same string with repeating whitespace pattern into editors of various size,
10408 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10409 let resize_step = 10.0;
10410 let mut editor_width = 200.0;
10411 while editor_width <= 1000.0 {
10412 for show_line_numbers in [true, false] {
10413 update_test_language_settings(cx, |s| {
10414 s.defaults.tab_size = NonZeroU32::new(tab_size);
10415 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10416 s.defaults.preferred_line_length = Some(editor_width as u32);
10417 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10418 });
10419
10420 let actual_invisibles = collect_invisibles_from_new_editor(
10421 cx,
10422 EditorMode::full(),
10423 &input_text,
10424 px(editor_width),
10425 show_line_numbers,
10426 );
10427
10428 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10429 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10430 let mut i = 0;
10431 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10432 i = actual_index;
10433 match expected_invisibles.get(i) {
10434 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10435 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10436 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10437 _ => {
10438 panic!(
10439 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10440 )
10441 }
10442 },
10443 None => {
10444 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10445 }
10446 }
10447 }
10448 let missing_expected_invisibles = &expected_invisibles[i + 1..];
10449 assert!(
10450 missing_expected_invisibles.is_empty(),
10451 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10452 );
10453
10454 editor_width += resize_step;
10455 }
10456 }
10457 }
10458
10459 fn collect_invisibles_from_new_editor(
10460 cx: &mut TestAppContext,
10461 editor_mode: EditorMode,
10462 input_text: &str,
10463 editor_width: Pixels,
10464 show_line_numbers: bool,
10465 ) -> Vec<Invisible> {
10466 info!(
10467 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10468 editor_width.0
10469 );
10470 let window = cx.add_window(|window, cx| {
10471 let buffer = MultiBuffer::build_simple(input_text, cx);
10472 Editor::new(editor_mode, buffer, None, window, cx)
10473 });
10474 let cx = &mut VisualTestContext::from_window(*window, cx);
10475 let editor = window.root(cx).unwrap();
10476
10477 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10478 window
10479 .update(cx, |editor, _, cx| {
10480 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10481 editor.set_wrap_width(Some(editor_width), cx);
10482 editor.set_show_line_numbers(show_line_numbers, cx);
10483 })
10484 .unwrap();
10485 let (_, state) = cx.draw(
10486 point(px(500.), px(500.)),
10487 size(px(500.), px(500.)),
10488 |_, _| EditorElement::new(&editor, style),
10489 );
10490 state
10491 .position_map
10492 .line_layouts
10493 .iter()
10494 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10495 .cloned()
10496 .collect()
10497 }
10498}