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