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