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