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