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