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