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