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