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