1use crate::{
2 ActiveDiagnostic, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext, ChunkReplacement,
3 CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker, ConflictsOuter,
4 ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape, CustomBlockId,
5 DisplayDiffHunk, DisplayPoint, DisplayRow, EditDisplayMode, EditPrediction, Editor, EditorMode,
6 EditorSettings, EditorSnapshot, EditorStyle, FILE_HEADER_HEIGHT, FocusedBlock,
7 GutterDimensions, HalfPageDown, HalfPageUp, HandleInput, HoveredCursor, InlayHintRefreshReason,
8 JumpData, LineDown, LineHighlight, LineUp, MAX_LINE_LEN, MINIMAP_FONT_SIZE,
9 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts, PageDown, PageUp, PhantomBreakpointIndicator,
10 PhantomDiffReviewIndicator, Point, RowExt, RowRangeExt, SelectPhase, Selection,
11 SelectionDragState, SelectionEffects, SizingBehavior, SoftWrap, StickyHeaderExcerpt, ToPoint,
12 ToggleFold, ToggleFoldAll,
13 code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
14 column_pixels,
15 display_map::{
16 Block, BlockContext, BlockStyle, ChunkRendererId, DisplaySnapshot, EditorMargins,
17 HighlightKey, HighlightedChunk, ToDisplayPoint,
18 },
19 editor_settings::{
20 CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, Minimap,
21 MinimapThumb, MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes,
22 ScrollbarDiagnostics, ShowMinimap,
23 },
24 git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer},
25 hover_popover::{
26 self, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
27 POPOVER_RIGHT_OFFSET, hover_at,
28 },
29 inlay_hint_settings,
30 mouse_context_menu::{self, MenuPosition},
31 scroll::{
32 ActiveScrollbarState, Autoscroll, ScrollOffset, ScrollPixelOffset, ScrollbarThumbState,
33 scroll_amount::ScrollAmount,
34 },
35};
36use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
37use collections::{BTreeMap, HashMap};
38use feature_flags::{DiffReviewFeatureFlag, FeatureFlagAppExt as _};
39use file_icons::FileIcons;
40use git::{Oid, blame::BlameEntry, commit::ParsedCommitMessage, status::FileStatus};
41use gpui::{
42 Action, Along, AnyElement, App, AppContext, AvailableSpace, Axis as ScrollbarAxis, BorderStyle,
43 Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners, CursorStyle,
44 DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable as _, FontId, FontWeight,
45 GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero,
46 KeybindingKeystroke, Length, Modifiers, ModifiersChangedEvent, MouseButton, MouseClickEvent,
47 MouseDownEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent, PaintQuad, ParentElement,
48 Pixels, PressureStage, ScrollDelta, ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString,
49 Size, StatefulInteractiveElement, Style, Styled, StyledText, TextAlign, TextRun,
50 TextStyleRefinement, WeakEntity, Window, anchored, deferred, div, fill, linear_color_stop,
51 linear_gradient, outline, pattern_slash, point, px, quad, relative, size, solid_background,
52 transparent_black,
53};
54use itertools::Itertools;
55use language::{IndentGuideSettings, language_settings::ShowWhitespaceSetting};
56use markdown::Markdown;
57use multi_buffer::{
58 Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint,
59 MultiBufferRow, RowInfo,
60};
61
62use edit_prediction_types::EditPredictionGranularity;
63use project::{
64 DisableAiSettings, Entry, ProjectPath,
65 debugger::breakpoint_store::{Breakpoint, BreakpointSessionState},
66 project_settings::ProjectSettings,
67};
68use settings::{
69 GitGutterSetting, GitHunkStyleSetting, IndentGuideBackgroundColoring, IndentGuideColoring,
70 RelativeLineNumbers, Settings,
71};
72use smallvec::{SmallVec, smallvec};
73use std::{
74 any::TypeId,
75 borrow::Cow,
76 cell::Cell,
77 cmp::{self, Ordering},
78 fmt::{self, Write},
79 iter, mem,
80 ops::{Deref, Range},
81 path::{self, Path},
82 rc::Rc,
83 sync::Arc,
84 time::{Duration, Instant},
85};
86use sum_tree::Bias;
87use text::{BufferId, SelectionGoal};
88use theme::{ActiveTheme, Appearance, BufferLineHeight, PlayerColor};
89use ui::utils::ensure_minimum_contrast;
90use ui::{
91 ButtonLike, ContextMenu, Indicator, KeyBinding, POPOVER_Y_PADDING, Tooltip, prelude::*,
92 right_click_menu, scrollbars::ShowScrollbar, text_for_keystroke,
93};
94use unicode_segmentation::UnicodeSegmentation;
95use util::post_inc;
96use util::{RangeExt, ResultExt, debug_panic};
97use workspace::{
98 CollaboratorId, ItemHandle, ItemSettings, OpenInTerminal, OpenTerminal, RevealInProjectPanel,
99 Workspace,
100 item::{BreadcrumbText, Item, ItemBufferKind},
101 notifications::NotifyTaskExt,
102};
103
104/// Determines what kinds of highlights should be applied to a lines background.
105#[derive(Clone, Copy, Default)]
106struct LineHighlightSpec {
107 selection: bool,
108 breakpoint: bool,
109 _active_stack_frame: bool,
110}
111
112#[derive(Debug)]
113struct SelectionLayout {
114 head: DisplayPoint,
115 cursor_shape: CursorShape,
116 is_newest: bool,
117 is_local: bool,
118 range: Range<DisplayPoint>,
119 active_rows: Range<DisplayRow>,
120 user_name: Option<SharedString>,
121}
122
123struct InlineBlameLayout {
124 element: AnyElement,
125 bounds: Bounds<Pixels>,
126 buffer_id: BufferId,
127 entry: BlameEntry,
128}
129
130impl SelectionLayout {
131 fn new<T: ToPoint + ToDisplayPoint + Clone>(
132 selection: Selection<T>,
133 line_mode: bool,
134 cursor_offset: bool,
135 cursor_shape: CursorShape,
136 map: &DisplaySnapshot,
137 is_newest: bool,
138 is_local: bool,
139 user_name: Option<SharedString>,
140 ) -> Self {
141 let point_selection = selection.map(|p| p.to_point(map.buffer_snapshot()));
142 let display_selection = point_selection.map(|p| p.to_display_point(map));
143 let mut range = display_selection.range();
144 let mut head = display_selection.head();
145 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
146 ..map.next_line_boundary(point_selection.end).1.row();
147
148 // vim visual line mode
149 if line_mode {
150 let point_range = map.expand_to_line(point_selection.range());
151 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
152 }
153
154 // any vim visual mode (including line mode)
155 if cursor_offset && !range.is_empty() && !selection.reversed {
156 if head.column() > 0 {
157 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left);
158 } else if head.row().0 > 0 && head != map.max_point() {
159 head = map.clip_point(
160 DisplayPoint::new(
161 head.row().previous_row(),
162 map.line_len(head.row().previous_row()),
163 ),
164 Bias::Left,
165 );
166 // updating range.end is a no-op unless you're cursor is
167 // on the newline containing a multi-buffer divider
168 // in which case the clip_point may have moved the head up
169 // an additional row.
170 range.end = DisplayPoint::new(head.row().next_row(), 0);
171 active_rows.end = head.row();
172 }
173 }
174
175 Self {
176 head,
177 cursor_shape,
178 is_newest,
179 is_local,
180 range,
181 active_rows,
182 user_name,
183 }
184 }
185}
186
187#[derive(Default)]
188struct RenderBlocksOutput {
189 blocks: Vec<BlockLayout>,
190 row_block_types: HashMap<DisplayRow, bool>,
191 resized_blocks: Option<HashMap<CustomBlockId, u32>>,
192}
193
194pub struct EditorElement {
195 editor: Entity<Editor>,
196 style: EditorStyle,
197 split_side: Option<SplitSide>,
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub enum SplitSide {
202 Left,
203 Right,
204}
205
206impl EditorElement {
207 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
208
209 pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
210 Self {
211 editor: editor.clone(),
212 style,
213 split_side: None,
214 }
215 }
216
217 pub fn set_split_side(&mut self, side: SplitSide) {
218 self.split_side = Some(side);
219 }
220
221 fn should_show_buffer_headers(&self) -> bool {
222 self.split_side.is_none()
223 }
224
225 fn register_actions(&self, window: &mut Window, cx: &mut App) {
226 let editor = &self.editor;
227 editor.update(cx, |editor, cx| {
228 for action in editor.editor_actions.borrow().values() {
229 (action)(editor, window, cx)
230 }
231 });
232
233 crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
234 crate::clangd_ext::apply_related_actions(editor, window, cx);
235
236 register_action(editor, window, Editor::open_context_menu);
237 register_action(editor, window, Editor::move_left);
238 register_action(editor, window, Editor::move_right);
239 register_action(editor, window, Editor::move_down);
240 register_action(editor, window, Editor::move_down_by_lines);
241 register_action(editor, window, Editor::select_down_by_lines);
242 register_action(editor, window, Editor::move_up);
243 register_action(editor, window, Editor::move_up_by_lines);
244 register_action(editor, window, Editor::select_up_by_lines);
245 register_action(editor, window, Editor::select_page_down);
246 register_action(editor, window, Editor::select_page_up);
247 register_action(editor, window, Editor::cancel);
248 register_action(editor, window, Editor::newline);
249 register_action(editor, window, Editor::newline_above);
250 register_action(editor, window, Editor::newline_below);
251 register_action(editor, window, Editor::backspace);
252 register_action(editor, window, Editor::blame_hover);
253 register_action(editor, window, Editor::delete);
254 register_action(editor, window, Editor::tab);
255 register_action(editor, window, Editor::next_snippet_tabstop);
256 register_action(editor, window, Editor::previous_snippet_tabstop);
257 register_action(editor, window, Editor::backtab);
258 register_action(editor, window, Editor::indent);
259 register_action(editor, window, Editor::outdent);
260 register_action(editor, window, Editor::autoindent);
261 register_action(editor, window, Editor::delete_line);
262 register_action(editor, window, Editor::join_lines);
263 register_action(editor, window, Editor::sort_lines_by_length);
264 register_action(editor, window, Editor::sort_lines_case_sensitive);
265 register_action(editor, window, Editor::sort_lines_case_insensitive);
266 register_action(editor, window, Editor::reverse_lines);
267 register_action(editor, window, Editor::shuffle_lines);
268 register_action(editor, window, Editor::rotate_selections_forward);
269 register_action(editor, window, Editor::rotate_selections_backward);
270 register_action(editor, window, Editor::convert_indentation_to_spaces);
271 register_action(editor, window, Editor::convert_indentation_to_tabs);
272 register_action(editor, window, Editor::convert_to_upper_case);
273 register_action(editor, window, Editor::convert_to_lower_case);
274 register_action(editor, window, Editor::convert_to_title_case);
275 register_action(editor, window, Editor::convert_to_snake_case);
276 register_action(editor, window, Editor::convert_to_kebab_case);
277 register_action(editor, window, Editor::convert_to_upper_camel_case);
278 register_action(editor, window, Editor::convert_to_lower_camel_case);
279 register_action(editor, window, Editor::convert_to_opposite_case);
280 register_action(editor, window, Editor::convert_to_sentence_case);
281 register_action(editor, window, Editor::toggle_case);
282 register_action(editor, window, Editor::convert_to_rot13);
283 register_action(editor, window, Editor::convert_to_rot47);
284 register_action(editor, window, Editor::delete_to_previous_word_start);
285 register_action(editor, window, Editor::delete_to_previous_subword_start);
286 register_action(editor, window, Editor::delete_to_next_word_end);
287 register_action(editor, window, Editor::delete_to_next_subword_end);
288 register_action(editor, window, Editor::delete_to_beginning_of_line);
289 register_action(editor, window, Editor::delete_to_end_of_line);
290 register_action(editor, window, Editor::cut_to_end_of_line);
291 register_action(editor, window, Editor::duplicate_line_up);
292 register_action(editor, window, Editor::duplicate_line_down);
293 register_action(editor, window, Editor::duplicate_selection);
294 register_action(editor, window, Editor::move_line_up);
295 register_action(editor, window, Editor::move_line_down);
296 register_action(editor, window, Editor::transpose);
297 register_action(editor, window, Editor::rewrap);
298 register_action(editor, window, Editor::cut);
299 register_action(editor, window, Editor::kill_ring_cut);
300 register_action(editor, window, Editor::kill_ring_yank);
301 register_action(editor, window, Editor::copy);
302 register_action(editor, window, Editor::copy_and_trim);
303 register_action(editor, window, Editor::diff_clipboard_with_selection);
304 register_action(editor, window, Editor::paste);
305 register_action(editor, window, Editor::undo);
306 register_action(editor, window, Editor::redo);
307 register_action(editor, window, Editor::move_page_up);
308 register_action(editor, window, Editor::move_page_down);
309 register_action(editor, window, Editor::next_screen);
310 register_action(editor, window, Editor::scroll_cursor_top);
311 register_action(editor, window, Editor::scroll_cursor_center);
312 register_action(editor, window, Editor::scroll_cursor_bottom);
313 register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
314 register_action(editor, window, |editor, _: &LineDown, window, cx| {
315 editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
316 });
317 register_action(editor, window, |editor, _: &LineUp, window, cx| {
318 editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
319 });
320 register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
321 editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
322 });
323 register_action(
324 editor,
325 window,
326 |editor, HandleInput(text): &HandleInput, window, cx| {
327 if text.is_empty() {
328 return;
329 }
330 editor.handle_input(text, window, cx);
331 },
332 );
333 register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
334 editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
335 });
336 register_action(editor, window, |editor, _: &PageDown, window, cx| {
337 editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
338 });
339 register_action(editor, window, |editor, _: &PageUp, window, cx| {
340 editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
341 });
342 register_action(editor, window, Editor::move_to_previous_word_start);
343 register_action(editor, window, Editor::move_to_previous_subword_start);
344 register_action(editor, window, Editor::move_to_next_word_end);
345 register_action(editor, window, Editor::move_to_next_subword_end);
346 register_action(editor, window, Editor::move_to_beginning_of_line);
347 register_action(editor, window, Editor::move_to_end_of_line);
348 register_action(editor, window, Editor::move_to_start_of_paragraph);
349 register_action(editor, window, Editor::move_to_end_of_paragraph);
350 register_action(editor, window, Editor::move_to_beginning);
351 register_action(editor, window, Editor::move_to_end);
352 register_action(editor, window, Editor::move_to_start_of_excerpt);
353 register_action(editor, window, Editor::move_to_start_of_next_excerpt);
354 register_action(editor, window, Editor::move_to_end_of_excerpt);
355 register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
356 register_action(editor, window, Editor::select_up);
357 register_action(editor, window, Editor::select_down);
358 register_action(editor, window, Editor::select_left);
359 register_action(editor, window, Editor::select_right);
360 register_action(editor, window, Editor::select_to_previous_word_start);
361 register_action(editor, window, Editor::select_to_previous_subword_start);
362 register_action(editor, window, Editor::select_to_next_word_end);
363 register_action(editor, window, Editor::select_to_next_subword_end);
364 register_action(editor, window, Editor::select_to_beginning_of_line);
365 register_action(editor, window, Editor::select_to_end_of_line);
366 register_action(editor, window, Editor::select_to_start_of_paragraph);
367 register_action(editor, window, Editor::select_to_end_of_paragraph);
368 register_action(editor, window, Editor::select_to_start_of_excerpt);
369 register_action(editor, window, Editor::select_to_start_of_next_excerpt);
370 register_action(editor, window, Editor::select_to_end_of_excerpt);
371 register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
372 register_action(editor, window, Editor::select_to_beginning);
373 register_action(editor, window, Editor::select_to_end);
374 register_action(editor, window, Editor::select_all);
375 register_action(editor, window, |editor, action, window, cx| {
376 editor.select_all_matches(action, window, cx).log_err();
377 });
378 register_action(editor, window, Editor::select_line);
379 register_action(editor, window, Editor::split_selection_into_lines);
380 register_action(editor, window, Editor::add_selection_above);
381 register_action(editor, window, Editor::add_selection_below);
382 register_action(editor, window, Editor::insert_snippet_at_selections);
383 register_action(editor, window, |editor, action, window, cx| {
384 editor.select_next(action, window, cx).log_err();
385 });
386 register_action(editor, window, |editor, action, window, cx| {
387 editor.select_previous(action, window, cx).log_err();
388 });
389 register_action(editor, window, |editor, action, window, cx| {
390 editor.find_next_match(action, window, cx).log_err();
391 });
392 register_action(editor, window, |editor, action, window, cx| {
393 editor.find_previous_match(action, window, cx).log_err();
394 });
395 register_action(editor, window, Editor::toggle_comments);
396 register_action(editor, window, Editor::select_larger_syntax_node);
397 register_action(editor, window, Editor::select_smaller_syntax_node);
398 register_action(editor, window, Editor::select_next_syntax_node);
399 register_action(editor, window, Editor::select_prev_syntax_node);
400 register_action(
401 editor,
402 window,
403 Editor::select_to_start_of_larger_syntax_node,
404 );
405 register_action(editor, window, Editor::select_to_end_of_larger_syntax_node);
406 register_action(editor, window, Editor::unwrap_syntax_node);
407 register_action(editor, window, Editor::move_to_start_of_larger_syntax_node);
408 register_action(editor, window, Editor::move_to_end_of_larger_syntax_node);
409 register_action(editor, window, Editor::select_enclosing_symbol);
410 register_action(editor, window, Editor::move_to_enclosing_bracket);
411 register_action(editor, window, Editor::undo_selection);
412 register_action(editor, window, Editor::redo_selection);
413 if editor.read(cx).buffer_kind(cx) == ItemBufferKind::Multibuffer {
414 register_action(editor, window, Editor::expand_excerpts);
415 register_action(editor, window, Editor::expand_excerpts_up);
416 register_action(editor, window, Editor::expand_excerpts_down);
417 }
418 register_action(editor, window, Editor::go_to_diagnostic);
419 register_action(editor, window, Editor::go_to_prev_diagnostic);
420 register_action(editor, window, Editor::go_to_next_hunk);
421 register_action(editor, window, Editor::go_to_prev_hunk);
422 register_action(editor, window, Editor::go_to_next_document_highlight);
423 register_action(editor, window, Editor::go_to_prev_document_highlight);
424 register_action(editor, window, |editor, action, window, cx| {
425 editor
426 .go_to_definition(action, window, cx)
427 .detach_and_log_err(cx);
428 });
429 register_action(editor, window, |editor, action, window, cx| {
430 editor
431 .go_to_definition_split(action, window, cx)
432 .detach_and_log_err(cx);
433 });
434 register_action(editor, window, |editor, action, window, cx| {
435 editor
436 .go_to_declaration(action, window, cx)
437 .detach_and_log_err(cx);
438 });
439 register_action(editor, window, |editor, action, window, cx| {
440 editor
441 .go_to_declaration_split(action, window, cx)
442 .detach_and_log_err(cx);
443 });
444 register_action(editor, window, |editor, action, window, cx| {
445 editor
446 .go_to_implementation(action, window, cx)
447 .detach_and_log_err(cx);
448 });
449 register_action(editor, window, |editor, action, window, cx| {
450 editor
451 .go_to_implementation_split(action, window, cx)
452 .detach_and_log_err(cx);
453 });
454 register_action(editor, window, |editor, action, window, cx| {
455 editor
456 .go_to_type_definition(action, window, cx)
457 .detach_and_log_err(cx);
458 });
459 register_action(editor, window, |editor, action, window, cx| {
460 editor
461 .go_to_type_definition_split(action, window, cx)
462 .detach_and_log_err(cx);
463 });
464 register_action(editor, window, Editor::open_url);
465 register_action(editor, window, Editor::open_selected_filename);
466 register_action(editor, window, Editor::fold);
467 register_action(editor, window, Editor::fold_at_level);
468 register_action(editor, window, Editor::fold_at_level_1);
469 register_action(editor, window, Editor::fold_at_level_2);
470 register_action(editor, window, Editor::fold_at_level_3);
471 register_action(editor, window, Editor::fold_at_level_4);
472 register_action(editor, window, Editor::fold_at_level_5);
473 register_action(editor, window, Editor::fold_at_level_6);
474 register_action(editor, window, Editor::fold_at_level_7);
475 register_action(editor, window, Editor::fold_at_level_8);
476 register_action(editor, window, Editor::fold_at_level_9);
477 register_action(editor, window, Editor::fold_all);
478 register_action(editor, window, Editor::fold_function_bodies);
479 register_action(editor, window, Editor::fold_recursive);
480 register_action(editor, window, Editor::toggle_fold);
481 register_action(editor, window, Editor::toggle_fold_recursive);
482 register_action(editor, window, Editor::toggle_fold_all);
483 register_action(editor, window, Editor::unfold_lines);
484 register_action(editor, window, Editor::unfold_recursive);
485 register_action(editor, window, Editor::unfold_all);
486 register_action(editor, window, Editor::fold_selected_ranges);
487 register_action(editor, window, Editor::set_mark);
488 register_action(editor, window, Editor::swap_selection_ends);
489 register_action(editor, window, Editor::show_completions);
490 register_action(editor, window, Editor::show_word_completions);
491 register_action(editor, window, Editor::toggle_code_actions);
492 register_action(editor, window, Editor::open_excerpts);
493 register_action(editor, window, Editor::open_excerpts_in_split);
494 register_action(editor, window, Editor::toggle_soft_wrap);
495 register_action(editor, window, Editor::toggle_tab_bar);
496 register_action(editor, window, Editor::toggle_line_numbers);
497 register_action(editor, window, Editor::toggle_relative_line_numbers);
498 register_action(editor, window, Editor::toggle_indent_guides);
499 register_action(editor, window, Editor::toggle_inlay_hints);
500 register_action(editor, window, Editor::toggle_semantic_highlights);
501 register_action(editor, window, Editor::toggle_edit_predictions);
502 if editor.read(cx).diagnostics_enabled() {
503 register_action(editor, window, Editor::toggle_diagnostics);
504 }
505 if editor.read(cx).inline_diagnostics_enabled() {
506 register_action(editor, window, Editor::toggle_inline_diagnostics);
507 }
508 if editor.read(cx).supports_minimap(cx) {
509 register_action(editor, window, Editor::toggle_minimap);
510 }
511 register_action(editor, window, hover_popover::hover);
512 register_action(editor, window, Editor::reveal_in_finder);
513 register_action(editor, window, Editor::copy_path);
514 register_action(editor, window, Editor::copy_relative_path);
515 register_action(editor, window, Editor::copy_file_name);
516 register_action(editor, window, Editor::copy_file_name_without_extension);
517 register_action(editor, window, Editor::copy_highlight_json);
518 register_action(editor, window, Editor::copy_permalink_to_line);
519 register_action(editor, window, Editor::open_permalink_to_line);
520 register_action(editor, window, Editor::copy_file_location);
521 register_action(editor, window, Editor::toggle_git_blame);
522 register_action(editor, window, Editor::toggle_git_blame_inline);
523 register_action(editor, window, Editor::open_git_blame_commit);
524 register_action(editor, window, Editor::toggle_selected_diff_hunks);
525 register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
526 register_action(editor, window, Editor::stage_and_next);
527 register_action(editor, window, Editor::unstage_and_next);
528 register_action(editor, window, Editor::expand_all_diff_hunks);
529 register_action(editor, window, Editor::collapse_all_diff_hunks);
530 register_action(editor, window, Editor::toggle_review_comments_expanded);
531 register_action(editor, window, Editor::submit_diff_review_comment_action);
532 register_action(editor, window, Editor::edit_review_comment);
533 register_action(editor, window, Editor::delete_review_comment);
534 register_action(editor, window, Editor::confirm_edit_review_comment_action);
535 register_action(editor, window, Editor::cancel_edit_review_comment_action);
536 register_action(editor, window, Editor::go_to_previous_change);
537 register_action(editor, window, Editor::go_to_next_change);
538 register_action(editor, window, Editor::go_to_prev_reference);
539 register_action(editor, window, Editor::go_to_next_reference);
540
541 register_action(editor, window, |editor, action, window, cx| {
542 if let Some(task) = editor.format(action, window, cx) {
543 task.detach_and_notify_err(window, cx);
544 } else {
545 cx.propagate();
546 }
547 });
548 register_action(editor, window, |editor, action, window, cx| {
549 if let Some(task) = editor.format_selections(action, window, cx) {
550 task.detach_and_notify_err(window, cx);
551 } else {
552 cx.propagate();
553 }
554 });
555 register_action(editor, window, |editor, action, window, cx| {
556 if let Some(task) = editor.organize_imports(action, window, cx) {
557 task.detach_and_notify_err(window, cx);
558 } else {
559 cx.propagate();
560 }
561 });
562 register_action(editor, window, Editor::restart_language_server);
563 register_action(editor, window, Editor::stop_language_server);
564 register_action(editor, window, Editor::show_character_palette);
565 register_action(editor, window, |editor, action, window, cx| {
566 if let Some(task) = editor.confirm_completion(action, window, cx) {
567 task.detach_and_notify_err(window, cx);
568 } else {
569 cx.propagate();
570 }
571 });
572 register_action(editor, window, |editor, action, window, cx| {
573 if let Some(task) = editor.confirm_completion_replace(action, window, cx) {
574 task.detach_and_notify_err(window, cx);
575 } else {
576 cx.propagate();
577 }
578 });
579 register_action(editor, window, |editor, action, window, cx| {
580 if let Some(task) = editor.confirm_completion_insert(action, window, cx) {
581 task.detach_and_notify_err(window, cx);
582 } else {
583 cx.propagate();
584 }
585 });
586 register_action(editor, window, |editor, action, window, cx| {
587 if let Some(task) = editor.compose_completion(action, window, cx) {
588 task.detach_and_notify_err(window, cx);
589 } else {
590 cx.propagate();
591 }
592 });
593 register_action(editor, window, |editor, action, window, cx| {
594 if let Some(task) = editor.confirm_code_action(action, window, cx) {
595 task.detach_and_notify_err(window, cx);
596 } else {
597 cx.propagate();
598 }
599 });
600 register_action(editor, window, |editor, action, window, cx| {
601 if let Some(task) = editor.rename(action, window, cx) {
602 task.detach_and_notify_err(window, cx);
603 } else {
604 cx.propagate();
605 }
606 });
607 register_action(editor, window, |editor, action, window, cx| {
608 if let Some(task) = editor.confirm_rename(action, window, cx) {
609 task.detach_and_notify_err(window, cx);
610 } else {
611 cx.propagate();
612 }
613 });
614 register_action(editor, window, |editor, action, window, cx| {
615 if let Some(task) = editor.find_all_references(action, window, cx) {
616 task.detach_and_log_err(cx);
617 } else {
618 cx.propagate();
619 }
620 });
621 register_action(editor, window, Editor::show_signature_help);
622 register_action(editor, window, Editor::signature_help_prev);
623 register_action(editor, window, Editor::signature_help_next);
624 register_action(editor, window, Editor::show_edit_prediction);
625 register_action(editor, window, Editor::context_menu_first);
626 register_action(editor, window, Editor::context_menu_prev);
627 register_action(editor, window, Editor::context_menu_next);
628 register_action(editor, window, Editor::context_menu_last);
629 register_action(editor, window, Editor::display_cursor_names);
630 register_action(editor, window, Editor::unique_lines_case_insensitive);
631 register_action(editor, window, Editor::unique_lines_case_sensitive);
632 register_action(editor, window, Editor::accept_next_word_edit_prediction);
633 register_action(editor, window, Editor::accept_next_line_edit_prediction);
634 register_action(editor, window, Editor::accept_edit_prediction);
635 register_action(editor, window, Editor::restore_file);
636 register_action(editor, window, Editor::git_restore);
637 register_action(editor, window, Editor::apply_all_diff_hunks);
638 register_action(editor, window, Editor::apply_selected_diff_hunks);
639 register_action(editor, window, Editor::open_active_item_in_terminal);
640 register_action(editor, window, Editor::reload_file);
641 register_action(editor, window, Editor::spawn_nearest_task);
642 register_action(editor, window, Editor::insert_uuid_v4);
643 register_action(editor, window, Editor::insert_uuid_v7);
644 register_action(editor, window, Editor::open_selections_in_multibuffer);
645 register_action(editor, window, Editor::toggle_breakpoint);
646 register_action(editor, window, Editor::edit_log_breakpoint);
647 register_action(editor, window, Editor::enable_breakpoint);
648 register_action(editor, window, Editor::disable_breakpoint);
649 register_action(editor, window, Editor::toggle_read_only);
650 if editor.read(cx).enable_wrap_selections_in_tag(cx) {
651 register_action(editor, window, Editor::wrap_selections_in_tag);
652 }
653 }
654
655 fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
656 let position_map = layout.position_map.clone();
657 window.on_key_event({
658 let editor = self.editor.clone();
659 move |event: &ModifiersChangedEvent, phase, window, cx| {
660 if phase != DispatchPhase::Bubble {
661 return;
662 }
663 editor.update(cx, |editor, cx| {
664 let inlay_hint_settings = inlay_hint_settings(
665 editor.selections.newest_anchor().head(),
666 &editor.buffer.read(cx).snapshot(cx),
667 cx,
668 );
669
670 if let Some(inlay_modifiers) = inlay_hint_settings
671 .toggle_on_modifiers_press
672 .as_ref()
673 .filter(|modifiers| modifiers.modified())
674 {
675 editor.refresh_inlay_hints(
676 InlayHintRefreshReason::ModifiersChanged(
677 inlay_modifiers == &event.modifiers,
678 ),
679 cx,
680 );
681 }
682
683 if editor.hover_state.focused(window, cx) {
684 return;
685 }
686
687 editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
688 })
689 }
690 });
691 }
692
693 fn mouse_left_down(
694 editor: &mut Editor,
695 event: &MouseDownEvent,
696 position_map: &PositionMap,
697 line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
698 window: &mut Window,
699 cx: &mut Context<Editor>,
700 ) {
701 if window.default_prevented() {
702 return;
703 }
704
705 let text_hitbox = &position_map.text_hitbox;
706 let gutter_hitbox = &position_map.gutter_hitbox;
707 let point_for_position = position_map.point_for_position(event.position);
708 let mut click_count = event.click_count;
709 let mut modifiers = event.modifiers;
710
711 if let Some(hovered_hunk) =
712 position_map
713 .display_hunks
714 .iter()
715 .find_map(|(hunk, hunk_hitbox)| match hunk {
716 DisplayDiffHunk::Folded { .. } => None,
717 DisplayDiffHunk::Unfolded {
718 multi_buffer_range, ..
719 } => hunk_hitbox
720 .as_ref()
721 .is_some_and(|hitbox| hitbox.is_hovered(window))
722 .then(|| multi_buffer_range.clone()),
723 })
724 {
725 editor.toggle_single_diff_hunk(hovered_hunk, cx);
726 cx.notify();
727 return;
728 } else if gutter_hitbox.is_hovered(window) {
729 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
730 } else if !text_hitbox.is_hovered(window) {
731 return;
732 }
733
734 if EditorSettings::get_global(cx)
735 .drag_and_drop_selection
736 .enabled
737 && click_count == 1
738 && !modifiers.shift
739 {
740 let newest_anchor = editor.selections.newest_anchor();
741 let snapshot = editor.snapshot(window, cx);
742 let selection = newest_anchor.map(|anchor| anchor.to_display_point(&snapshot));
743 if point_for_position.intersects_selection(&selection) {
744 editor.selection_drag_state = SelectionDragState::ReadyToDrag {
745 selection: newest_anchor.clone(),
746 click_position: event.position,
747 mouse_down_time: Instant::now(),
748 };
749 cx.stop_propagation();
750 return;
751 }
752 }
753
754 let is_singleton = editor.buffer().read(cx).is_singleton();
755
756 if click_count == 2 && !is_singleton {
757 match EditorSettings::get_global(cx).double_click_in_multibuffer {
758 DoubleClickInMultibuffer::Select => {
759 // do nothing special on double click, all selection logic is below
760 }
761 DoubleClickInMultibuffer::Open => {
762 if modifiers.alt {
763 // if double click is made with alt, pretend it's a regular double click without opening and alt,
764 // and run the selection logic.
765 modifiers.alt = false;
766 } else {
767 let scroll_position_row = position_map.scroll_position.y;
768 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
769 / position_map.line_height)
770 as f64
771 + position_map.scroll_position.y)
772 as u32;
773 let multi_buffer_row = position_map
774 .snapshot
775 .display_point_to_point(
776 DisplayPoint::new(DisplayRow(display_row), 0),
777 Bias::Right,
778 )
779 .row;
780 let line_offset_from_top = display_row - scroll_position_row as u32;
781 // if double click is made without alt, open the corresponding excerp
782 editor.open_excerpts_common(
783 Some(JumpData::MultiBufferRow {
784 row: MultiBufferRow(multi_buffer_row),
785 line_offset_from_top,
786 }),
787 false,
788 window,
789 cx,
790 );
791 return;
792 }
793 }
794 }
795 }
796
797 if !is_singleton {
798 let display_row = (ScrollPixelOffset::from(
799 (event.position - gutter_hitbox.bounds.origin).y / position_map.line_height,
800 ) + position_map.scroll_position.y) as u32;
801 let multi_buffer_row = position_map
802 .snapshot
803 .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
804 .row;
805 if line_numbers
806 .get(&MultiBufferRow(multi_buffer_row))
807 .is_some_and(|line_layout| {
808 line_layout.segments.iter().any(|segment| {
809 segment
810 .hitbox
811 .as_ref()
812 .is_some_and(|hitbox| hitbox.contains(&event.position))
813 })
814 })
815 {
816 let line_offset_from_top = display_row - position_map.scroll_position.y as u32;
817
818 editor.open_excerpts_common(
819 Some(JumpData::MultiBufferRow {
820 row: MultiBufferRow(multi_buffer_row),
821 line_offset_from_top,
822 }),
823 modifiers.alt,
824 window,
825 cx,
826 );
827 cx.stop_propagation();
828 return;
829 }
830 }
831
832 let position = point_for_position.previous_valid;
833 if let Some(mode) = Editor::columnar_selection_mode(&modifiers, cx) {
834 editor.select(
835 SelectPhase::BeginColumnar {
836 position,
837 reset: match mode {
838 ColumnarMode::FromMouse => true,
839 ColumnarMode::FromSelection => false,
840 },
841 mode,
842 goal_column: point_for_position.exact_unclipped.column(),
843 },
844 window,
845 cx,
846 );
847 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
848 {
849 editor.select(
850 SelectPhase::Extend {
851 position,
852 click_count,
853 },
854 window,
855 cx,
856 );
857 } else {
858 editor.select(
859 SelectPhase::Begin {
860 position,
861 add: Editor::is_alt_pressed(&modifiers, cx),
862 click_count,
863 },
864 window,
865 cx,
866 );
867 }
868 cx.stop_propagation();
869 }
870
871 fn mouse_right_down(
872 editor: &mut Editor,
873 event: &MouseDownEvent,
874 position_map: &PositionMap,
875 window: &mut Window,
876 cx: &mut Context<Editor>,
877 ) {
878 if position_map.gutter_hitbox.is_hovered(window) {
879 let gutter_right_padding = editor.gutter_dimensions.right_padding;
880 let hitbox = &position_map.gutter_hitbox;
881
882 if event.position.x <= hitbox.bounds.right() - gutter_right_padding {
883 let point_for_position = position_map.point_for_position(event.position);
884 editor.set_breakpoint_context_menu(
885 point_for_position.previous_valid.row(),
886 None,
887 event.position,
888 window,
889 cx,
890 );
891 }
892 return;
893 }
894
895 if !position_map.text_hitbox.is_hovered(window) {
896 return;
897 }
898
899 let point_for_position = position_map.point_for_position(event.position);
900 mouse_context_menu::deploy_context_menu(
901 editor,
902 Some(event.position),
903 point_for_position.previous_valid,
904 window,
905 cx,
906 );
907 cx.stop_propagation();
908 }
909
910 fn mouse_middle_down(
911 editor: &mut Editor,
912 event: &MouseDownEvent,
913 position_map: &PositionMap,
914 window: &mut Window,
915 cx: &mut Context<Editor>,
916 ) {
917 if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
918 return;
919 }
920
921 let point_for_position = position_map.point_for_position(event.position);
922 let position = point_for_position.previous_valid;
923
924 editor.select(
925 SelectPhase::BeginColumnar {
926 position,
927 reset: true,
928 mode: ColumnarMode::FromMouse,
929 goal_column: point_for_position.exact_unclipped.column(),
930 },
931 window,
932 cx,
933 );
934 }
935
936 fn mouse_up(
937 editor: &mut Editor,
938 event: &MouseUpEvent,
939 position_map: &PositionMap,
940 window: &mut Window,
941 cx: &mut Context<Editor>,
942 ) {
943 // Handle diff review drag completion
944 if editor.diff_review_drag_state.is_some() {
945 editor.end_diff_review_drag(window, cx);
946 cx.stop_propagation();
947 return;
948 }
949
950 let text_hitbox = &position_map.text_hitbox;
951 let end_selection = editor.has_pending_selection();
952 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
953 let point_for_position = position_map.point_for_position(event.position);
954
955 match editor.selection_drag_state {
956 SelectionDragState::ReadyToDrag {
957 selection: _,
958 ref click_position,
959 mouse_down_time: _,
960 } => {
961 if event.position == *click_position {
962 editor.select(
963 SelectPhase::Begin {
964 position: point_for_position.previous_valid,
965 add: false,
966 click_count: 1, // ready to drag state only occurs on click count 1
967 },
968 window,
969 cx,
970 );
971 editor.selection_drag_state = SelectionDragState::None;
972 cx.stop_propagation();
973 return;
974 } else {
975 debug_panic!("drag state can never be in ready state after drag")
976 }
977 }
978 SelectionDragState::Dragging { ref selection, .. } => {
979 let snapshot = editor.snapshot(window, cx);
980 let selection_display = selection.map(|anchor| anchor.to_display_point(&snapshot));
981 if !point_for_position.intersects_selection(&selection_display)
982 && text_hitbox.is_hovered(window)
983 {
984 let is_cut = !(cfg!(target_os = "macos") && event.modifiers.alt
985 || cfg!(not(target_os = "macos")) && event.modifiers.control);
986 editor.move_selection_on_drop(
987 &selection.clone(),
988 point_for_position.previous_valid,
989 is_cut,
990 window,
991 cx,
992 );
993 }
994 editor.selection_drag_state = SelectionDragState::None;
995 cx.stop_propagation();
996 cx.notify();
997 return;
998 }
999 _ => {}
1000 }
1001
1002 if end_selection {
1003 editor.select(SelectPhase::End, window, cx);
1004 }
1005
1006 if end_selection && pending_nonempty_selections {
1007 cx.stop_propagation();
1008 } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
1009 && event.button == MouseButton::Middle
1010 {
1011 #[allow(
1012 clippy::collapsible_if,
1013 clippy::needless_return,
1014 reason = "The cfg-block below makes this a false positive"
1015 )]
1016 if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
1017 return;
1018 }
1019
1020 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1021 if EditorSettings::get_global(cx).middle_click_paste {
1022 if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
1023 let point_for_position = position_map.point_for_position(event.position);
1024 let position = point_for_position.previous_valid;
1025
1026 editor.select(
1027 SelectPhase::Begin {
1028 position,
1029 add: false,
1030 click_count: 1,
1031 },
1032 window,
1033 cx,
1034 );
1035 editor.insert(&text, window, cx);
1036 }
1037 cx.stop_propagation()
1038 }
1039 }
1040 }
1041
1042 fn click(
1043 editor: &mut Editor,
1044 event: &ClickEvent,
1045 position_map: &PositionMap,
1046 window: &mut Window,
1047 cx: &mut Context<Editor>,
1048 ) {
1049 let text_hitbox = &position_map.text_hitbox;
1050 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
1051
1052 let hovered_link_modifier = Editor::is_cmd_or_ctrl_pressed(&event.modifiers(), cx);
1053 let mouse_down_hovered_link_modifier = if let ClickEvent::Mouse(mouse_event) = event {
1054 Editor::is_cmd_or_ctrl_pressed(&mouse_event.down.modifiers, cx)
1055 } else {
1056 true
1057 };
1058
1059 if let Some(mouse_position) = event.mouse_position()
1060 && !pending_nonempty_selections
1061 && hovered_link_modifier
1062 && mouse_down_hovered_link_modifier
1063 && text_hitbox.is_hovered(window)
1064 && !matches!(
1065 editor.selection_drag_state,
1066 SelectionDragState::Dragging { .. }
1067 )
1068 {
1069 let point = position_map.point_for_position(mouse_position);
1070 editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
1071 editor.selection_drag_state = SelectionDragState::None;
1072
1073 cx.stop_propagation();
1074 }
1075 }
1076
1077 fn pressure_click(
1078 editor: &mut Editor,
1079 event: &MousePressureEvent,
1080 position_map: &PositionMap,
1081 window: &mut Window,
1082 cx: &mut Context<Editor>,
1083 ) {
1084 let text_hitbox = &position_map.text_hitbox;
1085 let force_click_possible =
1086 matches!(editor.prev_pressure_stage, Some(PressureStage::Normal))
1087 && event.stage == PressureStage::Force;
1088
1089 editor.prev_pressure_stage = Some(event.stage);
1090
1091 if force_click_possible && text_hitbox.is_hovered(window) {
1092 let point = position_map.point_for_position(event.position);
1093 editor.handle_click_hovered_link(point, event.modifiers, window, cx);
1094 editor.selection_drag_state = SelectionDragState::None;
1095 cx.stop_propagation();
1096 }
1097 }
1098
1099 fn mouse_dragged(
1100 editor: &mut Editor,
1101 event: &MouseMoveEvent,
1102 position_map: &PositionMap,
1103 window: &mut Window,
1104 cx: &mut Context<Editor>,
1105 ) {
1106 if !editor.has_pending_selection()
1107 && matches!(editor.selection_drag_state, SelectionDragState::None)
1108 {
1109 return;
1110 }
1111
1112 let point_for_position = position_map.point_for_position(event.position);
1113 let text_hitbox = &position_map.text_hitbox;
1114
1115 let scroll_delta = {
1116 let text_bounds = text_hitbox.bounds;
1117 let mut scroll_delta = gpui::Point::<f32>::default();
1118 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
1119 let top = text_bounds.origin.y + vertical_margin;
1120 let bottom = text_bounds.bottom_left().y - vertical_margin;
1121 if event.position.y < top {
1122 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
1123 }
1124 if event.position.y > bottom {
1125 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
1126 }
1127
1128 // We need horizontal width of text
1129 let style = editor.style.clone().unwrap_or_default();
1130 let font_id = window.text_system().resolve_font(&style.text.font());
1131 let font_size = style.text.font_size.to_pixels(window.rem_size());
1132 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
1133
1134 let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
1135
1136 let scroll_space: Pixels = scroll_margin_x * em_width;
1137
1138 let left = text_bounds.origin.x + scroll_space;
1139 let right = text_bounds.top_right().x - scroll_space;
1140
1141 if event.position.x < left {
1142 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
1143 }
1144 if event.position.x > right {
1145 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
1146 }
1147 scroll_delta
1148 };
1149
1150 if !editor.has_pending_selection() {
1151 let drop_anchor = position_map
1152 .snapshot
1153 .display_point_to_anchor(point_for_position.previous_valid, Bias::Left);
1154 match editor.selection_drag_state {
1155 SelectionDragState::Dragging {
1156 ref mut drop_cursor,
1157 ref mut hide_drop_cursor,
1158 ..
1159 } => {
1160 drop_cursor.start = drop_anchor;
1161 drop_cursor.end = drop_anchor;
1162 *hide_drop_cursor = !text_hitbox.is_hovered(window);
1163 editor.apply_scroll_delta(scroll_delta, window, cx);
1164 cx.notify();
1165 }
1166 SelectionDragState::ReadyToDrag {
1167 ref selection,
1168 ref click_position,
1169 ref mouse_down_time,
1170 } => {
1171 let drag_and_drop_delay = Duration::from_millis(
1172 EditorSettings::get_global(cx)
1173 .drag_and_drop_selection
1174 .delay
1175 .0,
1176 );
1177 if mouse_down_time.elapsed() >= drag_and_drop_delay {
1178 let drop_cursor = Selection {
1179 id: post_inc(&mut editor.selections.next_selection_id()),
1180 start: drop_anchor,
1181 end: drop_anchor,
1182 reversed: false,
1183 goal: SelectionGoal::None,
1184 };
1185 editor.selection_drag_state = SelectionDragState::Dragging {
1186 selection: selection.clone(),
1187 drop_cursor,
1188 hide_drop_cursor: false,
1189 };
1190 editor.apply_scroll_delta(scroll_delta, window, cx);
1191 cx.notify();
1192 } else {
1193 let click_point = position_map.point_for_position(*click_position);
1194 editor.selection_drag_state = SelectionDragState::None;
1195 editor.select(
1196 SelectPhase::Begin {
1197 position: click_point.previous_valid,
1198 add: false,
1199 click_count: 1,
1200 },
1201 window,
1202 cx,
1203 );
1204 editor.select(
1205 SelectPhase::Update {
1206 position: point_for_position.previous_valid,
1207 goal_column: point_for_position.exact_unclipped.column(),
1208 scroll_delta,
1209 },
1210 window,
1211 cx,
1212 );
1213 }
1214 }
1215 _ => {}
1216 }
1217 } else {
1218 editor.select(
1219 SelectPhase::Update {
1220 position: point_for_position.previous_valid,
1221 goal_column: point_for_position.exact_unclipped.column(),
1222 scroll_delta,
1223 },
1224 window,
1225 cx,
1226 );
1227 }
1228 }
1229
1230 pub(crate) fn mouse_moved(
1231 editor: &mut Editor,
1232 event: &MouseMoveEvent,
1233 position_map: &PositionMap,
1234 split_side: Option<SplitSide>,
1235 window: &mut Window,
1236 cx: &mut Context<Editor>,
1237 ) {
1238 let text_hitbox = &position_map.text_hitbox;
1239 let gutter_hitbox = &position_map.gutter_hitbox;
1240 let modifiers = event.modifiers;
1241 let text_hovered = text_hitbox.is_hovered(window);
1242 let gutter_hovered = gutter_hitbox.bounds.contains(&event.position);
1243 editor.set_gutter_hovered(gutter_hovered, cx);
1244 editor.show_mouse_cursor(cx);
1245
1246 let point_for_position = position_map.point_for_position(event.position);
1247 let valid_point = point_for_position.previous_valid;
1248
1249 // Update diff review drag state if we're dragging
1250 if editor.diff_review_drag_state.is_some() {
1251 editor.update_diff_review_drag(valid_point.row(), window, cx);
1252 }
1253
1254 let hovered_diff_control = position_map
1255 .diff_hunk_control_bounds
1256 .iter()
1257 .find(|(_, bounds)| bounds.contains(&event.position))
1258 .map(|(row, _)| *row);
1259
1260 let hovered_diff_hunk_row = if let Some(control_row) = hovered_diff_control {
1261 Some(control_row)
1262 } else if text_hovered {
1263 let current_row = valid_point.row();
1264 position_map.display_hunks.iter().find_map(|(hunk, _)| {
1265 if let DisplayDiffHunk::Unfolded {
1266 display_row_range, ..
1267 } = hunk
1268 {
1269 if display_row_range.contains(¤t_row) {
1270 Some(display_row_range.start)
1271 } else {
1272 None
1273 }
1274 } else {
1275 None
1276 }
1277 })
1278 } else {
1279 None
1280 };
1281
1282 if hovered_diff_hunk_row != editor.hovered_diff_hunk_row {
1283 editor.hovered_diff_hunk_row = hovered_diff_hunk_row;
1284 cx.notify();
1285 }
1286
1287 if let Some((bounds, buffer_id, blame_entry)) = &position_map.inline_blame_bounds {
1288 let mouse_over_inline_blame = bounds.contains(&event.position);
1289 let mouse_over_popover = editor
1290 .inline_blame_popover
1291 .as_ref()
1292 .and_then(|state| state.popover_bounds)
1293 .is_some_and(|bounds| bounds.contains(&event.position));
1294 let keyboard_grace = editor
1295 .inline_blame_popover
1296 .as_ref()
1297 .is_some_and(|state| state.keyboard_grace);
1298
1299 if mouse_over_inline_blame || mouse_over_popover {
1300 editor.show_blame_popover(*buffer_id, blame_entry, event.position, false, cx);
1301 } else if !keyboard_grace {
1302 editor.hide_blame_popover(false, cx);
1303 }
1304 } else {
1305 let keyboard_grace = editor
1306 .inline_blame_popover
1307 .as_ref()
1308 .is_some_and(|state| state.keyboard_grace);
1309 if !keyboard_grace {
1310 editor.hide_blame_popover(false, cx);
1311 }
1312 }
1313
1314 // Handle diff review indicator when gutter is hovered in diff mode with AI enabled
1315 let show_diff_review = editor.show_diff_review_button()
1316 && cx.has_flag::<DiffReviewFeatureFlag>()
1317 && !DisableAiSettings::get_global(cx).disable_ai;
1318
1319 let diff_review_indicator = if gutter_hovered && show_diff_review {
1320 let is_visible = editor
1321 .gutter_diff_review_indicator
1322 .0
1323 .is_some_and(|indicator| indicator.is_active);
1324
1325 if !is_visible {
1326 editor
1327 .gutter_diff_review_indicator
1328 .1
1329 .get_or_insert_with(|| {
1330 cx.spawn(async move |this, cx| {
1331 cx.background_executor()
1332 .timer(Duration::from_millis(200))
1333 .await;
1334
1335 this.update(cx, |this, cx| {
1336 if let Some(indicator) =
1337 this.gutter_diff_review_indicator.0.as_mut()
1338 {
1339 indicator.is_active = true;
1340 cx.notify();
1341 }
1342 })
1343 .ok();
1344 })
1345 });
1346 }
1347
1348 let anchor = position_map
1349 .snapshot
1350 .display_point_to_anchor(valid_point, Bias::Left);
1351 Some(PhantomDiffReviewIndicator {
1352 start: anchor,
1353 end: anchor,
1354 is_active: is_visible,
1355 })
1356 } else {
1357 editor.gutter_diff_review_indicator.1 = None;
1358 None
1359 };
1360
1361 if diff_review_indicator != editor.gutter_diff_review_indicator.0 {
1362 editor.gutter_diff_review_indicator.0 = diff_review_indicator;
1363 cx.notify();
1364 }
1365
1366 // Don't show breakpoint indicator when diff review indicator is active on this row
1367 let is_on_diff_review_button_row = diff_review_indicator.is_some_and(|indicator| {
1368 let start_row = indicator
1369 .start
1370 .to_display_point(&position_map.snapshot.display_snapshot)
1371 .row();
1372 indicator.is_active && start_row == valid_point.row()
1373 });
1374
1375 let breakpoint_indicator = if gutter_hovered
1376 && !is_on_diff_review_button_row
1377 && split_side != Some(SplitSide::Left)
1378 {
1379 let buffer_anchor = position_map
1380 .snapshot
1381 .display_point_to_anchor(valid_point, Bias::Left);
1382
1383 if let Some((buffer_snapshot, file)) = position_map
1384 .snapshot
1385 .buffer_snapshot()
1386 .buffer_for_excerpt(buffer_anchor.excerpt_id)
1387 .and_then(|buffer| buffer.file().map(|file| (buffer, file)))
1388 {
1389 let as_point = text::ToPoint::to_point(&buffer_anchor.text_anchor, buffer_snapshot);
1390
1391 let is_visible = editor
1392 .gutter_breakpoint_indicator
1393 .0
1394 .is_some_and(|indicator| indicator.is_active);
1395
1396 let has_existing_breakpoint =
1397 editor.breakpoint_store.as_ref().is_some_and(|store| {
1398 let Some(project) = &editor.project else {
1399 return false;
1400 };
1401 let Some(abs_path) = project.read(cx).absolute_path(
1402 &ProjectPath {
1403 path: file.path().clone(),
1404 worktree_id: file.worktree_id(cx),
1405 },
1406 cx,
1407 ) else {
1408 return false;
1409 };
1410 store
1411 .read(cx)
1412 .breakpoint_at_row(&abs_path, as_point.row, cx)
1413 .is_some()
1414 });
1415
1416 if !is_visible {
1417 editor.gutter_breakpoint_indicator.1.get_or_insert_with(|| {
1418 cx.spawn(async move |this, cx| {
1419 cx.background_executor()
1420 .timer(Duration::from_millis(200))
1421 .await;
1422
1423 this.update(cx, |this, cx| {
1424 if let Some(indicator) = this.gutter_breakpoint_indicator.0.as_mut()
1425 {
1426 indicator.is_active = true;
1427 cx.notify();
1428 }
1429 })
1430 .ok();
1431 })
1432 });
1433 }
1434
1435 Some(PhantomBreakpointIndicator {
1436 display_row: valid_point.row(),
1437 is_active: is_visible,
1438 collides_with_existing_breakpoint: has_existing_breakpoint,
1439 })
1440 } else {
1441 editor.gutter_breakpoint_indicator.1 = None;
1442 None
1443 }
1444 } else {
1445 editor.gutter_breakpoint_indicator.1 = None;
1446 None
1447 };
1448
1449 if &breakpoint_indicator != &editor.gutter_breakpoint_indicator.0 {
1450 editor.gutter_breakpoint_indicator.0 = breakpoint_indicator;
1451 cx.notify();
1452 }
1453
1454 // Don't trigger hover popover if mouse is hovering over context menu
1455 if text_hovered {
1456 editor.update_hovered_link(
1457 point_for_position,
1458 &position_map.snapshot,
1459 modifiers,
1460 window,
1461 cx,
1462 );
1463
1464 if let Some(point) = point_for_position.as_valid() {
1465 let anchor = position_map
1466 .snapshot
1467 .buffer_snapshot()
1468 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
1469 hover_at(editor, Some(anchor), window, cx);
1470 Self::update_visible_cursor(editor, point, position_map, window, cx);
1471 } else {
1472 editor.update_inlay_link_and_hover_points(
1473 &position_map.snapshot,
1474 point_for_position,
1475 modifiers.secondary(),
1476 modifiers.shift,
1477 window,
1478 cx,
1479 );
1480 }
1481 } else {
1482 editor.hide_hovered_link(cx);
1483 hover_at(editor, None, window, cx);
1484 }
1485 }
1486
1487 fn update_visible_cursor(
1488 editor: &mut Editor,
1489 point: DisplayPoint,
1490 position_map: &PositionMap,
1491 window: &mut Window,
1492 cx: &mut Context<Editor>,
1493 ) {
1494 let snapshot = &position_map.snapshot;
1495 let Some(hub) = editor.collaboration_hub() else {
1496 return;
1497 };
1498 let start = snapshot.display_snapshot.clip_point(
1499 DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
1500 Bias::Left,
1501 );
1502 let end = snapshot.display_snapshot.clip_point(
1503 DisplayPoint::new(
1504 point.row(),
1505 (point.column() + 1).min(snapshot.line_len(point.row())),
1506 ),
1507 Bias::Right,
1508 );
1509
1510 let range = snapshot
1511 .buffer_snapshot()
1512 .anchor_before(start.to_point(&snapshot.display_snapshot))
1513 ..snapshot
1514 .buffer_snapshot()
1515 .anchor_after(end.to_point(&snapshot.display_snapshot));
1516
1517 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
1518 return;
1519 };
1520 let key = crate::HoveredCursor {
1521 replica_id: selection.replica_id,
1522 selection_id: selection.selection.id,
1523 };
1524 editor.hovered_cursors.insert(
1525 key.clone(),
1526 cx.spawn_in(window, async move |editor, cx| {
1527 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
1528 editor
1529 .update(cx, |editor, cx| {
1530 editor.hovered_cursors.remove(&key);
1531 cx.notify();
1532 })
1533 .ok();
1534 }),
1535 );
1536 cx.notify()
1537 }
1538
1539 fn layout_selections(
1540 &self,
1541 start_anchor: Anchor,
1542 end_anchor: Anchor,
1543 local_selections: &[Selection<Point>],
1544 snapshot: &EditorSnapshot,
1545 start_row: DisplayRow,
1546 end_row: DisplayRow,
1547 window: &mut Window,
1548 cx: &mut App,
1549 ) -> (
1550 Vec<(PlayerColor, Vec<SelectionLayout>)>,
1551 BTreeMap<DisplayRow, LineHighlightSpec>,
1552 Option<DisplayPoint>,
1553 ) {
1554 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1555 let mut active_rows = BTreeMap::new();
1556 let mut newest_selection_head = None;
1557
1558 let Some(editor_with_selections) = self.editor_with_selections(cx) else {
1559 return (selections, active_rows, newest_selection_head);
1560 };
1561
1562 editor_with_selections.update(cx, |editor, cx| {
1563 if editor.show_local_selections {
1564 let mut layouts = Vec::new();
1565 let newest = editor.selections.newest(&editor.display_snapshot(cx));
1566 for selection in local_selections.iter().cloned() {
1567 let is_empty = selection.start == selection.end;
1568 let is_newest = selection == newest;
1569
1570 let layout = SelectionLayout::new(
1571 selection,
1572 editor.selections.line_mode(),
1573 editor.cursor_offset_on_selection,
1574 editor.cursor_shape,
1575 &snapshot.display_snapshot,
1576 is_newest,
1577 editor.leader_id.is_none(),
1578 None,
1579 );
1580 if is_newest {
1581 newest_selection_head = Some(layout.head);
1582 }
1583
1584 for row in cmp::max(layout.active_rows.start.0, start_row.0)
1585 ..=cmp::min(layout.active_rows.end.0, end_row.0)
1586 {
1587 let contains_non_empty_selection = active_rows
1588 .entry(DisplayRow(row))
1589 .or_insert_with(LineHighlightSpec::default);
1590 contains_non_empty_selection.selection |= !is_empty;
1591 }
1592 layouts.push(layout);
1593 }
1594
1595 let mut player = editor.current_user_player_color(cx);
1596 if !editor.is_focused(window) {
1597 const UNFOCUS_EDITOR_SELECTION_OPACITY: f32 = 0.5;
1598 player.selection = player.selection.opacity(UNFOCUS_EDITOR_SELECTION_OPACITY);
1599 }
1600 selections.push((player, layouts));
1601
1602 if let SelectionDragState::Dragging {
1603 ref selection,
1604 ref drop_cursor,
1605 ref hide_drop_cursor,
1606 } = editor.selection_drag_state
1607 && !hide_drop_cursor
1608 && (drop_cursor
1609 .start
1610 .cmp(&selection.start, &snapshot.buffer_snapshot())
1611 .eq(&Ordering::Less)
1612 || drop_cursor
1613 .end
1614 .cmp(&selection.end, &snapshot.buffer_snapshot())
1615 .eq(&Ordering::Greater))
1616 {
1617 let drag_cursor_layout = SelectionLayout::new(
1618 drop_cursor.clone(),
1619 false,
1620 editor.cursor_offset_on_selection,
1621 CursorShape::Bar,
1622 &snapshot.display_snapshot,
1623 false,
1624 false,
1625 None,
1626 );
1627 let absent_color = cx.theme().players().absent();
1628 selections.push((absent_color, vec![drag_cursor_layout]));
1629 }
1630 }
1631
1632 if let Some(collaboration_hub) = &editor.collaboration_hub {
1633 // When following someone, render the local selections in their color.
1634 if let Some(leader_id) = editor.leader_id {
1635 match leader_id {
1636 CollaboratorId::PeerId(peer_id) => {
1637 if let Some(collaborator) =
1638 collaboration_hub.collaborators(cx).get(&peer_id)
1639 && let Some(participant_index) = collaboration_hub
1640 .user_participant_indices(cx)
1641 .get(&collaborator.user_id)
1642 && let Some((local_selection_style, _)) = selections.first_mut()
1643 {
1644 *local_selection_style = cx
1645 .theme()
1646 .players()
1647 .color_for_participant(participant_index.0);
1648 }
1649 }
1650 CollaboratorId::Agent => {
1651 if let Some((local_selection_style, _)) = selections.first_mut() {
1652 *local_selection_style = cx.theme().players().agent();
1653 }
1654 }
1655 }
1656 }
1657
1658 let mut remote_selections = HashMap::default();
1659 for selection in snapshot.remote_selections_in_range(
1660 &(start_anchor..end_anchor),
1661 collaboration_hub.as_ref(),
1662 cx,
1663 ) {
1664 // Don't re-render the leader's selections, since the local selections
1665 // match theirs.
1666 if Some(selection.collaborator_id) == editor.leader_id {
1667 continue;
1668 }
1669 let key = HoveredCursor {
1670 replica_id: selection.replica_id,
1671 selection_id: selection.selection.id,
1672 };
1673
1674 let is_shown =
1675 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
1676
1677 remote_selections
1678 .entry(selection.replica_id)
1679 .or_insert((selection.color, Vec::new()))
1680 .1
1681 .push(SelectionLayout::new(
1682 selection.selection,
1683 selection.line_mode,
1684 editor.cursor_offset_on_selection,
1685 selection.cursor_shape,
1686 &snapshot.display_snapshot,
1687 false,
1688 false,
1689 if is_shown { selection.user_name } else { None },
1690 ));
1691 }
1692
1693 selections.extend(remote_selections.into_values());
1694 } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
1695 let cursor_offset_on_selection = editor.cursor_offset_on_selection;
1696
1697 let layouts = snapshot
1698 .buffer_snapshot()
1699 .selections_in_range(&(start_anchor..end_anchor), true)
1700 .map(move |(_, line_mode, cursor_shape, selection)| {
1701 SelectionLayout::new(
1702 selection,
1703 line_mode,
1704 cursor_offset_on_selection,
1705 cursor_shape,
1706 &snapshot.display_snapshot,
1707 false,
1708 false,
1709 None,
1710 )
1711 })
1712 .collect::<Vec<_>>();
1713 let player = editor.current_user_player_color(cx);
1714 selections.push((player, layouts));
1715 }
1716 });
1717
1718 #[cfg(debug_assertions)]
1719 Self::layout_debug_ranges(
1720 &mut selections,
1721 start_anchor..end_anchor,
1722 &snapshot.display_snapshot,
1723 cx,
1724 );
1725
1726 (selections, active_rows, newest_selection_head)
1727 }
1728
1729 fn collect_cursors(
1730 &self,
1731 snapshot: &EditorSnapshot,
1732 cx: &mut App,
1733 ) -> Vec<(DisplayPoint, Hsla)> {
1734 let editor = self.editor.read(cx);
1735 let mut cursors = Vec::new();
1736 let mut skip_local = false;
1737 let mut add_cursor = |anchor: Anchor, color| {
1738 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
1739 };
1740 // Remote cursors
1741 if let Some(collaboration_hub) = &editor.collaboration_hub {
1742 for remote_selection in snapshot.remote_selections_in_range(
1743 &(Anchor::min()..Anchor::max()),
1744 collaboration_hub.deref(),
1745 cx,
1746 ) {
1747 add_cursor(
1748 remote_selection.selection.head(),
1749 remote_selection.color.cursor,
1750 );
1751 if Some(remote_selection.collaborator_id) == editor.leader_id {
1752 skip_local = true;
1753 }
1754 }
1755 }
1756 // Local cursors
1757 if !skip_local {
1758 let color = cx.theme().players().local().cursor;
1759 editor
1760 .selections
1761 .disjoint_anchors()
1762 .iter()
1763 .for_each(|selection| {
1764 add_cursor(selection.head(), color);
1765 });
1766 if let Some(ref selection) = editor.selections.pending_anchor() {
1767 add_cursor(selection.head(), color);
1768 }
1769 }
1770 cursors
1771 }
1772
1773 fn layout_visible_cursors(
1774 &self,
1775 snapshot: &EditorSnapshot,
1776 selections: &[(PlayerColor, Vec<SelectionLayout>)],
1777 row_block_types: &HashMap<DisplayRow, bool>,
1778 visible_display_row_range: Range<DisplayRow>,
1779 line_layouts: &[LineWithInvisibles],
1780 text_hitbox: &Hitbox,
1781 content_origin: gpui::Point<Pixels>,
1782 scroll_position: gpui::Point<ScrollOffset>,
1783 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
1784 line_height: Pixels,
1785 em_width: Pixels,
1786 em_advance: Pixels,
1787 autoscroll_containing_element: bool,
1788 redacted_ranges: &[Range<DisplayPoint>],
1789 window: &mut Window,
1790 cx: &mut App,
1791 ) -> Vec<CursorLayout> {
1792 let mut autoscroll_bounds = None;
1793 let cursor_layouts = self.editor.update(cx, |editor, cx| {
1794 let mut cursors = Vec::new();
1795
1796 let show_local_cursors = editor.show_local_cursors(window, cx);
1797
1798 for (player_color, selections) in selections {
1799 for selection in selections {
1800 let cursor_position = selection.head;
1801
1802 let in_range = visible_display_row_range.contains(&cursor_position.row());
1803 if (selection.is_local && !show_local_cursors)
1804 || !in_range
1805 || row_block_types.get(&cursor_position.row()) == Some(&true)
1806 {
1807 continue;
1808 }
1809
1810 let cursor_row_layout = &line_layouts
1811 [cursor_position.row().minus(visible_display_row_range.start) as usize];
1812 let cursor_column = cursor_position.column() as usize;
1813
1814 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column)
1815 + cursor_row_layout
1816 .alignment_offset(self.style.text.text_align, text_hitbox.size.width);
1817 let cursor_next_x = cursor_row_layout.x_for_index(cursor_column + 1)
1818 + cursor_row_layout
1819 .alignment_offset(self.style.text.text_align, text_hitbox.size.width);
1820 let mut cell_width = cursor_next_x - cursor_character_x;
1821 if cell_width == Pixels::ZERO {
1822 cell_width = em_advance;
1823 }
1824
1825 let mut block_width = cell_width;
1826 let mut block_text = None;
1827
1828 let is_cursor_in_redacted_range = redacted_ranges
1829 .iter()
1830 .any(|range| range.start <= cursor_position && cursor_position < range.end);
1831
1832 if selection.cursor_shape == CursorShape::Block && !is_cursor_in_redacted_range
1833 {
1834 if let Some(text) = snapshot.grapheme_at(cursor_position).or_else(|| {
1835 if snapshot.is_empty() {
1836 snapshot.placeholder_text().and_then(|s| {
1837 s.graphemes(true).next().map(|s| s.to_string().into())
1838 })
1839 } else {
1840 None
1841 }
1842 }) {
1843 let is_ascii_whitespace_only =
1844 text.as_ref().chars().all(|c| c.is_ascii_whitespace());
1845 let len = text.len();
1846
1847 let mut font = cursor_row_layout
1848 .font_id_for_index(cursor_column)
1849 .and_then(|cursor_font_id| {
1850 window.text_system().get_font_for_id(cursor_font_id)
1851 })
1852 .unwrap_or(self.style.text.font());
1853 font.features = self.style.text.font_features.clone();
1854
1855 // Invert the text color for the block cursor. Ensure that the text
1856 // color is opaque enough to be visible against the background color.
1857 //
1858 // 0.75 is an arbitrary threshold to determine if the background color is
1859 // opaque enough to use as a text color.
1860 //
1861 // TODO: In the future we should ensure themes have a `text_inverse` color.
1862 let color = if cx.theme().colors().editor_background.a < 0.75 {
1863 match cx.theme().appearance {
1864 Appearance::Dark => Hsla::black(),
1865 Appearance::Light => Hsla::white(),
1866 }
1867 } else {
1868 cx.theme().colors().editor_background
1869 };
1870
1871 let shaped = window.text_system().shape_line(
1872 text,
1873 cursor_row_layout.font_size,
1874 &[TextRun {
1875 len,
1876 font,
1877 color,
1878 ..Default::default()
1879 }],
1880 None,
1881 );
1882 if !is_ascii_whitespace_only {
1883 block_width = block_width.max(shaped.width);
1884 }
1885 block_text = Some(shaped);
1886 }
1887 }
1888
1889 let x = cursor_character_x - scroll_pixel_position.x.into();
1890 let y = ((cursor_position.row().as_f64() - scroll_position.y)
1891 * ScrollPixelOffset::from(line_height))
1892 .into();
1893 if selection.is_newest {
1894 editor.pixel_position_of_newest_cursor = Some(point(
1895 text_hitbox.origin.x + x + block_width / 2.,
1896 text_hitbox.origin.y + y + line_height / 2.,
1897 ));
1898
1899 if autoscroll_containing_element {
1900 let top = text_hitbox.origin.y
1901 + ((cursor_position.row().as_f64() - scroll_position.y - 3.)
1902 .max(0.)
1903 * ScrollPixelOffset::from(line_height))
1904 .into();
1905 let left = text_hitbox.origin.x
1906 + ((cursor_position.column() as ScrollOffset
1907 - scroll_position.x
1908 - 3.)
1909 .max(0.)
1910 * ScrollPixelOffset::from(em_width))
1911 .into();
1912
1913 let bottom = text_hitbox.origin.y
1914 + ((cursor_position.row().as_f64() - scroll_position.y + 4.)
1915 * ScrollPixelOffset::from(line_height))
1916 .into();
1917 let right = text_hitbox.origin.x
1918 + ((cursor_position.column() as ScrollOffset - scroll_position.x
1919 + 4.)
1920 * ScrollPixelOffset::from(em_width))
1921 .into();
1922
1923 autoscroll_bounds =
1924 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1925 }
1926 }
1927
1928 let mut cursor = CursorLayout {
1929 color: player_color.cursor,
1930 block_width,
1931 origin: point(x, y),
1932 line_height,
1933 shape: selection.cursor_shape,
1934 block_text,
1935 cursor_name: None,
1936 };
1937 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1938 string: name,
1939 color: self.style.background,
1940 is_top_row: cursor_position.row().0 == 0,
1941 });
1942 cursor.layout(content_origin, cursor_name, window, cx);
1943 cursors.push(cursor);
1944 }
1945 }
1946
1947 cursors
1948 });
1949
1950 if let Some(bounds) = autoscroll_bounds {
1951 window.request_autoscroll(bounds);
1952 }
1953
1954 cursor_layouts
1955 }
1956
1957 fn layout_scrollbars(
1958 &self,
1959 snapshot: &EditorSnapshot,
1960 scrollbar_layout_information: &ScrollbarLayoutInformation,
1961 content_offset: gpui::Point<Pixels>,
1962 scroll_position: gpui::Point<ScrollOffset>,
1963 non_visible_cursors: bool,
1964 right_margin: Pixels,
1965 editor_width: Pixels,
1966 window: &mut Window,
1967 cx: &mut App,
1968 ) -> Option<EditorScrollbars> {
1969 let show_scrollbars = self.editor.read(cx).show_scrollbars;
1970 if (!show_scrollbars.horizontal && !show_scrollbars.vertical)
1971 || self.style.scrollbar_width.is_zero()
1972 {
1973 return None;
1974 }
1975
1976 // If a drag took place after we started dragging the scrollbar,
1977 // cancel the scrollbar drag.
1978 if cx.has_active_drag() {
1979 self.editor.update(cx, |editor, cx| {
1980 editor.scroll_manager.reset_scrollbar_state(cx)
1981 });
1982 }
1983
1984 let editor_settings = EditorSettings::get_global(cx);
1985 let scrollbar_settings = editor_settings.scrollbar;
1986 let show_scrollbars = match scrollbar_settings.show {
1987 ShowScrollbar::Auto => {
1988 let editor = self.editor.read(cx);
1989 let is_singleton = editor.buffer_kind(cx) == ItemBufferKind::Singleton;
1990 // Git
1991 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot().has_diff_hunks())
1992 ||
1993 // Buffer Search Results
1994 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights(HighlightKey::BufferSearchHighlights))
1995 ||
1996 // Selected Text Occurrences
1997 (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights(HighlightKey::SelectedTextHighlight))
1998 ||
1999 // Selected Symbol Occurrences
2000 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights(HighlightKey::DocumentHighlightRead) || editor.has_background_highlights(HighlightKey::DocumentHighlightWrite)))
2001 ||
2002 // Diagnostics
2003 (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot().has_diagnostics())
2004 ||
2005 // Cursors out of sight
2006 non_visible_cursors
2007 ||
2008 // Scrollmanager
2009 editor.scroll_manager.scrollbars_visible()
2010 }
2011 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
2012 ShowScrollbar::Always => true,
2013 ShowScrollbar::Never => return None,
2014 };
2015
2016 // The horizontal scrollbar is usually slightly offset to align nicely with
2017 // indent guides. However, this offset is not needed if indent guides are
2018 // disabled for the current editor.
2019 let content_offset = self
2020 .editor
2021 .read(cx)
2022 .show_indent_guides
2023 .is_none_or(|should_show| should_show)
2024 .then_some(content_offset)
2025 .unwrap_or_default();
2026
2027 Some(EditorScrollbars::from_scrollbar_axes(
2028 ScrollbarAxes {
2029 horizontal: scrollbar_settings.axes.horizontal
2030 && self.editor.read(cx).show_scrollbars.horizontal,
2031 vertical: scrollbar_settings.axes.vertical
2032 && self.editor.read(cx).show_scrollbars.vertical,
2033 },
2034 scrollbar_layout_information,
2035 content_offset,
2036 scroll_position,
2037 self.style.scrollbar_width,
2038 right_margin,
2039 editor_width,
2040 show_scrollbars,
2041 self.editor.read(cx).scroll_manager.active_scrollbar_state(),
2042 window,
2043 ))
2044 }
2045
2046 fn layout_minimap(
2047 &self,
2048 snapshot: &EditorSnapshot,
2049 minimap_width: Pixels,
2050 scroll_position: gpui::Point<f64>,
2051 scrollbar_layout_information: &ScrollbarLayoutInformation,
2052 scrollbar_layout: Option<&EditorScrollbars>,
2053 window: &mut Window,
2054 cx: &mut App,
2055 ) -> Option<MinimapLayout> {
2056 let minimap_editor = self.editor.read(cx).minimap().cloned()?;
2057
2058 let minimap_settings = EditorSettings::get_global(cx).minimap;
2059
2060 if minimap_settings.on_active_editor() {
2061 let active_editor = self.editor.read(cx).workspace().and_then(|ws| {
2062 ws.read(cx)
2063 .active_pane()
2064 .read(cx)
2065 .active_item()
2066 .and_then(|i| i.act_as::<Editor>(cx))
2067 });
2068 if active_editor.is_some_and(|e| e != self.editor) {
2069 return None;
2070 }
2071 }
2072
2073 if !snapshot.mode.is_full()
2074 || minimap_width.is_zero()
2075 || matches!(
2076 minimap_settings.show,
2077 ShowMinimap::Auto if scrollbar_layout.is_none_or(|layout| !layout.visible)
2078 )
2079 {
2080 return None;
2081 }
2082
2083 const MINIMAP_AXIS: ScrollbarAxis = ScrollbarAxis::Vertical;
2084
2085 let ScrollbarLayoutInformation {
2086 editor_bounds,
2087 scroll_range,
2088 glyph_grid_cell,
2089 } = scrollbar_layout_information;
2090
2091 let line_height = glyph_grid_cell.height;
2092 let scroll_position = scroll_position.along(MINIMAP_AXIS);
2093
2094 let top_right_anchor = scrollbar_layout
2095 .and_then(|layout| layout.vertical.as_ref())
2096 .map(|vertical_scrollbar| vertical_scrollbar.hitbox.origin)
2097 .unwrap_or_else(|| editor_bounds.top_right());
2098
2099 let thumb_state = self
2100 .editor
2101 .read_with(cx, |editor, _| editor.scroll_manager.minimap_thumb_state());
2102
2103 let show_thumb = match minimap_settings.thumb {
2104 MinimapThumb::Always => true,
2105 MinimapThumb::Hover => thumb_state.is_some(),
2106 };
2107
2108 let minimap_bounds = Bounds::from_corner_and_size(
2109 Corner::TopRight,
2110 top_right_anchor,
2111 size(minimap_width, editor_bounds.size.height),
2112 );
2113 let minimap_line_height = self.get_minimap_line_height(
2114 minimap_editor
2115 .read(cx)
2116 .text_style_refinement
2117 .as_ref()
2118 .and_then(|refinement| refinement.font_size)
2119 .unwrap_or(MINIMAP_FONT_SIZE),
2120 window,
2121 cx,
2122 );
2123 let minimap_height = minimap_bounds.size.height;
2124
2125 let visible_editor_lines = (editor_bounds.size.height / line_height) as f64;
2126 let total_editor_lines = (scroll_range.height / line_height) as f64;
2127 let minimap_lines = (minimap_height / minimap_line_height) as f64;
2128
2129 let minimap_scroll_top = MinimapLayout::calculate_minimap_top_offset(
2130 total_editor_lines,
2131 visible_editor_lines,
2132 minimap_lines,
2133 scroll_position,
2134 );
2135
2136 let layout = ScrollbarLayout::for_minimap(
2137 window.insert_hitbox(minimap_bounds, HitboxBehavior::Normal),
2138 visible_editor_lines,
2139 total_editor_lines,
2140 minimap_line_height,
2141 scroll_position,
2142 minimap_scroll_top,
2143 show_thumb,
2144 )
2145 .with_thumb_state(thumb_state);
2146
2147 minimap_editor.update(cx, |editor, cx| {
2148 editor.set_scroll_position(point(0., minimap_scroll_top), window, cx)
2149 });
2150
2151 // Required for the drop shadow to be visible
2152 const PADDING_OFFSET: Pixels = px(4.);
2153
2154 let mut minimap = div()
2155 .size_full()
2156 .shadow_xs()
2157 .px(PADDING_OFFSET)
2158 .child(minimap_editor)
2159 .into_any_element();
2160
2161 let extended_bounds = minimap_bounds.extend(Edges {
2162 right: PADDING_OFFSET,
2163 left: PADDING_OFFSET,
2164 ..Default::default()
2165 });
2166 minimap.layout_as_root(extended_bounds.size.into(), window, cx);
2167 window.with_absolute_element_offset(extended_bounds.origin, |window| {
2168 minimap.prepaint(window, cx)
2169 });
2170
2171 Some(MinimapLayout {
2172 minimap,
2173 thumb_layout: layout,
2174 thumb_border_style: minimap_settings.thumb_border,
2175 minimap_line_height,
2176 minimap_scroll_top,
2177 max_scroll_top: total_editor_lines,
2178 })
2179 }
2180
2181 fn get_minimap_line_height(
2182 &self,
2183 font_size: AbsoluteLength,
2184 window: &mut Window,
2185 cx: &mut App,
2186 ) -> Pixels {
2187 let rem_size = self.rem_size(cx).unwrap_or(window.rem_size());
2188 let mut text_style = self.style.text.clone();
2189 text_style.font_size = font_size;
2190 text_style.line_height_in_pixels(rem_size)
2191 }
2192
2193 fn get_minimap_width(
2194 &self,
2195 minimap_settings: &Minimap,
2196 scrollbars_shown: bool,
2197 text_width: Pixels,
2198 em_width: Pixels,
2199 font_size: Pixels,
2200 rem_size: Pixels,
2201 cx: &App,
2202 ) -> Option<Pixels> {
2203 if minimap_settings.show == ShowMinimap::Auto && !scrollbars_shown {
2204 return None;
2205 }
2206
2207 let minimap_font_size = self.editor.read_with(cx, |editor, cx| {
2208 editor.minimap().map(|minimap_editor| {
2209 minimap_editor
2210 .read(cx)
2211 .text_style_refinement
2212 .as_ref()
2213 .and_then(|refinement| refinement.font_size)
2214 .unwrap_or(MINIMAP_FONT_SIZE)
2215 })
2216 })?;
2217
2218 let minimap_em_width = em_width * (minimap_font_size.to_pixels(rem_size) / font_size);
2219
2220 let minimap_width = (text_width * MinimapLayout::MINIMAP_WIDTH_PCT)
2221 .min(minimap_em_width * minimap_settings.max_width_columns.get() as f32);
2222
2223 (minimap_width >= minimap_em_width * MinimapLayout::MINIMAP_MIN_WIDTH_COLUMNS)
2224 .then_some(minimap_width)
2225 }
2226
2227 fn prepaint_crease_toggles(
2228 &self,
2229 crease_toggles: &mut [Option<AnyElement>],
2230 line_height: Pixels,
2231 gutter_dimensions: &GutterDimensions,
2232 gutter_settings: crate::editor_settings::Gutter,
2233 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
2234 gutter_hitbox: &Hitbox,
2235 window: &mut Window,
2236 cx: &mut App,
2237 ) {
2238 for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
2239 if let Some(crease_toggle) = crease_toggle {
2240 debug_assert!(gutter_settings.folds);
2241 let available_space = size(
2242 AvailableSpace::MinContent,
2243 AvailableSpace::Definite(line_height * 0.55),
2244 );
2245 let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
2246
2247 let position = point(
2248 gutter_dimensions.width - gutter_dimensions.right_padding,
2249 ix as f32 * line_height
2250 - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
2251 );
2252 let centering_offset = point(
2253 (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
2254 (line_height - crease_toggle_size.height) / 2.,
2255 );
2256 let origin = gutter_hitbox.origin + position + centering_offset;
2257 crease_toggle.prepaint_as_root(origin, available_space, window, cx);
2258 }
2259 }
2260 }
2261
2262 fn prepaint_expand_toggles(
2263 &self,
2264 expand_toggles: &mut [Option<(AnyElement, gpui::Point<Pixels>)>],
2265 window: &mut Window,
2266 cx: &mut App,
2267 ) {
2268 for (expand_toggle, origin) in expand_toggles.iter_mut().flatten() {
2269 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2270 expand_toggle.layout_as_root(available_space, window, cx);
2271 expand_toggle.prepaint_as_root(*origin, available_space, window, cx);
2272 }
2273 }
2274
2275 fn prepaint_crease_trailers(
2276 &self,
2277 trailers: Vec<Option<AnyElement>>,
2278 lines: &[LineWithInvisibles],
2279 line_height: Pixels,
2280 content_origin: gpui::Point<Pixels>,
2281 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
2282 em_width: Pixels,
2283 window: &mut Window,
2284 cx: &mut App,
2285 ) -> Vec<Option<CreaseTrailerLayout>> {
2286 trailers
2287 .into_iter()
2288 .enumerate()
2289 .map(|(ix, element)| {
2290 let mut element = element?;
2291 let available_space = size(
2292 AvailableSpace::MinContent,
2293 AvailableSpace::Definite(line_height),
2294 );
2295 let size = element.layout_as_root(available_space, window, cx);
2296
2297 let line = &lines[ix];
2298 let padding = if line.width == Pixels::ZERO {
2299 Pixels::ZERO
2300 } else {
2301 4. * em_width
2302 };
2303 let position = point(
2304 Pixels::from(scroll_pixel_position.x) + line.width + padding,
2305 ix as f32 * line_height
2306 - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
2307 );
2308 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
2309 let origin = content_origin + position + centering_offset;
2310 element.prepaint_as_root(origin, available_space, window, cx);
2311 Some(CreaseTrailerLayout {
2312 element,
2313 bounds: Bounds::new(origin, size),
2314 })
2315 })
2316 .collect()
2317 }
2318
2319 // Folds contained in a hunk are ignored apart from shrinking visual size
2320 // If a fold contains any hunks then that fold line is marked as modified
2321 fn layout_gutter_diff_hunks(
2322 &self,
2323 line_height: Pixels,
2324 gutter_hitbox: &Hitbox,
2325 display_rows: Range<DisplayRow>,
2326 snapshot: &EditorSnapshot,
2327 window: &mut Window,
2328 cx: &mut App,
2329 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
2330 let folded_buffers = self.editor.read(cx).folded_buffers(cx);
2331 let mut display_hunks = snapshot
2332 .display_diff_hunks_for_rows(display_rows, folded_buffers)
2333 .map(|hunk| (hunk, None))
2334 .collect::<Vec<_>>();
2335 let git_gutter_setting = ProjectSettings::get_global(cx).git.git_gutter;
2336 if let GitGutterSetting::TrackedFiles = git_gutter_setting {
2337 for (hunk, hitbox) in &mut display_hunks {
2338 if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
2339 let hunk_bounds =
2340 Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
2341 *hitbox = Some(window.insert_hitbox(hunk_bounds, HitboxBehavior::BlockMouse));
2342 }
2343 }
2344 }
2345
2346 display_hunks
2347 }
2348
2349 fn layout_inline_diagnostics(
2350 &self,
2351 line_layouts: &[LineWithInvisibles],
2352 crease_trailers: &[Option<CreaseTrailerLayout>],
2353 row_block_types: &HashMap<DisplayRow, bool>,
2354 content_origin: gpui::Point<Pixels>,
2355 scroll_position: gpui::Point<ScrollOffset>,
2356 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
2357 edit_prediction_popover_origin: Option<gpui::Point<Pixels>>,
2358 start_row: DisplayRow,
2359 end_row: DisplayRow,
2360 line_height: Pixels,
2361 em_width: Pixels,
2362 style: &EditorStyle,
2363 window: &mut Window,
2364 cx: &mut App,
2365 ) -> HashMap<DisplayRow, AnyElement> {
2366 let max_severity = match self
2367 .editor
2368 .read(cx)
2369 .inline_diagnostics_enabled()
2370 .then(|| {
2371 ProjectSettings::get_global(cx)
2372 .diagnostics
2373 .inline
2374 .max_severity
2375 .unwrap_or_else(|| self.editor.read(cx).diagnostics_max_severity)
2376 .into_lsp()
2377 })
2378 .flatten()
2379 {
2380 Some(max_severity) => max_severity,
2381 None => return HashMap::default(),
2382 };
2383
2384 let active_diagnostics_group =
2385 if let ActiveDiagnostic::Group(group) = &self.editor.read(cx).active_diagnostics {
2386 Some(group.group_id)
2387 } else {
2388 None
2389 };
2390
2391 let diagnostics_by_rows = self.editor.update(cx, |editor, cx| {
2392 let snapshot = editor.snapshot(window, cx);
2393 editor
2394 .inline_diagnostics
2395 .iter()
2396 .filter(|(_, diagnostic)| diagnostic.severity <= max_severity)
2397 .filter(|(_, diagnostic)| match active_diagnostics_group {
2398 Some(active_diagnostics_group) => {
2399 // Active diagnostics are all shown in the editor already, no need to display them inline
2400 diagnostic.group_id != active_diagnostics_group
2401 }
2402 None => true,
2403 })
2404 .map(|(point, diag)| (point.to_display_point(&snapshot), diag.clone()))
2405 .skip_while(|(point, _)| point.row() < start_row)
2406 .take_while(|(point, _)| point.row() < end_row)
2407 .filter(|(point, _)| !row_block_types.contains_key(&point.row()))
2408 .fold(HashMap::default(), |mut acc, (point, diagnostic)| {
2409 acc.entry(point.row())
2410 .or_insert_with(Vec::new)
2411 .push(diagnostic);
2412 acc
2413 })
2414 });
2415
2416 if diagnostics_by_rows.is_empty() {
2417 return HashMap::default();
2418 }
2419
2420 let severity_to_color = |sev: &lsp::DiagnosticSeverity| match sev {
2421 &lsp::DiagnosticSeverity::ERROR => Color::Error,
2422 &lsp::DiagnosticSeverity::WARNING => Color::Warning,
2423 &lsp::DiagnosticSeverity::INFORMATION => Color::Info,
2424 &lsp::DiagnosticSeverity::HINT => Color::Hint,
2425 _ => Color::Error,
2426 };
2427
2428 let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
2429 let min_x = column_pixels(
2430 &self.style,
2431 ProjectSettings::get_global(cx)
2432 .diagnostics
2433 .inline
2434 .min_column as usize,
2435 window,
2436 );
2437
2438 let mut elements = HashMap::default();
2439 for (row, mut diagnostics) in diagnostics_by_rows {
2440 diagnostics.sort_by_key(|diagnostic| {
2441 (
2442 diagnostic.severity,
2443 std::cmp::Reverse(diagnostic.is_primary),
2444 diagnostic.start.row,
2445 diagnostic.start.column,
2446 )
2447 });
2448
2449 let Some(diagnostic_to_render) = diagnostics
2450 .iter()
2451 .find(|diagnostic| diagnostic.is_primary)
2452 .or_else(|| diagnostics.first())
2453 else {
2454 continue;
2455 };
2456
2457 let pos_y = content_origin.y + line_height * (row.0 as f64 - scroll_position.y) as f32;
2458
2459 let window_ix = row.0.saturating_sub(start_row.0) as usize;
2460 let pos_x = {
2461 let crease_trailer_layout = &crease_trailers[window_ix];
2462 let line_layout = &line_layouts[window_ix];
2463
2464 let line_end = if let Some(crease_trailer) = crease_trailer_layout {
2465 crease_trailer.bounds.right()
2466 } else {
2467 Pixels::from(
2468 ScrollPixelOffset::from(content_origin.x + line_layout.width)
2469 - scroll_pixel_position.x,
2470 )
2471 };
2472
2473 let padded_line = line_end + padding;
2474 let min_start = Pixels::from(
2475 ScrollPixelOffset::from(content_origin.x + min_x) - scroll_pixel_position.x,
2476 );
2477
2478 cmp::max(padded_line, min_start)
2479 };
2480
2481 let behind_edit_prediction_popover = edit_prediction_popover_origin
2482 .as_ref()
2483 .is_some_and(|edit_prediction_popover_origin| {
2484 (pos_y..pos_y + line_height).contains(&edit_prediction_popover_origin.y)
2485 });
2486 let opacity = if behind_edit_prediction_popover {
2487 0.5
2488 } else {
2489 1.0
2490 };
2491
2492 let mut element = h_flex()
2493 .id(("diagnostic", row.0))
2494 .h(line_height)
2495 .w_full()
2496 .px_1()
2497 .rounded_xs()
2498 .opacity(opacity)
2499 .bg(severity_to_color(&diagnostic_to_render.severity)
2500 .color(cx)
2501 .opacity(0.05))
2502 .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
2503 .text_sm()
2504 .font(style.text.font())
2505 .child(diagnostic_to_render.message.clone())
2506 .into_any();
2507
2508 element.prepaint_as_root(point(pos_x, pos_y), AvailableSpace::min_size(), window, cx);
2509
2510 elements.insert(row, element);
2511 }
2512
2513 elements
2514 }
2515
2516 fn layout_inline_code_actions(
2517 &self,
2518 display_point: DisplayPoint,
2519 content_origin: gpui::Point<Pixels>,
2520 scroll_position: gpui::Point<ScrollOffset>,
2521 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
2522 line_height: Pixels,
2523 snapshot: &EditorSnapshot,
2524 window: &mut Window,
2525 cx: &mut App,
2526 ) -> Option<AnyElement> {
2527 // Don't show code actions in split diff view
2528 if self.split_side.is_some() {
2529 return None;
2530 }
2531
2532 if !snapshot
2533 .show_code_actions
2534 .unwrap_or(EditorSettings::get_global(cx).inline_code_actions)
2535 {
2536 return None;
2537 }
2538
2539 let icon_size = ui::IconSize::XSmall;
2540 let mut button = self.editor.update(cx, |editor, cx| {
2541 editor.available_code_actions.as_ref()?;
2542 let active = editor
2543 .context_menu
2544 .borrow()
2545 .as_ref()
2546 .and_then(|menu| {
2547 if let crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2548 deployed_from,
2549 ..
2550 }) = menu
2551 {
2552 deployed_from.as_ref()
2553 } else {
2554 None
2555 }
2556 })
2557 .is_some_and(|source| matches!(source, CodeActionSource::Indicator(..)));
2558 Some(editor.render_inline_code_actions(icon_size, display_point.row(), active, cx))
2559 })?;
2560
2561 let buffer_point = display_point.to_point(&snapshot.display_snapshot);
2562
2563 // do not show code action for folded line
2564 if snapshot.is_line_folded(MultiBufferRow(buffer_point.row)) {
2565 return None;
2566 }
2567
2568 // do not show code action for blank line with cursor
2569 let line_indent = snapshot
2570 .display_snapshot
2571 .buffer_snapshot()
2572 .line_indent_for_row(MultiBufferRow(buffer_point.row));
2573 if line_indent.is_line_blank() {
2574 return None;
2575 }
2576
2577 const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
2578 const MAX_ALTERNATE_DISTANCE: u32 = 8;
2579
2580 let excerpt_id = snapshot
2581 .display_snapshot
2582 .buffer_snapshot()
2583 .excerpt_containing(buffer_point..buffer_point)
2584 .map(|excerpt| excerpt.id());
2585
2586 let is_valid_row = |row_candidate: u32| -> bool {
2587 // move to other row if folded row
2588 if snapshot.is_line_folded(MultiBufferRow(row_candidate)) {
2589 return false;
2590 }
2591 if buffer_point.row == row_candidate {
2592 // move to other row if cursor is in slot
2593 if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
2594 return false;
2595 }
2596 } else {
2597 let candidate_point = MultiBufferPoint {
2598 row: row_candidate,
2599 column: 0,
2600 };
2601 let candidate_excerpt_id = snapshot
2602 .display_snapshot
2603 .buffer_snapshot()
2604 .excerpt_containing(candidate_point..candidate_point)
2605 .map(|excerpt| excerpt.id());
2606 // move to other row if different excerpt
2607 if excerpt_id != candidate_excerpt_id {
2608 return false;
2609 }
2610 }
2611 let line_indent = snapshot
2612 .display_snapshot
2613 .buffer_snapshot()
2614 .line_indent_for_row(MultiBufferRow(row_candidate));
2615 // use this row if it's blank
2616 if line_indent.is_line_blank() {
2617 true
2618 } else {
2619 // use this row if code starts after slot
2620 let indent_size = snapshot
2621 .display_snapshot
2622 .buffer_snapshot()
2623 .indent_size_for_line(MultiBufferRow(row_candidate));
2624 indent_size.len >= INLINE_SLOT_CHAR_LIMIT
2625 }
2626 };
2627
2628 let new_buffer_row = if is_valid_row(buffer_point.row) {
2629 Some(buffer_point.row)
2630 } else {
2631 let max_row = snapshot.display_snapshot.buffer_snapshot().max_point().row;
2632 (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
2633 let row_above = buffer_point.row.saturating_sub(offset);
2634 let row_below = buffer_point.row + offset;
2635 if row_above != buffer_point.row && is_valid_row(row_above) {
2636 Some(row_above)
2637 } else if row_below <= max_row && is_valid_row(row_below) {
2638 Some(row_below)
2639 } else {
2640 None
2641 }
2642 })
2643 }?;
2644
2645 let new_display_row = snapshot
2646 .display_snapshot
2647 .point_to_display_point(
2648 Point {
2649 row: new_buffer_row,
2650 column: buffer_point.column,
2651 },
2652 text::Bias::Left,
2653 )
2654 .row();
2655
2656 let start_y = content_origin.y
2657 + (((new_display_row.as_f64() - scroll_position.y) as f32) * line_height)
2658 + (line_height / 2.0)
2659 - (icon_size.square(window, cx) / 2.);
2660 let start_x = (ScrollPixelOffset::from(content_origin.x) - scroll_pixel_position.x
2661 + ScrollPixelOffset::from(window.rem_size() * 0.1))
2662 .into();
2663
2664 let absolute_offset = gpui::point(start_x, start_y);
2665 button.layout_as_root(gpui::AvailableSpace::min_size(), window, cx);
2666 button.prepaint_as_root(
2667 absolute_offset,
2668 gpui::AvailableSpace::min_size(),
2669 window,
2670 cx,
2671 );
2672 Some(button)
2673 }
2674
2675 fn layout_inline_blame(
2676 &self,
2677 display_row: DisplayRow,
2678 row_info: &RowInfo,
2679 line_layout: &LineWithInvisibles,
2680 crease_trailer: Option<&CreaseTrailerLayout>,
2681 em_width: Pixels,
2682 content_origin: gpui::Point<Pixels>,
2683 scroll_position: gpui::Point<ScrollOffset>,
2684 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
2685 line_height: Pixels,
2686 window: &mut Window,
2687 cx: &mut App,
2688 ) -> Option<InlineBlameLayout> {
2689 if !self
2690 .editor
2691 .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
2692 {
2693 return None;
2694 }
2695
2696 let editor = self.editor.read(cx);
2697 let blame = editor.blame.clone()?;
2698 let padding = {
2699 const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
2700
2701 let mut padding = ProjectSettings::get_global(cx).git.inline_blame.padding as f32;
2702
2703 if let Some(edit_prediction) = editor.active_edit_prediction.as_ref()
2704 && let EditPrediction::Edit {
2705 display_mode: EditDisplayMode::TabAccept,
2706 ..
2707 } = &edit_prediction.completion
2708 {
2709 padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS
2710 }
2711
2712 padding * em_width
2713 };
2714
2715 let (buffer_id, entry) = blame
2716 .update(cx, |blame, cx| {
2717 blame.blame_for_rows(&[*row_info], cx).next()
2718 })
2719 .flatten()?;
2720
2721 let mut element = render_inline_blame_entry(entry.clone(), &self.style, cx)?;
2722
2723 let start_y =
2724 content_origin.y + line_height * ((display_row.as_f64() - scroll_position.y) as f32);
2725
2726 let start_x = {
2727 let line_end = if let Some(crease_trailer) = crease_trailer {
2728 crease_trailer.bounds.right()
2729 } else {
2730 Pixels::from(
2731 ScrollPixelOffset::from(content_origin.x + line_layout.width)
2732 - scroll_pixel_position.x,
2733 )
2734 };
2735
2736 let padded_line_end = line_end + padding;
2737
2738 let min_column_in_pixels = column_pixels(
2739 &self.style,
2740 ProjectSettings::get_global(cx).git.inline_blame.min_column as usize,
2741 window,
2742 );
2743 let min_start = Pixels::from(
2744 ScrollPixelOffset::from(content_origin.x + min_column_in_pixels)
2745 - scroll_pixel_position.x,
2746 );
2747
2748 cmp::max(padded_line_end, min_start)
2749 };
2750
2751 let absolute_offset = point(start_x, start_y);
2752 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
2753 let bounds = Bounds::new(absolute_offset, size);
2754
2755 element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
2756
2757 Some(InlineBlameLayout {
2758 element,
2759 bounds,
2760 buffer_id,
2761 entry,
2762 })
2763 }
2764
2765 fn layout_blame_popover(
2766 &self,
2767 editor_snapshot: &EditorSnapshot,
2768 text_hitbox: &Hitbox,
2769 line_height: Pixels,
2770 window: &mut Window,
2771 cx: &mut App,
2772 ) {
2773 if !self.editor.read(cx).inline_blame_popover.is_some() {
2774 return;
2775 }
2776
2777 let Some(blame) = self.editor.read(cx).blame.clone() else {
2778 return;
2779 };
2780 let cursor_point = self
2781 .editor
2782 .read(cx)
2783 .selections
2784 .newest::<language::Point>(&editor_snapshot.display_snapshot)
2785 .head();
2786
2787 let Some((buffer, buffer_point, _)) = editor_snapshot
2788 .buffer_snapshot()
2789 .point_to_buffer_point(cursor_point)
2790 else {
2791 return;
2792 };
2793
2794 let row_info = RowInfo {
2795 buffer_id: Some(buffer.remote_id()),
2796 buffer_row: Some(buffer_point.row),
2797 ..Default::default()
2798 };
2799
2800 let Some((buffer_id, blame_entry)) = blame
2801 .update(cx, |blame, cx| blame.blame_for_rows(&[row_info], cx).next())
2802 .flatten()
2803 else {
2804 return;
2805 };
2806
2807 let Some((popover_state, target_point)) = self.editor.read_with(cx, |editor, _| {
2808 editor
2809 .inline_blame_popover
2810 .as_ref()
2811 .map(|state| (state.popover_state.clone(), state.position))
2812 }) else {
2813 return;
2814 };
2815
2816 let workspace = self
2817 .editor
2818 .read_with(cx, |editor, _| editor.workspace().map(|w| w.downgrade()));
2819
2820 let maybe_element = workspace.and_then(|workspace| {
2821 render_blame_entry_popover(
2822 blame_entry,
2823 popover_state.scroll_handle,
2824 popover_state.commit_message,
2825 popover_state.markdown,
2826 workspace,
2827 &blame,
2828 buffer_id,
2829 window,
2830 cx,
2831 )
2832 });
2833
2834 if let Some(mut element) = maybe_element {
2835 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
2836 let overall_height = size.height + HOVER_POPOVER_GAP;
2837 let popover_origin = if target_point.y > overall_height {
2838 point(target_point.x, target_point.y - size.height)
2839 } else {
2840 point(
2841 target_point.x,
2842 target_point.y + line_height + HOVER_POPOVER_GAP,
2843 )
2844 };
2845
2846 let horizontal_offset = (text_hitbox.top_right().x
2847 - POPOVER_RIGHT_OFFSET
2848 - (popover_origin.x + size.width))
2849 .min(Pixels::ZERO);
2850
2851 let origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
2852 let popover_bounds = Bounds::new(origin, size);
2853
2854 self.editor.update(cx, |editor, _| {
2855 if let Some(state) = &mut editor.inline_blame_popover {
2856 state.popover_bounds = Some(popover_bounds);
2857 }
2858 });
2859
2860 window.defer_draw(element, origin, 2);
2861 }
2862 }
2863
2864 fn layout_blame_entries(
2865 &self,
2866 buffer_rows: &[RowInfo],
2867 em_width: Pixels,
2868 scroll_position: gpui::Point<ScrollOffset>,
2869 line_height: Pixels,
2870 gutter_hitbox: &Hitbox,
2871 max_width: Option<Pixels>,
2872 window: &mut Window,
2873 cx: &mut App,
2874 ) -> Option<Vec<AnyElement>> {
2875 if !self
2876 .editor
2877 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
2878 {
2879 return None;
2880 }
2881
2882 let blame = self.editor.read(cx).blame.clone()?;
2883 let workspace = self.editor.read(cx).workspace()?;
2884 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
2885 blame.blame_for_rows(buffer_rows, cx).collect()
2886 });
2887
2888 let width = if let Some(max_width) = max_width {
2889 AvailableSpace::Definite(max_width)
2890 } else {
2891 AvailableSpace::MaxContent
2892 };
2893 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
2894 let start_x = em_width;
2895
2896 let mut last_used_color: Option<(Hsla, Oid)> = None;
2897 let blame_renderer = cx.global::<GlobalBlameRenderer>().0.clone();
2898
2899 let shaped_lines = blamed_rows
2900 .into_iter()
2901 .enumerate()
2902 .flat_map(|(ix, blame_entry)| {
2903 let (buffer_id, blame_entry) = blame_entry?;
2904 let mut element = render_blame_entry(
2905 ix,
2906 &blame,
2907 blame_entry,
2908 &self.style,
2909 &mut last_used_color,
2910 self.editor.clone(),
2911 workspace.clone(),
2912 buffer_id,
2913 &*blame_renderer,
2914 window,
2915 cx,
2916 )?;
2917
2918 let start_y = ix as f32 * line_height
2919 - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height));
2920 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
2921
2922 element.prepaint_as_root(
2923 absolute_offset,
2924 size(width, AvailableSpace::MinContent),
2925 window,
2926 cx,
2927 );
2928
2929 Some(element)
2930 })
2931 .collect();
2932
2933 Some(shaped_lines)
2934 }
2935
2936 fn layout_indent_guides(
2937 &self,
2938 content_origin: gpui::Point<Pixels>,
2939 text_origin: gpui::Point<Pixels>,
2940 visible_buffer_range: Range<MultiBufferRow>,
2941 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
2942 line_height: Pixels,
2943 snapshot: &DisplaySnapshot,
2944 window: &mut Window,
2945 cx: &mut App,
2946 ) -> Option<Vec<IndentGuideLayout>> {
2947 let indent_guides = self.editor.update(cx, |editor, cx| {
2948 editor.indent_guides(visible_buffer_range, snapshot, cx)
2949 })?;
2950
2951 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
2952 editor
2953 .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
2954 .unwrap_or_default()
2955 });
2956
2957 Some(
2958 indent_guides
2959 .into_iter()
2960 .enumerate()
2961 .filter_map(|(i, indent_guide)| {
2962 let single_indent_width =
2963 column_pixels(&self.style, indent_guide.tab_size as usize, window);
2964 let total_width = single_indent_width * indent_guide.depth as f32;
2965 let start_x = Pixels::from(
2966 ScrollOffset::from(content_origin.x + total_width)
2967 - scroll_pixel_position.x,
2968 );
2969 if start_x >= text_origin.x {
2970 let (offset_y, length) = Self::calculate_indent_guide_bounds(
2971 indent_guide.start_row..indent_guide.end_row,
2972 line_height,
2973 snapshot,
2974 );
2975
2976 let start_y = Pixels::from(
2977 ScrollOffset::from(content_origin.y) + offset_y
2978 - scroll_pixel_position.y,
2979 );
2980
2981 Some(IndentGuideLayout {
2982 origin: point(start_x, start_y),
2983 length,
2984 single_indent_width,
2985 depth: indent_guide.depth,
2986 active: active_indent_guide_indices.contains(&i),
2987 settings: indent_guide.settings,
2988 })
2989 } else {
2990 None
2991 }
2992 })
2993 .collect(),
2994 )
2995 }
2996
2997 fn layout_wrap_guides(
2998 &self,
2999 em_advance: Pixels,
3000 scroll_position: gpui::Point<f64>,
3001 content_origin: gpui::Point<Pixels>,
3002 scrollbar_layout: Option<&EditorScrollbars>,
3003 vertical_scrollbar_width: Pixels,
3004 hitbox: &Hitbox,
3005 window: &Window,
3006 cx: &App,
3007 ) -> SmallVec<[(Pixels, bool); 2]> {
3008 let scroll_left = scroll_position.x as f32 * em_advance;
3009 let content_origin = content_origin.x;
3010 let horizontal_offset = content_origin - scroll_left;
3011 let vertical_scrollbar_width = scrollbar_layout
3012 .and_then(|layout| layout.visible.then_some(vertical_scrollbar_width))
3013 .unwrap_or_default();
3014
3015 self.editor
3016 .read(cx)
3017 .wrap_guides(cx)
3018 .into_iter()
3019 .flat_map(|(guide, active)| {
3020 let wrap_position = column_pixels(&self.style, guide, window);
3021 let wrap_guide_x = wrap_position + horizontal_offset;
3022 let display_wrap_guide = wrap_guide_x >= content_origin
3023 && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
3024
3025 display_wrap_guide.then_some((wrap_guide_x, active))
3026 })
3027 .collect()
3028 }
3029
3030 fn calculate_indent_guide_bounds(
3031 row_range: Range<MultiBufferRow>,
3032 line_height: Pixels,
3033 snapshot: &DisplaySnapshot,
3034 ) -> (f64, gpui::Pixels) {
3035 let start_point = Point::new(row_range.start.0, 0);
3036 let end_point = Point::new(row_range.end.0, 0);
3037
3038 let row_range = start_point.to_display_point(snapshot).row()
3039 ..end_point.to_display_point(snapshot).row();
3040
3041 let mut prev_line = start_point;
3042 prev_line.row = prev_line.row.saturating_sub(1);
3043 let prev_line = prev_line.to_display_point(snapshot).row();
3044
3045 let mut cons_line = end_point;
3046 cons_line.row += 1;
3047 let cons_line = cons_line.to_display_point(snapshot).row();
3048
3049 let mut offset_y = row_range.start.as_f64() * f64::from(line_height);
3050 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
3051
3052 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
3053 if row_range.end == cons_line {
3054 length += line_height;
3055 }
3056
3057 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
3058 // we want to extend the indent guide to the start of the block.
3059 let mut block_height = 0;
3060 let mut block_offset = 0;
3061 let mut found_excerpt_header = false;
3062 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
3063 if matches!(
3064 block,
3065 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
3066 ) {
3067 found_excerpt_header = true;
3068 break;
3069 }
3070 block_offset += block.height();
3071 block_height += block.height();
3072 }
3073 if !found_excerpt_header {
3074 offset_y -= block_offset as f64 * f64::from(line_height);
3075 length += block_height as f32 * line_height;
3076 }
3077
3078 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
3079 // we want to ensure that the indent guide stops before the excerpt header.
3080 let mut block_height = 0;
3081 let mut found_excerpt_header = false;
3082 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
3083 if matches!(
3084 block,
3085 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
3086 ) {
3087 found_excerpt_header = true;
3088 }
3089 block_height += block.height();
3090 }
3091 if found_excerpt_header {
3092 length -= block_height as f32 * line_height;
3093 }
3094
3095 (offset_y, length)
3096 }
3097
3098 fn layout_breakpoints(
3099 &self,
3100 line_height: Pixels,
3101 range: Range<DisplayRow>,
3102 scroll_position: gpui::Point<ScrollOffset>,
3103 gutter_dimensions: &GutterDimensions,
3104 gutter_hitbox: &Hitbox,
3105 snapshot: &EditorSnapshot,
3106 breakpoints: HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
3107 row_infos: &[RowInfo],
3108 window: &mut Window,
3109 cx: &mut App,
3110 ) -> Vec<AnyElement> {
3111 if self.split_side == Some(SplitSide::Left) {
3112 return Vec::new();
3113 }
3114
3115 self.editor.update(cx, |editor, cx| {
3116 breakpoints
3117 .into_iter()
3118 .filter_map(|(display_row, (text_anchor, bp, state))| {
3119 if row_infos
3120 .get((display_row.0.saturating_sub(range.start.0)) as usize)
3121 .is_some_and(|row_info| {
3122 row_info.expand_info.is_some()
3123 || row_info
3124 .diff_status
3125 .is_some_and(|status| status.is_deleted())
3126 })
3127 {
3128 return None;
3129 }
3130
3131 if range.start > display_row || range.end < display_row {
3132 return None;
3133 }
3134
3135 let row =
3136 MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(snapshot).row);
3137 if snapshot.is_line_folded(row) {
3138 return None;
3139 }
3140
3141 let button = editor.render_breakpoint(text_anchor, display_row, &bp, state, cx);
3142
3143 let button = prepaint_gutter_button(
3144 button.into_any_element(),
3145 display_row,
3146 line_height,
3147 gutter_dimensions,
3148 scroll_position,
3149 gutter_hitbox,
3150 window,
3151 cx,
3152 );
3153 Some(button)
3154 })
3155 .collect_vec()
3156 })
3157 }
3158
3159 fn should_render_diff_review_button(
3160 &self,
3161 range: Range<DisplayRow>,
3162 row_infos: &[RowInfo],
3163 snapshot: &EditorSnapshot,
3164 cx: &App,
3165 ) -> Option<(DisplayRow, Option<u32>)> {
3166 if !cx.has_flag::<DiffReviewFeatureFlag>() {
3167 return None;
3168 }
3169
3170 let show_diff_review_button = self.editor.read(cx).show_diff_review_button();
3171 if !show_diff_review_button {
3172 return None;
3173 }
3174
3175 let indicator = self.editor.read(cx).gutter_diff_review_indicator.0?;
3176 if !indicator.is_active {
3177 return None;
3178 }
3179
3180 let display_row = indicator
3181 .start
3182 .to_display_point(&snapshot.display_snapshot)
3183 .row();
3184 let row_index = (display_row.0.saturating_sub(range.start.0)) as usize;
3185
3186 let row_info = row_infos.get(row_index);
3187 if row_info.is_some_and(|row_info| row_info.expand_info.is_some()) {
3188 return None;
3189 }
3190
3191 let buffer_id = row_info.and_then(|info| info.buffer_id);
3192 if buffer_id.is_none() {
3193 return None;
3194 }
3195
3196 let editor = self.editor.read(cx);
3197 if buffer_id.is_some_and(|buffer_id| editor.is_buffer_folded(buffer_id, cx)) {
3198 return None;
3199 }
3200
3201 let buffer_row = row_info.and_then(|info| info.buffer_row);
3202 Some((display_row, buffer_row))
3203 }
3204
3205 #[allow(clippy::too_many_arguments)]
3206 fn layout_run_indicators(
3207 &self,
3208 line_height: Pixels,
3209 range: Range<DisplayRow>,
3210 row_infos: &[RowInfo],
3211 scroll_position: gpui::Point<ScrollOffset>,
3212 gutter_dimensions: &GutterDimensions,
3213 gutter_hitbox: &Hitbox,
3214 snapshot: &EditorSnapshot,
3215 breakpoints: &mut HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
3216 window: &mut Window,
3217 cx: &mut App,
3218 ) -> Vec<AnyElement> {
3219 if self.split_side == Some(SplitSide::Left) {
3220 return Vec::new();
3221 }
3222
3223 self.editor.update(cx, |editor, cx| {
3224 let active_task_indicator_row =
3225 // TODO: add edit button on the right side of each row in the context menu
3226 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
3227 deployed_from,
3228 actions,
3229 ..
3230 })) = editor.context_menu.borrow().as_ref()
3231 {
3232 actions
3233 .tasks()
3234 .map(|tasks| tasks.position.to_display_point(snapshot).row())
3235 .or_else(|| match deployed_from {
3236 Some(CodeActionSource::Indicator(row)) => Some(*row),
3237 _ => None,
3238 })
3239 } else {
3240 None
3241 };
3242
3243 let offset_range_start =
3244 snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left);
3245
3246 let offset_range_end =
3247 snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
3248
3249 editor
3250 .tasks
3251 .iter()
3252 .filter_map(|(_, tasks)| {
3253 let multibuffer_point = tasks.offset.to_point(&snapshot.buffer_snapshot());
3254 if multibuffer_point < offset_range_start
3255 || multibuffer_point > offset_range_end
3256 {
3257 return None;
3258 }
3259 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
3260 let buffer_folded = snapshot
3261 .buffer_snapshot()
3262 .buffer_line_for_row(multibuffer_row)
3263 .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
3264 .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
3265 .unwrap_or(false);
3266 if buffer_folded {
3267 return None;
3268 }
3269
3270 if snapshot.is_line_folded(multibuffer_row) {
3271 // Skip folded indicators, unless it's the starting line of a fold.
3272 if multibuffer_row
3273 .0
3274 .checked_sub(1)
3275 .is_some_and(|previous_row| {
3276 snapshot.is_line_folded(MultiBufferRow(previous_row))
3277 })
3278 {
3279 return None;
3280 }
3281 }
3282
3283 let display_row = multibuffer_point.to_display_point(snapshot).row();
3284 if !range.contains(&display_row) {
3285 return None;
3286 }
3287 if row_infos
3288 .get((display_row - range.start).0 as usize)
3289 .is_some_and(|row_info| row_info.expand_info.is_some())
3290 {
3291 return None;
3292 }
3293
3294 let removed_breakpoint = breakpoints.remove(&display_row);
3295 let button = editor.render_run_indicator(
3296 &self.style,
3297 Some(display_row) == active_task_indicator_row,
3298 display_row,
3299 removed_breakpoint,
3300 cx,
3301 );
3302
3303 let button = prepaint_gutter_button(
3304 button.into_any_element(),
3305 display_row,
3306 line_height,
3307 gutter_dimensions,
3308 scroll_position,
3309 gutter_hitbox,
3310 window,
3311 cx,
3312 );
3313 Some(button)
3314 })
3315 .collect_vec()
3316 })
3317 }
3318
3319 fn layout_expand_toggles(
3320 &self,
3321 gutter_hitbox: &Hitbox,
3322 gutter_dimensions: GutterDimensions,
3323 em_width: Pixels,
3324 line_height: Pixels,
3325 scroll_position: gpui::Point<ScrollOffset>,
3326 buffer_rows: &[RowInfo],
3327 window: &mut Window,
3328 cx: &mut App,
3329 ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
3330 if self.editor.read(cx).disable_expand_excerpt_buttons {
3331 return vec![];
3332 }
3333
3334 let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
3335
3336 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
3337
3338 let max_line_number_length = self
3339 .editor
3340 .read(cx)
3341 .buffer()
3342 .read(cx)
3343 .snapshot(cx)
3344 .widest_line_number()
3345 .ilog10()
3346 + 1;
3347
3348 let git_gutter_width = Self::gutter_strip_width(line_height)
3349 + gutter_dimensions
3350 .git_blame_entries_width
3351 .unwrap_or_default();
3352 let available_width = gutter_dimensions.left_padding - git_gutter_width;
3353
3354 buffer_rows
3355 .iter()
3356 .enumerate()
3357 .map(|(ix, row_info)| {
3358 let ExpandInfo {
3359 excerpt_id,
3360 direction,
3361 } = row_info.expand_info?;
3362
3363 let icon_name = match direction {
3364 ExpandExcerptDirection::Up => IconName::ExpandUp,
3365 ExpandExcerptDirection::Down => IconName::ExpandDown,
3366 ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
3367 };
3368
3369 let editor = self.editor.clone();
3370 let is_wide = max_line_number_length
3371 >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
3372 && row_info
3373 .buffer_row
3374 .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
3375 || gutter_dimensions.right_padding == px(0.);
3376
3377 let width = if is_wide {
3378 available_width - px(5.)
3379 } else {
3380 available_width + em_width - px(5.)
3381 };
3382
3383 let toggle = IconButton::new(("expand", ix), icon_name)
3384 .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
3385 .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
3386 .width(width)
3387 .on_click(move |_, window, cx| {
3388 editor.update(cx, |editor, cx| {
3389 editor.expand_excerpt(excerpt_id, direction, window, cx);
3390 });
3391 })
3392 .tooltip(Tooltip::for_action_title(
3393 "Expand Excerpt",
3394 &crate::actions::ExpandExcerpts::default(),
3395 ))
3396 .into_any_element();
3397
3398 let position = point(
3399 git_gutter_width + px(1.),
3400 ix as f32 * line_height
3401 - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height))
3402 + px(1.),
3403 );
3404 let origin = gutter_hitbox.origin + position;
3405
3406 Some((toggle, origin))
3407 })
3408 .collect()
3409 }
3410
3411 fn layout_line_numbers(
3412 &self,
3413 gutter_hitbox: Option<&Hitbox>,
3414 gutter_dimensions: GutterDimensions,
3415 line_height: Pixels,
3416 scroll_position: gpui::Point<ScrollOffset>,
3417 rows: Range<DisplayRow>,
3418 buffer_rows: &[RowInfo],
3419 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3420 current_selection_head: Option<DisplayRow>,
3421 snapshot: &EditorSnapshot,
3422 window: &mut Window,
3423 cx: &mut App,
3424 ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
3425 let include_line_numbers = snapshot
3426 .show_line_numbers
3427 .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
3428 if !include_line_numbers {
3429 return Arc::default();
3430 }
3431
3432 let relative = self.editor.read(cx).relative_line_numbers(cx);
3433
3434 let relative_line_numbers_enabled = relative.enabled();
3435 let relative_rows = if relative_line_numbers_enabled
3436 && let Some(current_selection_head) = current_selection_head
3437 {
3438 snapshot.calculate_relative_line_numbers(
3439 &rows,
3440 current_selection_head,
3441 relative.wrapped(),
3442 )
3443 } else {
3444 Default::default()
3445 };
3446
3447 let mut line_number = String::new();
3448 let segments = buffer_rows.iter().enumerate().flat_map(|(ix, row_info)| {
3449 let display_row = DisplayRow(rows.start.0 + ix as u32);
3450 line_number.clear();
3451 let non_relative_number = if relative.wrapped() {
3452 row_info.buffer_row.or(row_info.wrapped_buffer_row)? + 1
3453 } else {
3454 row_info.buffer_row? + 1
3455 };
3456 let relative_number = relative_rows.get(&display_row);
3457 if !(relative_line_numbers_enabled && relative_number.is_some())
3458 && !snapshot.number_deleted_lines
3459 && row_info
3460 .diff_status
3461 .is_some_and(|status| status.is_deleted())
3462 {
3463 return None;
3464 }
3465
3466 let number = relative_number.unwrap_or(&non_relative_number);
3467 write!(&mut line_number, "{number}").unwrap();
3468
3469 let color = active_rows
3470 .get(&display_row)
3471 .map(|spec| {
3472 if spec.breakpoint {
3473 cx.theme().colors().debugger_accent
3474 } else {
3475 cx.theme().colors().editor_active_line_number
3476 }
3477 })
3478 .unwrap_or_else(|| cx.theme().colors().editor_line_number);
3479 let shaped_line =
3480 self.shape_line_number(SharedString::from(&line_number), color, window);
3481 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
3482 let line_origin = gutter_hitbox.map(|hitbox| {
3483 hitbox.origin
3484 + point(
3485 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
3486 ix as f32 * line_height
3487 - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height)),
3488 )
3489 });
3490
3491 #[cfg(not(test))]
3492 let hitbox = line_origin.map(|line_origin| {
3493 window.insert_hitbox(
3494 Bounds::new(line_origin, size(shaped_line.width, line_height)),
3495 HitboxBehavior::Normal,
3496 )
3497 });
3498 #[cfg(test)]
3499 let hitbox = {
3500 let _ = line_origin;
3501 None
3502 };
3503
3504 let segment = LineNumberSegment {
3505 shaped_line,
3506 hitbox,
3507 };
3508
3509 let buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
3510 let multi_buffer_row = MultiBufferRow(buffer_row);
3511
3512 Some((multi_buffer_row, segment))
3513 });
3514
3515 let mut line_numbers: HashMap<MultiBufferRow, LineNumberLayout> = HashMap::default();
3516 for (buffer_row, segment) in segments {
3517 line_numbers
3518 .entry(buffer_row)
3519 .or_insert_with(|| LineNumberLayout {
3520 segments: Default::default(),
3521 })
3522 .segments
3523 .push(segment);
3524 }
3525 Arc::new(line_numbers)
3526 }
3527
3528 fn layout_crease_toggles(
3529 &self,
3530 rows: Range<DisplayRow>,
3531 row_infos: &[RowInfo],
3532 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3533 snapshot: &EditorSnapshot,
3534 window: &mut Window,
3535 cx: &mut App,
3536 ) -> Vec<Option<AnyElement>> {
3537 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
3538 && snapshot.mode.is_full()
3539 && self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
3540 if include_fold_statuses {
3541 row_infos
3542 .iter()
3543 .enumerate()
3544 .map(|(ix, info)| {
3545 if info.expand_info.is_some() {
3546 return None;
3547 }
3548 let row = info.multibuffer_row?;
3549 let display_row = DisplayRow(rows.start.0 + ix as u32);
3550 let active = active_rows.contains_key(&display_row);
3551
3552 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
3553 })
3554 .collect()
3555 } else {
3556 Vec::new()
3557 }
3558 }
3559
3560 fn layout_crease_trailers(
3561 &self,
3562 buffer_rows: impl IntoIterator<Item = RowInfo>,
3563 snapshot: &EditorSnapshot,
3564 window: &mut Window,
3565 cx: &mut App,
3566 ) -> Vec<Option<AnyElement>> {
3567 buffer_rows
3568 .into_iter()
3569 .map(|row_info| {
3570 if row_info.expand_info.is_some() {
3571 return None;
3572 }
3573 if let Some(row) = row_info.multibuffer_row {
3574 snapshot.render_crease_trailer(row, window, cx)
3575 } else {
3576 None
3577 }
3578 })
3579 .collect()
3580 }
3581
3582 fn bg_segments_per_row(
3583 rows: Range<DisplayRow>,
3584 selections: &[(PlayerColor, Vec<SelectionLayout>)],
3585 highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
3586 base_background: Hsla,
3587 ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
3588 if rows.start >= rows.end {
3589 return Vec::new();
3590 }
3591 if !base_background.is_opaque() {
3592 // We don't actually know what color is behind this editor.
3593 return Vec::new();
3594 }
3595 let highlight_iter = highlight_ranges.iter().cloned();
3596 let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
3597 let color = player_color.selection;
3598 layouts.iter().filter_map(move |selection_layout| {
3599 if selection_layout.range.start != selection_layout.range.end {
3600 Some((selection_layout.range.clone(), color))
3601 } else {
3602 None
3603 }
3604 })
3605 });
3606 let mut per_row_map = vec![Vec::new(); rows.len()];
3607 for (range, color) in highlight_iter.chain(selection_iter) {
3608 let covered_rows = if range.end.column() == 0 {
3609 cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
3610 } else {
3611 cmp::max(range.start.row(), rows.start)
3612 ..cmp::min(range.end.row().next_row(), rows.end)
3613 };
3614 for row in covered_rows.iter_rows() {
3615 let seg_start = if row == range.start.row() {
3616 range.start
3617 } else {
3618 DisplayPoint::new(row, 0)
3619 };
3620 let seg_end = if row == range.end.row() && range.end.column() != 0 {
3621 range.end
3622 } else {
3623 DisplayPoint::new(row, u32::MAX)
3624 };
3625 let ix = row.minus(rows.start) as usize;
3626 debug_assert!(row >= rows.start && row < rows.end);
3627 debug_assert!(ix < per_row_map.len());
3628 per_row_map[ix].push((seg_start..seg_end, color));
3629 }
3630 }
3631 for row_segments in per_row_map.iter_mut() {
3632 if row_segments.is_empty() {
3633 continue;
3634 }
3635 let segments = mem::take(row_segments);
3636 let merged = Self::merge_overlapping_ranges(segments, base_background);
3637 *row_segments = merged;
3638 }
3639 per_row_map
3640 }
3641
3642 /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
3643 /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
3644 ///
3645 /// Expects `start.row() == end.row()` for each range.
3646 fn merge_overlapping_ranges(
3647 ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3648 base_background: Hsla,
3649 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
3650 struct Boundary {
3651 pos: DisplayPoint,
3652 is_start: bool,
3653 index: usize,
3654 color: Hsla,
3655 }
3656
3657 let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
3658 for (index, (range, color)) in ranges.iter().enumerate() {
3659 debug_assert!(
3660 range.start.row() == range.end.row(),
3661 "expects single-row ranges"
3662 );
3663 if range.start < range.end {
3664 boundaries.push(Boundary {
3665 pos: range.start,
3666 is_start: true,
3667 index,
3668 color: *color,
3669 });
3670 boundaries.push(Boundary {
3671 pos: range.end,
3672 is_start: false,
3673 index,
3674 color: *color,
3675 });
3676 }
3677 }
3678
3679 if boundaries.is_empty() {
3680 return Vec::new();
3681 }
3682
3683 boundaries
3684 .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
3685
3686 let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
3687 let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
3688
3689 let mut i = 0;
3690 let mut start_pos = boundaries[0].pos;
3691
3692 let boundaries_len = boundaries.len();
3693 while i < boundaries_len {
3694 let current_boundary_pos = boundaries[i].pos;
3695 if start_pos < current_boundary_pos {
3696 if !active_ranges.is_empty() {
3697 let mut color = base_background;
3698 for &(_, c) in &active_ranges {
3699 color = Hsla::blend(color, c);
3700 }
3701 if let Some((last_range, last_color)) = processed_ranges.last_mut() {
3702 if *last_color == color && last_range.end == start_pos {
3703 last_range.end = current_boundary_pos;
3704 } else {
3705 processed_ranges.push((start_pos..current_boundary_pos, color));
3706 }
3707 } else {
3708 processed_ranges.push((start_pos..current_boundary_pos, color));
3709 }
3710 }
3711 }
3712 while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
3713 let active_range = &boundaries[i];
3714 if active_range.is_start {
3715 let idx = active_range.index;
3716 let pos = active_ranges
3717 .binary_search_by_key(&idx, |(i, _)| *i)
3718 .unwrap_or_else(|p| p);
3719 active_ranges.insert(pos, (idx, active_range.color));
3720 } else {
3721 let idx = active_range.index;
3722 if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
3723 active_ranges.remove(pos);
3724 }
3725 }
3726 i += 1;
3727 }
3728 start_pos = current_boundary_pos;
3729 }
3730
3731 processed_ranges
3732 }
3733
3734 fn layout_lines(
3735 rows: Range<DisplayRow>,
3736 snapshot: &EditorSnapshot,
3737 style: &EditorStyle,
3738 editor_width: Pixels,
3739 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3740 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
3741 window: &mut Window,
3742 cx: &mut App,
3743 ) -> Vec<LineWithInvisibles> {
3744 if rows.start >= rows.end {
3745 return Vec::new();
3746 }
3747
3748 // Show the placeholder when the editor is empty
3749 if snapshot.is_empty() {
3750 let font_size = style.text.font_size.to_pixels(window.rem_size());
3751 let placeholder_color = cx.theme().colors().text_placeholder;
3752 let placeholder_text = snapshot.placeholder_text();
3753
3754 let placeholder_lines = placeholder_text
3755 .as_ref()
3756 .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
3757
3758 let placeholder_line_count = placeholder_lines.len();
3759
3760 placeholder_lines
3761 .into_iter()
3762 .skip(rows.start.0 as usize)
3763 .chain(iter::repeat(""))
3764 .take(cmp::max(rows.len(), placeholder_line_count))
3765 .map(move |line| {
3766 let run = TextRun {
3767 len: line.len(),
3768 font: style.text.font(),
3769 color: placeholder_color,
3770 ..Default::default()
3771 };
3772 let line = window.text_system().shape_line(
3773 line.to_string().into(),
3774 font_size,
3775 &[run],
3776 None,
3777 );
3778 LineWithInvisibles {
3779 width: line.width,
3780 len: line.len,
3781 fragments: smallvec![LineFragment::Text(line)],
3782 invisibles: Vec::new(),
3783 font_size,
3784 }
3785 })
3786 .collect()
3787 } else {
3788 let use_tree_sitter = !snapshot.semantic_tokens_enabled
3789 || snapshot.use_tree_sitter_for_syntax(rows.start, cx);
3790 let chunks = snapshot.highlighted_chunks(rows.clone(), use_tree_sitter, style);
3791 LineWithInvisibles::from_chunks(
3792 chunks,
3793 style,
3794 MAX_LINE_LEN,
3795 rows.len(),
3796 &snapshot.mode,
3797 editor_width,
3798 is_row_soft_wrapped,
3799 bg_segments_per_row,
3800 window,
3801 cx,
3802 )
3803 }
3804 }
3805
3806 fn prepaint_lines(
3807 &self,
3808 start_row: DisplayRow,
3809 line_layouts: &mut [LineWithInvisibles],
3810 line_height: Pixels,
3811 scroll_position: gpui::Point<ScrollOffset>,
3812 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
3813 content_origin: gpui::Point<Pixels>,
3814 window: &mut Window,
3815 cx: &mut App,
3816 ) -> SmallVec<[AnyElement; 1]> {
3817 let mut line_elements = SmallVec::new();
3818 for (ix, line) in line_layouts.iter_mut().enumerate() {
3819 let row = start_row + DisplayRow(ix as u32);
3820 line.prepaint(
3821 line_height,
3822 scroll_position,
3823 scroll_pixel_position,
3824 row,
3825 content_origin,
3826 &mut line_elements,
3827 window,
3828 cx,
3829 );
3830 }
3831 line_elements
3832 }
3833
3834 fn render_block(
3835 &self,
3836 block: &Block,
3837 available_width: AvailableSpace,
3838 block_id: BlockId,
3839 block_row_start: DisplayRow,
3840 snapshot: &EditorSnapshot,
3841 text_x: Pixels,
3842 rows: &Range<DisplayRow>,
3843 line_layouts: &[LineWithInvisibles],
3844 editor_margins: &EditorMargins,
3845 line_height: Pixels,
3846 em_width: Pixels,
3847 text_hitbox: &Hitbox,
3848 editor_width: Pixels,
3849 scroll_width: &mut Pixels,
3850 resized_blocks: &mut HashMap<CustomBlockId, u32>,
3851 row_block_types: &mut HashMap<DisplayRow, bool>,
3852 selections: &[Selection<Point>],
3853 selected_buffer_ids: &Vec<BufferId>,
3854 latest_selection_anchors: &HashMap<BufferId, Anchor>,
3855 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3856 sticky_header_excerpt_id: Option<ExcerptId>,
3857 block_resize_offset: &mut i32,
3858 window: &mut Window,
3859 cx: &mut App,
3860 ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
3861 let mut x_position = None;
3862 let mut element = match block {
3863 Block::Custom(custom) => {
3864 let block_start = custom.start().to_point(&snapshot.buffer_snapshot());
3865 let block_end = custom.end().to_point(&snapshot.buffer_snapshot());
3866 if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
3867 return None;
3868 }
3869 let align_to = block_start.to_display_point(snapshot);
3870 let x_and_width = |layout: &LineWithInvisibles| {
3871 Some((
3872 text_x + layout.x_for_index(align_to.column() as usize),
3873 text_x + layout.width,
3874 ))
3875 };
3876 let line_ix = align_to.row().0.checked_sub(rows.start.0);
3877 x_position =
3878 if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
3879 x_and_width(layout)
3880 } else {
3881 x_and_width(&layout_line(
3882 align_to.row(),
3883 snapshot,
3884 &self.style,
3885 editor_width,
3886 is_row_soft_wrapped,
3887 window,
3888 cx,
3889 ))
3890 };
3891
3892 let anchor_x = x_position.unwrap().0;
3893
3894 let selected = selections
3895 .binary_search_by(|selection| {
3896 if selection.end <= block_start {
3897 Ordering::Less
3898 } else if selection.start >= block_end {
3899 Ordering::Greater
3900 } else {
3901 Ordering::Equal
3902 }
3903 })
3904 .is_ok();
3905
3906 div()
3907 .size_full()
3908 .child(custom.render(&mut BlockContext {
3909 window,
3910 app: cx,
3911 anchor_x,
3912 margins: editor_margins,
3913 line_height,
3914 em_width,
3915 block_id,
3916 selected,
3917 max_width: text_hitbox.size.width.max(*scroll_width),
3918 editor_style: &self.style,
3919 }))
3920 .into_any()
3921 }
3922
3923 Block::FoldedBuffer {
3924 first_excerpt,
3925 height,
3926 ..
3927 } => {
3928 let mut result = v_flex().id(block_id).w_full().pr(editor_margins.right);
3929
3930 if self.should_show_buffer_headers() {
3931 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
3932 let jump_data = header_jump_data(
3933 snapshot,
3934 block_row_start,
3935 *height,
3936 first_excerpt,
3937 latest_selection_anchors,
3938 );
3939 result = result.child(self.render_buffer_header(
3940 first_excerpt,
3941 true,
3942 selected,
3943 false,
3944 jump_data,
3945 window,
3946 cx,
3947 ));
3948 } else {
3949 result =
3950 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3951 }
3952
3953 result.into_any_element()
3954 }
3955
3956 Block::ExcerptBoundary { .. } => {
3957 let color = cx.theme().colors().clone();
3958 let mut result = v_flex().id(block_id).w_full();
3959
3960 result = result.child(
3961 h_flex().relative().child(
3962 div()
3963 .top(line_height / 2.)
3964 .absolute()
3965 .w_full()
3966 .h_px()
3967 .bg(color.border_variant),
3968 ),
3969 );
3970
3971 result.into_any()
3972 }
3973
3974 Block::BufferHeader { excerpt, height } => {
3975 let mut result = v_flex().id(block_id).w_full();
3976
3977 if self.should_show_buffer_headers() {
3978 let jump_data = header_jump_data(
3979 snapshot,
3980 block_row_start,
3981 *height,
3982 excerpt,
3983 latest_selection_anchors,
3984 );
3985
3986 if sticky_header_excerpt_id != Some(excerpt.id) {
3987 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3988
3989 result = result.child(div().pr(editor_margins.right).child(
3990 self.render_buffer_header(
3991 excerpt, false, selected, false, jump_data, window, cx,
3992 ),
3993 ));
3994 } else {
3995 result =
3996 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3997 }
3998 } else {
3999 result =
4000 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
4001 }
4002
4003 result.into_any()
4004 }
4005
4006 Block::Spacer { height, .. } => div()
4007 .id(block_id)
4008 .w_full()
4009 .h((*height as f32) * line_height)
4010 .bg(pattern_slash(
4011 cx.theme().colors().panel_background,
4012 8.0,
4013 8.0,
4014 ))
4015 .into_any(),
4016 };
4017
4018 // Discover the element's content height, then round up to the nearest multiple of line height.
4019 let preliminary_size = element.layout_as_root(
4020 size(available_width, AvailableSpace::MinContent),
4021 window,
4022 cx,
4023 );
4024 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
4025 let final_size = if preliminary_size.height == quantized_height {
4026 preliminary_size
4027 } else {
4028 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
4029 };
4030 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
4031
4032 let effective_row_start = block_row_start.0 as i32 + *block_resize_offset;
4033 debug_assert!(effective_row_start >= 0);
4034 let mut row = DisplayRow(effective_row_start.max(0) as u32);
4035
4036 let mut x_offset = px(0.);
4037 let mut is_block = true;
4038
4039 if let BlockId::Custom(custom_block_id) = block_id
4040 && block.has_height()
4041 {
4042 if block.place_near()
4043 && let Some((x_target, line_width)) = x_position
4044 {
4045 let margin = em_width * 2;
4046 if line_width + final_size.width + margin
4047 < editor_width + editor_margins.gutter.full_width()
4048 && !row_block_types.contains_key(&(row - 1))
4049 && element_height_in_lines == 1
4050 {
4051 x_offset = line_width + margin;
4052 row = row - 1;
4053 is_block = false;
4054 element_height_in_lines = 0;
4055 row_block_types.insert(row, is_block);
4056 } else {
4057 let max_offset =
4058 editor_width + editor_margins.gutter.full_width() - final_size.width;
4059 let min_offset = (x_target + em_width - final_size.width)
4060 .max(editor_margins.gutter.full_width());
4061 x_offset = x_target.min(max_offset).max(min_offset);
4062 }
4063 };
4064 if element_height_in_lines != block.height() {
4065 *block_resize_offset += element_height_in_lines as i32 - block.height() as i32;
4066 resized_blocks.insert(custom_block_id, element_height_in_lines);
4067 }
4068 }
4069 for i in 0..element_height_in_lines {
4070 row_block_types.insert(row + i, is_block);
4071 }
4072
4073 Some((element, final_size, row, x_offset))
4074 }
4075
4076 fn render_buffer_header(
4077 &self,
4078 for_excerpt: &ExcerptInfo,
4079 is_folded: bool,
4080 is_selected: bool,
4081 is_sticky: bool,
4082 jump_data: JumpData,
4083 window: &mut Window,
4084 cx: &mut App,
4085 ) -> impl IntoElement {
4086 render_buffer_header(
4087 &self.editor,
4088 for_excerpt,
4089 is_folded,
4090 is_selected,
4091 is_sticky,
4092 jump_data,
4093 window,
4094 cx,
4095 )
4096 }
4097
4098 fn render_blocks(
4099 &self,
4100 rows: Range<DisplayRow>,
4101 snapshot: &EditorSnapshot,
4102 hitbox: &Hitbox,
4103 text_hitbox: &Hitbox,
4104 editor_width: Pixels,
4105 scroll_width: &mut Pixels,
4106 editor_margins: &EditorMargins,
4107 em_width: Pixels,
4108 text_x: Pixels,
4109 line_height: Pixels,
4110 line_layouts: &mut [LineWithInvisibles],
4111 selections: &[Selection<Point>],
4112 selected_buffer_ids: &Vec<BufferId>,
4113 latest_selection_anchors: &HashMap<BufferId, Anchor>,
4114 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4115 sticky_header_excerpt_id: Option<ExcerptId>,
4116 window: &mut Window,
4117 cx: &mut App,
4118 ) -> RenderBlocksOutput {
4119 let (fixed_blocks, non_fixed_blocks) = snapshot
4120 .blocks_in_range(rows.clone())
4121 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
4122
4123 let mut focused_block = self
4124 .editor
4125 .update(cx, |editor, _| editor.take_focused_block());
4126 let mut fixed_block_max_width = Pixels::ZERO;
4127 let mut blocks = Vec::new();
4128 let mut resized_blocks = HashMap::default();
4129 let mut row_block_types = HashMap::default();
4130 let mut block_resize_offset: i32 = 0;
4131
4132 for (row, block) in fixed_blocks {
4133 let block_id = block.id();
4134
4135 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4136 focused_block = None;
4137 }
4138
4139 if let Some((element, element_size, row, x_offset)) = self.render_block(
4140 block,
4141 AvailableSpace::MinContent,
4142 block_id,
4143 row,
4144 snapshot,
4145 text_x,
4146 &rows,
4147 line_layouts,
4148 editor_margins,
4149 line_height,
4150 em_width,
4151 text_hitbox,
4152 editor_width,
4153 scroll_width,
4154 &mut resized_blocks,
4155 &mut row_block_types,
4156 selections,
4157 selected_buffer_ids,
4158 latest_selection_anchors,
4159 is_row_soft_wrapped,
4160 sticky_header_excerpt_id,
4161 &mut block_resize_offset,
4162 window,
4163 cx,
4164 ) {
4165 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
4166 blocks.push(BlockLayout {
4167 id: block_id,
4168 x_offset,
4169 row: Some(row),
4170 element,
4171 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
4172 style: BlockStyle::Fixed,
4173 overlaps_gutter: true,
4174 is_buffer_header: block.is_buffer_header(),
4175 });
4176 }
4177 }
4178
4179 for (row, block) in non_fixed_blocks {
4180 let style = block.style();
4181 let width = match (style, block.place_near()) {
4182 (_, true) => AvailableSpace::MinContent,
4183 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
4184 (BlockStyle::Flex, _) => hitbox
4185 .size
4186 .width
4187 .max(fixed_block_max_width)
4188 .max(editor_margins.gutter.width + *scroll_width)
4189 .into(),
4190 (BlockStyle::Fixed, _) => unreachable!(),
4191 };
4192 let block_id = block.id();
4193
4194 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4195 focused_block = None;
4196 }
4197
4198 if let Some((element, element_size, row, x_offset)) = self.render_block(
4199 block,
4200 width,
4201 block_id,
4202 row,
4203 snapshot,
4204 text_x,
4205 &rows,
4206 line_layouts,
4207 editor_margins,
4208 line_height,
4209 em_width,
4210 text_hitbox,
4211 editor_width,
4212 scroll_width,
4213 &mut resized_blocks,
4214 &mut row_block_types,
4215 selections,
4216 selected_buffer_ids,
4217 latest_selection_anchors,
4218 is_row_soft_wrapped,
4219 sticky_header_excerpt_id,
4220 &mut block_resize_offset,
4221 window,
4222 cx,
4223 ) {
4224 blocks.push(BlockLayout {
4225 id: block_id,
4226 x_offset,
4227 row: Some(row),
4228 element,
4229 available_space: size(width, element_size.height.into()),
4230 style,
4231 overlaps_gutter: !block.place_near(),
4232 is_buffer_header: block.is_buffer_header(),
4233 });
4234 }
4235 }
4236
4237 if let Some(focused_block) = focused_block
4238 && let Some(focus_handle) = focused_block.focus_handle.upgrade()
4239 && focus_handle.is_focused(window)
4240 && let Some(block) = snapshot.block_for_id(focused_block.id)
4241 {
4242 let style = block.style();
4243 let width = match style {
4244 BlockStyle::Fixed => AvailableSpace::MinContent,
4245 BlockStyle::Flex => AvailableSpace::Definite(
4246 hitbox
4247 .size
4248 .width
4249 .max(fixed_block_max_width)
4250 .max(editor_margins.gutter.width + *scroll_width),
4251 ),
4252 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
4253 };
4254
4255 if let Some((element, element_size, _, x_offset)) = self.render_block(
4256 &block,
4257 width,
4258 focused_block.id,
4259 rows.end,
4260 snapshot,
4261 text_x,
4262 &rows,
4263 line_layouts,
4264 editor_margins,
4265 line_height,
4266 em_width,
4267 text_hitbox,
4268 editor_width,
4269 scroll_width,
4270 &mut resized_blocks,
4271 &mut row_block_types,
4272 selections,
4273 selected_buffer_ids,
4274 latest_selection_anchors,
4275 is_row_soft_wrapped,
4276 sticky_header_excerpt_id,
4277 &mut block_resize_offset,
4278 window,
4279 cx,
4280 ) {
4281 blocks.push(BlockLayout {
4282 id: block.id(),
4283 x_offset,
4284 row: None,
4285 element,
4286 available_space: size(width, element_size.height.into()),
4287 style,
4288 overlaps_gutter: true,
4289 is_buffer_header: block.is_buffer_header(),
4290 });
4291 }
4292 }
4293
4294 if resized_blocks.is_empty() {
4295 *scroll_width =
4296 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
4297 }
4298
4299 RenderBlocksOutput {
4300 blocks,
4301 row_block_types,
4302 resized_blocks: (!resized_blocks.is_empty()).then_some(resized_blocks),
4303 }
4304 }
4305
4306 fn layout_blocks(
4307 &self,
4308 blocks: &mut Vec<BlockLayout>,
4309 hitbox: &Hitbox,
4310 line_height: Pixels,
4311 scroll_position: gpui::Point<ScrollOffset>,
4312 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4313 window: &mut Window,
4314 cx: &mut App,
4315 ) {
4316 for block in blocks {
4317 let mut origin = if let Some(row) = block.row {
4318 hitbox.origin
4319 + point(
4320 block.x_offset,
4321 Pixels::from(
4322 (row.as_f64() - scroll_position.y)
4323 * ScrollPixelOffset::from(line_height),
4324 ),
4325 )
4326 } else {
4327 // Position the block outside the visible area
4328 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
4329 };
4330
4331 if !matches!(block.style, BlockStyle::Sticky) {
4332 origin += point(Pixels::from(-scroll_pixel_position.x), Pixels::ZERO);
4333 }
4334
4335 let focus_handle =
4336 block
4337 .element
4338 .prepaint_as_root(origin, block.available_space, window, cx);
4339
4340 if let Some(focus_handle) = focus_handle {
4341 self.editor.update(cx, |editor, _cx| {
4342 editor.set_focused_block(FocusedBlock {
4343 id: block.id,
4344 focus_handle: focus_handle.downgrade(),
4345 });
4346 });
4347 }
4348 }
4349 }
4350
4351 fn layout_sticky_buffer_header(
4352 &self,
4353 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
4354 scroll_position: gpui::Point<ScrollOffset>,
4355 line_height: Pixels,
4356 right_margin: Pixels,
4357 snapshot: &EditorSnapshot,
4358 hitbox: &Hitbox,
4359 selected_buffer_ids: &Vec<BufferId>,
4360 blocks: &[BlockLayout],
4361 latest_selection_anchors: &HashMap<BufferId, Anchor>,
4362 window: &mut Window,
4363 cx: &mut App,
4364 ) -> AnyElement {
4365 let jump_data = header_jump_data(
4366 snapshot,
4367 DisplayRow(scroll_position.y as u32),
4368 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4369 excerpt,
4370 latest_selection_anchors,
4371 );
4372
4373 let editor_bg_color = cx.theme().colors().editor_background;
4374
4375 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4376
4377 let available_width = hitbox.bounds.size.width - right_margin;
4378
4379 let mut header = v_flex()
4380 .w_full()
4381 .relative()
4382 .child(
4383 div()
4384 .w(available_width)
4385 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4386 .bg(linear_gradient(
4387 0.,
4388 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4389 linear_color_stop(editor_bg_color, 0.6),
4390 ))
4391 .absolute()
4392 .top_0(),
4393 )
4394 .child(
4395 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4396 .into_any_element(),
4397 )
4398 .into_any_element();
4399
4400 let mut origin = hitbox.origin;
4401 // Move floating header up to avoid colliding with the next buffer header.
4402 for block in blocks.iter() {
4403 if !block.is_buffer_header {
4404 continue;
4405 }
4406
4407 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position.y as u32) else {
4408 continue;
4409 };
4410
4411 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4412 let offset = scroll_position.y - max_row as f64;
4413
4414 if offset > 0.0 {
4415 origin.y -= Pixels::from(offset * ScrollPixelOffset::from(line_height));
4416 }
4417 break;
4418 }
4419
4420 let size = size(
4421 AvailableSpace::Definite(available_width),
4422 AvailableSpace::MinContent,
4423 );
4424
4425 header.prepaint_as_root(origin, size, window, cx);
4426
4427 header
4428 }
4429
4430 fn layout_sticky_headers(
4431 &self,
4432 snapshot: &EditorSnapshot,
4433 editor_width: Pixels,
4434 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4435 line_height: Pixels,
4436 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4437 content_origin: gpui::Point<Pixels>,
4438 gutter_dimensions: &GutterDimensions,
4439 gutter_hitbox: &Hitbox,
4440 text_hitbox: &Hitbox,
4441 style: &EditorStyle,
4442 relative_line_numbers: RelativeLineNumbers,
4443 relative_to: Option<DisplayRow>,
4444 window: &mut Window,
4445 cx: &mut App,
4446 ) -> Option<StickyHeaders> {
4447 let show_line_numbers = snapshot
4448 .show_line_numbers
4449 .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
4450
4451 let rows = Self::sticky_headers(self.editor.read(cx), snapshot, style, cx);
4452
4453 let mut lines = Vec::<StickyHeaderLine>::new();
4454
4455 for StickyHeader {
4456 item,
4457 sticky_row,
4458 start_point,
4459 offset,
4460 } in rows.into_iter().rev()
4461 {
4462 let line = layout_line(
4463 sticky_row,
4464 snapshot,
4465 &self.style,
4466 editor_width,
4467 is_row_soft_wrapped,
4468 window,
4469 cx,
4470 );
4471
4472 let line_number = show_line_numbers.then(|| {
4473 let start_display_row = start_point.to_display_point(snapshot).row();
4474 let relative_number = relative_to
4475 .filter(|_| relative_line_numbers != RelativeLineNumbers::Disabled)
4476 .map(|base| {
4477 snapshot.relative_line_delta(
4478 base,
4479 start_display_row,
4480 relative_line_numbers == RelativeLineNumbers::Wrapped,
4481 )
4482 });
4483 let number = relative_number
4484 .filter(|&delta| delta != 0)
4485 .map(|delta| delta.unsigned_abs() as u32)
4486 .unwrap_or(start_point.row + 1);
4487 let color = cx.theme().colors().editor_line_number;
4488 self.shape_line_number(SharedString::from(number.to_string()), color, window)
4489 });
4490
4491 lines.push(StickyHeaderLine::new(
4492 sticky_row,
4493 line_height * offset as f32,
4494 line,
4495 line_number,
4496 item.range.start,
4497 line_height,
4498 scroll_pixel_position,
4499 content_origin,
4500 gutter_hitbox,
4501 text_hitbox,
4502 window,
4503 cx,
4504 ));
4505 }
4506
4507 lines.reverse();
4508 if lines.is_empty() {
4509 return None;
4510 }
4511
4512 Some(StickyHeaders {
4513 lines,
4514 gutter_background: cx.theme().colors().editor_gutter_background,
4515 content_background: self.style.background,
4516 gutter_right_padding: gutter_dimensions.right_padding,
4517 })
4518 }
4519
4520 pub(crate) fn sticky_headers(
4521 editor: &Editor,
4522 snapshot: &EditorSnapshot,
4523 style: &EditorStyle,
4524 cx: &App,
4525 ) -> Vec<StickyHeader> {
4526 let scroll_top = snapshot.scroll_position().y;
4527
4528 let mut end_rows = Vec::<DisplayRow>::new();
4529 let mut rows = Vec::<StickyHeader>::new();
4530
4531 let items = editor
4532 .sticky_headers(&snapshot.display_snapshot, style, cx)
4533 .unwrap_or_default();
4534
4535 for item in items {
4536 let start_point = item.range.start.to_point(snapshot.buffer_snapshot());
4537 let end_point = item.range.end.to_point(snapshot.buffer_snapshot());
4538
4539 let sticky_row = snapshot
4540 .display_snapshot
4541 .point_to_display_point(start_point, Bias::Left)
4542 .row();
4543 let end_row = snapshot
4544 .display_snapshot
4545 .point_to_display_point(end_point, Bias::Left)
4546 .row();
4547 let max_sticky_row = end_row.previous_row();
4548 if max_sticky_row <= sticky_row {
4549 continue;
4550 }
4551
4552 while end_rows
4553 .last()
4554 .is_some_and(|&last_end| last_end <= sticky_row)
4555 {
4556 end_rows.pop();
4557 }
4558 let depth = end_rows.len();
4559 let adjusted_scroll_top = scroll_top + depth as f64;
4560
4561 if sticky_row.as_f64() >= adjusted_scroll_top || end_row.as_f64() <= adjusted_scroll_top
4562 {
4563 continue;
4564 }
4565
4566 let max_scroll_offset = max_sticky_row.as_f64() - scroll_top;
4567 let offset = (depth as f64).min(max_scroll_offset);
4568
4569 end_rows.push(end_row);
4570 rows.push(StickyHeader {
4571 item,
4572 sticky_row,
4573 start_point,
4574 offset,
4575 });
4576 }
4577
4578 rows
4579 }
4580
4581 fn layout_cursor_popovers(
4582 &self,
4583 line_height: Pixels,
4584 text_hitbox: &Hitbox,
4585 content_origin: gpui::Point<Pixels>,
4586 right_margin: Pixels,
4587 start_row: DisplayRow,
4588 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4589 line_layouts: &[LineWithInvisibles],
4590 cursor: DisplayPoint,
4591 cursor_point: Point,
4592 style: &EditorStyle,
4593 window: &mut Window,
4594 cx: &mut App,
4595 ) -> Option<ContextMenuLayout> {
4596 let mut min_menu_height = Pixels::ZERO;
4597 let mut max_menu_height = Pixels::ZERO;
4598 let mut height_above_menu = Pixels::ZERO;
4599 let height_below_menu = Pixels::ZERO;
4600 let mut edit_prediction_popover_visible = false;
4601 let mut context_menu_visible = false;
4602 let context_menu_placement;
4603
4604 {
4605 let editor = self.editor.read(cx);
4606 if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
4607 {
4608 height_above_menu +=
4609 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4610 edit_prediction_popover_visible = true;
4611 }
4612
4613 if editor.context_menu_visible()
4614 && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
4615 {
4616 let (min_height_in_lines, max_height_in_lines) = editor
4617 .context_menu_options
4618 .as_ref()
4619 .map_or((3, 12), |options| {
4620 (options.min_entries_visible, options.max_entries_visible)
4621 });
4622
4623 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4624 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4625 context_menu_visible = true;
4626 }
4627 context_menu_placement = editor
4628 .context_menu_options
4629 .as_ref()
4630 .and_then(|options| options.placement.clone());
4631 }
4632
4633 let visible = edit_prediction_popover_visible || context_menu_visible;
4634 if !visible {
4635 return None;
4636 }
4637
4638 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4639 let target_position = content_origin
4640 + gpui::Point {
4641 x: cmp::max(
4642 px(0.),
4643 Pixels::from(
4644 ScrollPixelOffset::from(
4645 cursor_row_layout.x_for_index(cursor.column() as usize),
4646 ) - scroll_pixel_position.x,
4647 ),
4648 ),
4649 y: cmp::max(
4650 px(0.),
4651 Pixels::from(
4652 cursor.row().next_row().as_f64() * ScrollPixelOffset::from(line_height)
4653 - scroll_pixel_position.y,
4654 ),
4655 ),
4656 };
4657
4658 let viewport_bounds =
4659 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4660 right: -right_margin - MENU_GAP,
4661 ..Default::default()
4662 });
4663
4664 let min_height = height_above_menu + min_menu_height + height_below_menu;
4665 let max_height = height_above_menu + max_menu_height + height_below_menu;
4666 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4667 target_position,
4668 line_height,
4669 min_height,
4670 max_height,
4671 context_menu_placement,
4672 text_hitbox,
4673 viewport_bounds,
4674 window,
4675 cx,
4676 |height, max_width_for_stable_x, y_flipped, window, cx| {
4677 // First layout the menu to get its size - others can be at least this wide.
4678 let context_menu = if context_menu_visible {
4679 let menu_height = if y_flipped {
4680 height - height_below_menu
4681 } else {
4682 height - height_above_menu
4683 };
4684 let mut element = self
4685 .render_context_menu(line_height, menu_height, window, cx)
4686 .expect("Visible context menu should always render.");
4687 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4688 Some((CursorPopoverType::CodeContextMenu, element, size))
4689 } else {
4690 None
4691 };
4692 let min_width = context_menu
4693 .as_ref()
4694 .map_or(px(0.), |(_, _, size)| size.width);
4695 let max_width = max_width_for_stable_x.max(
4696 context_menu
4697 .as_ref()
4698 .map_or(px(0.), |(_, _, size)| size.width),
4699 );
4700
4701 let edit_prediction = if edit_prediction_popover_visible {
4702 self.editor.update(cx, move |editor, cx| {
4703 let accept_binding = editor.accept_edit_prediction_keybind(
4704 EditPredictionGranularity::Full,
4705 window,
4706 cx,
4707 );
4708 let mut element = editor.render_edit_prediction_cursor_popover(
4709 min_width,
4710 max_width,
4711 cursor_point,
4712 style,
4713 accept_binding.keystroke(),
4714 window,
4715 cx,
4716 )?;
4717 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4718 Some((CursorPopoverType::EditPrediction, element, size))
4719 })
4720 } else {
4721 None
4722 };
4723 vec![edit_prediction, context_menu]
4724 .into_iter()
4725 .flatten()
4726 .collect::<Vec<_>>()
4727 },
4728 )?;
4729
4730 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4731 .iter()
4732 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4733 let last_ix = laid_out_popovers.len() - 1;
4734 let menu_is_last = menu_ix == last_ix;
4735 let first_popover_bounds = laid_out_popovers[0].1;
4736 let last_popover_bounds = laid_out_popovers[last_ix].1;
4737
4738 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4739 // right, and otherwise it goes below or to the right.
4740 let mut target_bounds = Bounds::from_corners(
4741 first_popover_bounds.origin,
4742 last_popover_bounds.bottom_right(),
4743 );
4744 target_bounds.size.width = menu_bounds.size.width;
4745
4746 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4747 // based on this is preferred for layout stability.
4748 let mut max_target_bounds = target_bounds;
4749 max_target_bounds.size.height = max_height;
4750 if y_flipped {
4751 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4752 }
4753
4754 // Add spacing around `target_bounds` and `max_target_bounds`.
4755 let mut extend_amount = Edges::all(MENU_GAP);
4756 if y_flipped {
4757 extend_amount.bottom = line_height;
4758 } else {
4759 extend_amount.top = line_height;
4760 }
4761 let target_bounds = target_bounds.extend(extend_amount);
4762 let max_target_bounds = max_target_bounds.extend(extend_amount);
4763
4764 let must_place_above_or_below =
4765 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4766 laid_out_popovers[menu_ix + 1..]
4767 .iter()
4768 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4769 } else {
4770 false
4771 };
4772
4773 let aside_bounds = self.layout_context_menu_aside(
4774 y_flipped,
4775 *menu_bounds,
4776 target_bounds,
4777 max_target_bounds,
4778 max_menu_height,
4779 must_place_above_or_below,
4780 text_hitbox,
4781 viewport_bounds,
4782 window,
4783 cx,
4784 );
4785
4786 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4787 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4788 Some(*bounds)
4789 } else {
4790 None
4791 }
4792 }) {
4793 let bounds = if let Some(aside_bounds) = aside_bounds {
4794 menu_bounds.union(&aside_bounds)
4795 } else {
4796 menu_bounds
4797 };
4798 return Some(ContextMenuLayout { y_flipped, bounds });
4799 }
4800
4801 None
4802 }
4803
4804 fn layout_gutter_menu(
4805 &self,
4806 line_height: Pixels,
4807 text_hitbox: &Hitbox,
4808 content_origin: gpui::Point<Pixels>,
4809 right_margin: Pixels,
4810 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4811 gutter_overshoot: Pixels,
4812 window: &mut Window,
4813 cx: &mut App,
4814 ) {
4815 let editor = self.editor.read(cx);
4816 if !editor.context_menu_visible() {
4817 return;
4818 }
4819 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4820 editor.context_menu_origin()
4821 else {
4822 return;
4823 };
4824 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4825 // indicator than just a plain first column of the text field.
4826 let target_position = content_origin
4827 + gpui::Point {
4828 x: -gutter_overshoot,
4829 y: Pixels::from(
4830 gutter_row.next_row().as_f64() * ScrollPixelOffset::from(line_height)
4831 - scroll_pixel_position.y,
4832 ),
4833 };
4834
4835 let (min_height_in_lines, max_height_in_lines) = editor
4836 .context_menu_options
4837 .as_ref()
4838 .map_or((3, 12), |options| {
4839 (options.min_entries_visible, options.max_entries_visible)
4840 });
4841
4842 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4843 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4844 let viewport_bounds =
4845 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4846 right: -right_margin - MENU_GAP,
4847 ..Default::default()
4848 });
4849 self.layout_popovers_above_or_below_line(
4850 target_position,
4851 line_height,
4852 min_height,
4853 max_height,
4854 editor
4855 .context_menu_options
4856 .as_ref()
4857 .and_then(|options| options.placement.clone()),
4858 text_hitbox,
4859 viewport_bounds,
4860 window,
4861 cx,
4862 move |height, _max_width_for_stable_x, _, window, cx| {
4863 let mut element = self
4864 .render_context_menu(line_height, height, window, cx)
4865 .expect("Visible context menu should always render.");
4866 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4867 vec![(CursorPopoverType::CodeContextMenu, element, size)]
4868 },
4869 );
4870 }
4871
4872 fn layout_popovers_above_or_below_line(
4873 &self,
4874 target_position: gpui::Point<Pixels>,
4875 line_height: Pixels,
4876 min_height: Pixels,
4877 max_height: Pixels,
4878 placement: Option<ContextMenuPlacement>,
4879 text_hitbox: &Hitbox,
4880 viewport_bounds: Bounds<Pixels>,
4881 window: &mut Window,
4882 cx: &mut App,
4883 make_sized_popovers: impl FnOnce(
4884 Pixels,
4885 Pixels,
4886 bool,
4887 &mut Window,
4888 &mut App,
4889 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
4890 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
4891 let text_style = TextStyleRefinement {
4892 line_height: Some(DefiniteLength::Fraction(
4893 BufferLineHeight::Comfortable.value(),
4894 )),
4895 ..Default::default()
4896 };
4897 window.with_text_style(Some(text_style), |window| {
4898 // If the max height won't fit below and there is more space above, put it above the line.
4899 let bottom_y_when_flipped = target_position.y - line_height;
4900 let available_above = bottom_y_when_flipped - text_hitbox.top();
4901 let available_below = text_hitbox.bottom() - target_position.y;
4902 let y_overflows_below = max_height > available_below;
4903 let mut y_flipped = match placement {
4904 Some(ContextMenuPlacement::Above) => true,
4905 Some(ContextMenuPlacement::Below) => false,
4906 None => y_overflows_below && available_above > available_below,
4907 };
4908 let mut height = cmp::min(
4909 max_height,
4910 if y_flipped {
4911 available_above
4912 } else {
4913 available_below
4914 },
4915 );
4916
4917 // If the min height doesn't fit within text bounds, instead fit within the window.
4918 if height < min_height {
4919 let available_above = bottom_y_when_flipped;
4920 let available_below = viewport_bounds.bottom() - target_position.y;
4921 let (y_flipped_override, height_override) = match placement {
4922 Some(ContextMenuPlacement::Above) => {
4923 (true, cmp::min(available_above, min_height))
4924 }
4925 Some(ContextMenuPlacement::Below) => {
4926 (false, cmp::min(available_below, min_height))
4927 }
4928 None => {
4929 if available_below > min_height {
4930 (false, min_height)
4931 } else if available_above > min_height {
4932 (true, min_height)
4933 } else if available_above > available_below {
4934 (true, available_above)
4935 } else {
4936 (false, available_below)
4937 }
4938 }
4939 };
4940 y_flipped = y_flipped_override;
4941 height = height_override;
4942 }
4943
4944 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
4945
4946 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
4947 // for very narrow windows.
4948 let popovers =
4949 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
4950 if popovers.is_empty() {
4951 return None;
4952 }
4953
4954 let max_width = popovers
4955 .iter()
4956 .map(|(_, _, size)| size.width)
4957 .max()
4958 .unwrap_or_default();
4959
4960 let mut current_position = gpui::Point {
4961 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
4962 // overflow. Include space for the scrollbar.
4963 x: target_position
4964 .x
4965 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
4966 y: if y_flipped {
4967 bottom_y_when_flipped
4968 } else {
4969 target_position.y
4970 },
4971 };
4972
4973 let mut laid_out_popovers = popovers
4974 .into_iter()
4975 .map(|(popover_type, element, size)| {
4976 if y_flipped {
4977 current_position.y -= size.height;
4978 }
4979 let position = current_position;
4980 window.defer_draw(element, current_position, 1);
4981 if !y_flipped {
4982 current_position.y += size.height + MENU_GAP;
4983 } else {
4984 current_position.y -= MENU_GAP;
4985 }
4986 (popover_type, Bounds::new(position, size))
4987 })
4988 .collect::<Vec<_>>();
4989
4990 if y_flipped {
4991 laid_out_popovers.reverse();
4992 }
4993
4994 Some((laid_out_popovers, y_flipped))
4995 })
4996 }
4997
4998 fn layout_context_menu_aside(
4999 &self,
5000 y_flipped: bool,
5001 menu_bounds: Bounds<Pixels>,
5002 target_bounds: Bounds<Pixels>,
5003 max_target_bounds: Bounds<Pixels>,
5004 max_height: Pixels,
5005 must_place_above_or_below: bool,
5006 text_hitbox: &Hitbox,
5007 viewport_bounds: Bounds<Pixels>,
5008 window: &mut Window,
5009 cx: &mut App,
5010 ) -> Option<Bounds<Pixels>> {
5011 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
5012 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
5013 && !must_place_above_or_below
5014 {
5015 let max_width = cmp::min(
5016 available_within_viewport.right - px(1.),
5017 MENU_ASIDE_MAX_WIDTH,
5018 );
5019 let mut aside = self.render_context_menu_aside(
5020 size(max_width, max_height - POPOVER_Y_PADDING),
5021 window,
5022 cx,
5023 )?;
5024 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5025 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
5026 Some((aside, right_position, size))
5027 } else {
5028 let max_size = size(
5029 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
5030 // won't be needed here.
5031 cmp::min(
5032 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
5033 viewport_bounds.right(),
5034 ),
5035 cmp::min(
5036 max_height,
5037 cmp::max(
5038 available_within_viewport.top,
5039 available_within_viewport.bottom,
5040 ),
5041 ) - POPOVER_Y_PADDING,
5042 );
5043 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
5044 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5045
5046 let top_position = point(
5047 menu_bounds.origin.x,
5048 target_bounds.top() - actual_size.height,
5049 );
5050 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
5051
5052 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
5053 // Prefer to fit on the same side of the line as the menu, then on the other side of
5054 // the line.
5055 if !y_flipped && wanted.height < available.bottom {
5056 Some(bottom_position)
5057 } else if !y_flipped && wanted.height < available.top {
5058 Some(top_position)
5059 } else if y_flipped && wanted.height < available.top {
5060 Some(top_position)
5061 } else if y_flipped && wanted.height < available.bottom {
5062 Some(bottom_position)
5063 } else {
5064 None
5065 }
5066 };
5067
5068 // Prefer choosing a direction using max sizes rather than actual size for stability.
5069 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
5070 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
5071 let aside_position = fit_within(available_within_text, wanted)
5072 // Fallback: fit max size in window.
5073 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
5074 // Fallback: fit actual size in window.
5075 .or_else(|| fit_within(available_within_viewport, actual_size));
5076
5077 aside_position.map(|position| (aside, position, actual_size))
5078 };
5079
5080 // Skip drawing if it doesn't fit anywhere.
5081 if let Some((aside, position, size)) = positioned_aside {
5082 let aside_bounds = Bounds::new(position, size);
5083 window.defer_draw(aside, position, 2);
5084 return Some(aside_bounds);
5085 }
5086
5087 None
5088 }
5089
5090 fn render_context_menu(
5091 &self,
5092 line_height: Pixels,
5093 height: Pixels,
5094 window: &mut Window,
5095 cx: &mut App,
5096 ) -> Option<AnyElement> {
5097 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
5098 self.editor.update(cx, |editor, cx| {
5099 editor.render_context_menu(max_height_in_lines, window, cx)
5100 })
5101 }
5102
5103 fn render_context_menu_aside(
5104 &self,
5105 max_size: Size<Pixels>,
5106 window: &mut Window,
5107 cx: &mut App,
5108 ) -> Option<AnyElement> {
5109 if max_size.width < px(100.) || max_size.height < px(12.) {
5110 None
5111 } else {
5112 self.editor.update(cx, |editor, cx| {
5113 editor.render_context_menu_aside(max_size, window, cx)
5114 })
5115 }
5116 }
5117
5118 fn layout_mouse_context_menu(
5119 &self,
5120 editor_snapshot: &EditorSnapshot,
5121 visible_range: Range<DisplayRow>,
5122 content_origin: gpui::Point<Pixels>,
5123 window: &mut Window,
5124 cx: &mut App,
5125 ) -> Option<AnyElement> {
5126 let position = self.editor.update(cx, |editor, cx| {
5127 let visible_start_point = editor.display_to_pixel_point(
5128 DisplayPoint::new(visible_range.start, 0),
5129 editor_snapshot,
5130 window,
5131 cx,
5132 )?;
5133 let visible_end_point = editor.display_to_pixel_point(
5134 DisplayPoint::new(visible_range.end, 0),
5135 editor_snapshot,
5136 window,
5137 cx,
5138 )?;
5139
5140 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5141 let (source_display_point, position) = match mouse_context_menu.position {
5142 MenuPosition::PinnedToScreen(point) => (None, point),
5143 MenuPosition::PinnedToEditor { source, offset } => {
5144 let source_display_point = source.to_display_point(editor_snapshot);
5145 let source_point =
5146 editor.to_pixel_point(source, editor_snapshot, window, cx)?;
5147 let position = content_origin + source_point + offset;
5148 (Some(source_display_point), position)
5149 }
5150 };
5151
5152 let source_included = source_display_point.is_none_or(|source_display_point| {
5153 visible_range
5154 .to_inclusive()
5155 .contains(&source_display_point.row())
5156 });
5157 let position_included =
5158 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
5159 if !source_included && !position_included {
5160 None
5161 } else {
5162 Some(position)
5163 }
5164 })?;
5165
5166 let text_style = TextStyleRefinement {
5167 line_height: Some(DefiniteLength::Fraction(
5168 BufferLineHeight::Comfortable.value(),
5169 )),
5170 ..Default::default()
5171 };
5172 window.with_text_style(Some(text_style), |window| {
5173 let mut element = self.editor.read_with(cx, |editor, _| {
5174 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5175 let context_menu = mouse_context_menu.context_menu.clone();
5176
5177 Some(
5178 deferred(
5179 anchored()
5180 .position(position)
5181 .child(context_menu)
5182 .anchor(Corner::TopLeft)
5183 .snap_to_window_with_margin(px(8.)),
5184 )
5185 .with_priority(1)
5186 .into_any(),
5187 )
5188 })?;
5189
5190 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
5191 Some(element)
5192 })
5193 }
5194
5195 fn layout_hover_popovers(
5196 &self,
5197 snapshot: &EditorSnapshot,
5198 hitbox: &Hitbox,
5199 visible_display_row_range: Range<DisplayRow>,
5200 content_origin: gpui::Point<Pixels>,
5201 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5202 line_layouts: &[LineWithInvisibles],
5203 line_height: Pixels,
5204 em_width: Pixels,
5205 context_menu_layout: Option<ContextMenuLayout>,
5206 window: &mut Window,
5207 cx: &mut App,
5208 ) {
5209 struct MeasuredHoverPopover {
5210 element: AnyElement,
5211 size: Size<Pixels>,
5212 horizontal_offset: Pixels,
5213 }
5214
5215 let max_size = size(
5216 (120. * em_width) // Default size
5217 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5218 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5219 (16. * line_height) // Default size
5220 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5221 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5222 );
5223
5224 // Don't show hover popovers when context menu is open to avoid overlap
5225 let has_context_menu = self.editor.read(cx).mouse_context_menu.is_some();
5226 if has_context_menu {
5227 return;
5228 }
5229
5230 let hover_popovers = self.editor.update(cx, |editor, cx| {
5231 editor.hover_state.render(
5232 snapshot,
5233 visible_display_row_range.clone(),
5234 max_size,
5235 &editor.text_layout_details(window, cx),
5236 window,
5237 cx,
5238 )
5239 });
5240 let Some((popover_position, hover_popovers)) = hover_popovers else {
5241 return;
5242 };
5243
5244 // This is safe because we check on layout whether the required row is available
5245 let hovered_row_layout = &line_layouts[popover_position
5246 .row()
5247 .minus(visible_display_row_range.start)
5248 as usize];
5249
5250 // Compute Hovered Point
5251 let x = hovered_row_layout.x_for_index(popover_position.column() as usize)
5252 - Pixels::from(scroll_pixel_position.x);
5253 let y = Pixels::from(
5254 popover_position.row().as_f64() * ScrollPixelOffset::from(line_height)
5255 - scroll_pixel_position.y,
5256 );
5257 let hovered_point = content_origin + point(x, y);
5258
5259 let mut overall_height = Pixels::ZERO;
5260 let mut measured_hover_popovers = Vec::new();
5261 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
5262 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
5263 let horizontal_offset =
5264 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
5265 .min(Pixels::ZERO);
5266 match position {
5267 itertools::Position::Middle | itertools::Position::Last => {
5268 overall_height += HOVER_POPOVER_GAP
5269 }
5270 _ => {}
5271 }
5272 overall_height += size.height;
5273 measured_hover_popovers.push(MeasuredHoverPopover {
5274 element: hover_popover,
5275 size,
5276 horizontal_offset,
5277 });
5278 }
5279
5280 fn draw_occluder(
5281 width: Pixels,
5282 origin: gpui::Point<Pixels>,
5283 window: &mut Window,
5284 cx: &mut App,
5285 ) {
5286 let mut occlusion = div()
5287 .size_full()
5288 .occlude()
5289 .on_mouse_move(|_, _, cx| cx.stop_propagation())
5290 .into_any_element();
5291 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
5292 window.defer_draw(occlusion, origin, 2);
5293 }
5294
5295 fn place_popovers_above(
5296 hovered_point: gpui::Point<Pixels>,
5297 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5298 window: &mut Window,
5299 cx: &mut App,
5300 ) {
5301 let mut current_y = hovered_point.y;
5302 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5303 let size = popover.size;
5304 let popover_origin = point(
5305 hovered_point.x + popover.horizontal_offset,
5306 current_y - size.height,
5307 );
5308
5309 window.defer_draw(popover.element, popover_origin, 2);
5310 if position != itertools::Position::Last {
5311 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
5312 draw_occluder(size.width, origin, window, cx);
5313 }
5314
5315 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5316 }
5317 }
5318
5319 fn place_popovers_below(
5320 hovered_point: gpui::Point<Pixels>,
5321 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5322 line_height: Pixels,
5323 window: &mut Window,
5324 cx: &mut App,
5325 ) {
5326 let mut current_y = hovered_point.y + line_height;
5327 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5328 let size = popover.size;
5329 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5330
5331 window.defer_draw(popover.element, popover_origin, 2);
5332 if position != itertools::Position::Last {
5333 let origin = point(popover_origin.x, popover_origin.y + size.height);
5334 draw_occluder(size.width, origin, window, cx);
5335 }
5336
5337 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5338 }
5339 }
5340
5341 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5342 context_menu_layout
5343 .as_ref()
5344 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5345 };
5346
5347 let can_place_above = {
5348 let mut bounds_above = Vec::new();
5349 let mut current_y = hovered_point.y;
5350 for popover in &measured_hover_popovers {
5351 let size = popover.size;
5352 let popover_origin = point(
5353 hovered_point.x + popover.horizontal_offset,
5354 current_y - size.height,
5355 );
5356 bounds_above.push(Bounds::new(popover_origin, size));
5357 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5358 }
5359 bounds_above
5360 .iter()
5361 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5362 };
5363
5364 let can_place_below = || {
5365 let mut bounds_below = Vec::new();
5366 let mut current_y = hovered_point.y + line_height;
5367 for popover in &measured_hover_popovers {
5368 let size = popover.size;
5369 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5370 bounds_below.push(Bounds::new(popover_origin, size));
5371 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5372 }
5373 bounds_below
5374 .iter()
5375 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5376 };
5377
5378 if can_place_above {
5379 // try placing above hovered point
5380 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5381 } else if can_place_below() {
5382 // try placing below hovered point
5383 place_popovers_below(
5384 hovered_point,
5385 measured_hover_popovers,
5386 line_height,
5387 window,
5388 cx,
5389 );
5390 } else {
5391 // try to place popovers around the context menu
5392 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5393 let total_width = measured_hover_popovers
5394 .iter()
5395 .map(|p| p.size.width)
5396 .max()
5397 .unwrap_or(Pixels::ZERO);
5398 let y_for_horizontal_positioning = if menu.y_flipped {
5399 menu.bounds.bottom() - overall_height
5400 } else {
5401 menu.bounds.top()
5402 };
5403 let possible_origins = vec![
5404 // left of context menu
5405 point(
5406 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
5407 y_for_horizontal_positioning,
5408 ),
5409 // right of context menu
5410 point(
5411 menu.bounds.right() + HOVER_POPOVER_GAP,
5412 y_for_horizontal_positioning,
5413 ),
5414 // top of context menu
5415 point(
5416 menu.bounds.left(),
5417 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
5418 ),
5419 // bottom of context menu
5420 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5421 ];
5422 possible_origins.into_iter().find(|&origin| {
5423 Bounds::new(origin, size(total_width, overall_height))
5424 .is_contained_within(hitbox)
5425 })
5426 });
5427 if let Some(origin) = origin_surrounding_menu {
5428 let mut current_y = origin.y;
5429 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5430 let size = popover.size;
5431 let popover_origin = point(origin.x, current_y);
5432
5433 window.defer_draw(popover.element, popover_origin, 2);
5434 if position != itertools::Position::Last {
5435 let origin = point(popover_origin.x, popover_origin.y + size.height);
5436 draw_occluder(size.width, origin, window, cx);
5437 }
5438
5439 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5440 }
5441 } else {
5442 // fallback to existing above/below cursor logic
5443 // this might overlap menu or overflow in rare case
5444 if can_place_above {
5445 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5446 } else {
5447 place_popovers_below(
5448 hovered_point,
5449 measured_hover_popovers,
5450 line_height,
5451 window,
5452 cx,
5453 );
5454 }
5455 }
5456 }
5457 }
5458
5459 fn layout_word_diff_highlights(
5460 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5461 row_infos: &[RowInfo],
5462 start_row: DisplayRow,
5463 snapshot: &EditorSnapshot,
5464 highlighted_ranges: &mut Vec<(Range<DisplayPoint>, Hsla)>,
5465 cx: &mut App,
5466 ) {
5467 let colors = cx.theme().colors();
5468
5469 let word_highlights = display_hunks
5470 .into_iter()
5471 .filter_map(|(hunk, _)| match hunk {
5472 DisplayDiffHunk::Unfolded {
5473 word_diffs, status, ..
5474 } => Some((word_diffs, status)),
5475 _ => None,
5476 })
5477 .filter(|(_, status)| status.is_modified())
5478 .flat_map(|(word_diffs, _)| word_diffs)
5479 .filter_map(|word_diff| {
5480 let start_point = word_diff.start.to_display_point(&snapshot.display_snapshot);
5481 let end_point = word_diff.end.to_display_point(&snapshot.display_snapshot);
5482 let start_row_offset = start_point.row().0.saturating_sub(start_row.0) as usize;
5483
5484 row_infos
5485 .get(start_row_offset)
5486 .and_then(|row_info| row_info.diff_status)
5487 .and_then(|diff_status| {
5488 let background_color = match diff_status.kind {
5489 DiffHunkStatusKind::Added => colors.version_control_word_added,
5490 DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,
5491 DiffHunkStatusKind::Modified => {
5492 debug_panic!("modified diff status for row info");
5493 return None;
5494 }
5495 };
5496 Some((start_point..end_point, background_color))
5497 })
5498 });
5499
5500 highlighted_ranges.extend(word_highlights);
5501 }
5502
5503 fn layout_diff_hunk_controls(
5504 &self,
5505 row_range: Range<DisplayRow>,
5506 row_infos: &[RowInfo],
5507 text_hitbox: &Hitbox,
5508 newest_cursor_position: Option<DisplayPoint>,
5509 line_height: Pixels,
5510 right_margin: Pixels,
5511 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5512 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5513 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
5514 editor: Entity<Editor>,
5515 window: &mut Window,
5516 cx: &mut App,
5517 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
5518 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
5519 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
5520
5521 let mut controls = vec![];
5522 let mut control_bounds = vec![];
5523
5524 let active_positions = [
5525 hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
5526 newest_cursor_position,
5527 ];
5528
5529 for (hunk, _) in display_hunks {
5530 if let DisplayDiffHunk::Unfolded {
5531 display_row_range,
5532 multi_buffer_range,
5533 status,
5534 is_created_file,
5535 ..
5536 } = &hunk
5537 {
5538 if display_row_range.start < row_range.start
5539 || display_row_range.start >= row_range.end
5540 {
5541 continue;
5542 }
5543 if highlighted_rows
5544 .get(&display_row_range.start)
5545 .and_then(|highlight| highlight.type_id)
5546 .is_some_and(|type_id| {
5547 [
5548 TypeId::of::<ConflictsOuter>(),
5549 TypeId::of::<ConflictsOursMarker>(),
5550 TypeId::of::<ConflictsOurs>(),
5551 TypeId::of::<ConflictsTheirs>(),
5552 TypeId::of::<ConflictsTheirsMarker>(),
5553 ]
5554 .contains(&type_id)
5555 })
5556 {
5557 continue;
5558 }
5559 let row_ix = (display_row_range.start - row_range.start).0 as usize;
5560 if row_infos[row_ix].diff_status.is_none() {
5561 continue;
5562 }
5563
5564 if active_positions
5565 .iter()
5566 .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
5567 {
5568 let y = (display_row_range.start.as_f64()
5569 * ScrollPixelOffset::from(line_height)
5570 + ScrollPixelOffset::from(text_hitbox.bounds.top())
5571 - scroll_pixel_position.y)
5572 .into();
5573
5574 let mut element = render_diff_hunk_controls(
5575 display_row_range.start.0,
5576 status,
5577 multi_buffer_range.clone(),
5578 *is_created_file,
5579 line_height,
5580 &editor,
5581 window,
5582 cx,
5583 );
5584 let size =
5585 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5586
5587 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5588
5589 if x < text_hitbox.bounds.left() {
5590 continue;
5591 }
5592
5593 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5594 control_bounds.push((display_row_range.start, bounds));
5595
5596 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5597 element.prepaint(window, cx)
5598 });
5599 controls.push(element);
5600 }
5601 }
5602 }
5603
5604 (controls, control_bounds)
5605 }
5606
5607 fn layout_signature_help(
5608 &self,
5609 hitbox: &Hitbox,
5610 content_origin: gpui::Point<Pixels>,
5611 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5612 newest_selection_head: Option<DisplayPoint>,
5613 start_row: DisplayRow,
5614 line_layouts: &[LineWithInvisibles],
5615 line_height: Pixels,
5616 em_width: Pixels,
5617 context_menu_layout: Option<ContextMenuLayout>,
5618 window: &mut Window,
5619 cx: &mut App,
5620 ) {
5621 if !self.editor.focus_handle(cx).is_focused(window) {
5622 return;
5623 }
5624 let Some(newest_selection_head) = newest_selection_head else {
5625 return;
5626 };
5627
5628 let max_size = size(
5629 (120. * em_width) // Default size
5630 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5631 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5632 (16. * line_height) // Default size
5633 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5634 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5635 );
5636
5637 let maybe_element = self.editor.update(cx, |editor, cx| {
5638 if let Some(popover) = editor.signature_help_state.popover_mut() {
5639 let element = popover.render(max_size, window, cx);
5640 Some(element)
5641 } else {
5642 None
5643 }
5644 });
5645 let Some(mut element) = maybe_element else {
5646 return;
5647 };
5648
5649 let selection_row = newest_selection_head.row();
5650 let Some(cursor_row_layout) = (selection_row >= start_row)
5651 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5652 .flatten()
5653 else {
5654 return;
5655 };
5656
5657 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5658 - Pixels::from(scroll_pixel_position.x);
5659 let target_y = Pixels::from(
5660 selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
5661 );
5662 let target_point = content_origin + point(target_x, target_y);
5663
5664 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5665
5666 let (popover_bounds_above, popover_bounds_below) = {
5667 let horizontal_offset = (hitbox.top_right().x
5668 - POPOVER_RIGHT_OFFSET
5669 - (target_point.x + actual_size.width))
5670 .min(Pixels::ZERO);
5671 let initial_x = target_point.x + horizontal_offset;
5672 (
5673 Bounds::new(
5674 point(initial_x, target_point.y - actual_size.height),
5675 actual_size,
5676 ),
5677 Bounds::new(
5678 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5679 actual_size,
5680 ),
5681 )
5682 };
5683
5684 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5685 context_menu_layout
5686 .as_ref()
5687 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5688 };
5689
5690 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5691 && !intersects_menu(popover_bounds_above)
5692 {
5693 // try placing above cursor
5694 popover_bounds_above.origin
5695 } else if popover_bounds_below.is_contained_within(hitbox)
5696 && !intersects_menu(popover_bounds_below)
5697 {
5698 // try placing below cursor
5699 popover_bounds_below.origin
5700 } else {
5701 // try surrounding context menu if exists
5702 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5703 let y_for_horizontal_positioning = if menu.y_flipped {
5704 menu.bounds.bottom() - actual_size.height
5705 } else {
5706 menu.bounds.top()
5707 };
5708 let possible_origins = vec![
5709 // left of context menu
5710 point(
5711 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5712 y_for_horizontal_positioning,
5713 ),
5714 // right of context menu
5715 point(
5716 menu.bounds.right() + HOVER_POPOVER_GAP,
5717 y_for_horizontal_positioning,
5718 ),
5719 // top of context menu
5720 point(
5721 menu.bounds.left(),
5722 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5723 ),
5724 // bottom of context menu
5725 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5726 ];
5727 possible_origins
5728 .into_iter()
5729 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5730 });
5731 origin_surrounding_menu.unwrap_or_else(|| {
5732 // fallback to existing above/below cursor logic
5733 // this might overlap menu or overflow in rare case
5734 if popover_bounds_above.is_contained_within(hitbox) {
5735 popover_bounds_above.origin
5736 } else {
5737 popover_bounds_below.origin
5738 }
5739 })
5740 };
5741
5742 window.defer_draw(element, final_origin, 2);
5743 }
5744
5745 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5746 window.paint_layer(layout.hitbox.bounds, |window| {
5747 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5748 let gutter_bg = cx.theme().colors().editor_gutter_background;
5749 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5750 window.paint_quad(fill(
5751 layout.position_map.text_hitbox.bounds,
5752 self.style.background,
5753 ));
5754
5755 if matches!(
5756 layout.mode,
5757 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5758 ) {
5759 let show_active_line_background = match layout.mode {
5760 EditorMode::Full {
5761 show_active_line_background,
5762 ..
5763 } => show_active_line_background,
5764 EditorMode::Minimap { .. } => true,
5765 _ => false,
5766 };
5767 let mut active_rows = layout.active_rows.iter().peekable();
5768 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5769 let mut end_row = start_row.0;
5770 while active_rows
5771 .peek()
5772 .is_some_and(|(active_row, has_selection)| {
5773 active_row.0 == end_row + 1
5774 && has_selection.selection == contains_non_empty_selection.selection
5775 })
5776 {
5777 active_rows.next().unwrap();
5778 end_row += 1;
5779 }
5780
5781 if show_active_line_background && !contains_non_empty_selection.selection {
5782 let highlight_h_range =
5783 match layout.position_map.snapshot.current_line_highlight {
5784 CurrentLineHighlight::Gutter => Some(Range {
5785 start: layout.hitbox.left(),
5786 end: layout.gutter_hitbox.right(),
5787 }),
5788 CurrentLineHighlight::Line => Some(Range {
5789 start: layout.position_map.text_hitbox.bounds.left(),
5790 end: layout.position_map.text_hitbox.bounds.right(),
5791 }),
5792 CurrentLineHighlight::All => Some(Range {
5793 start: layout.hitbox.left(),
5794 end: layout.hitbox.right(),
5795 }),
5796 CurrentLineHighlight::None => None,
5797 };
5798 if let Some(range) = highlight_h_range {
5799 let active_line_bg = cx.theme().colors().editor_active_line_background;
5800 let bounds = Bounds {
5801 origin: point(
5802 range.start,
5803 layout.hitbox.origin.y
5804 + Pixels::from(
5805 (start_row.as_f64() - scroll_top)
5806 * ScrollPixelOffset::from(
5807 layout.position_map.line_height,
5808 ),
5809 ),
5810 ),
5811 size: size(
5812 range.end - range.start,
5813 layout.position_map.line_height
5814 * (end_row - start_row.0 + 1) as f32,
5815 ),
5816 };
5817 window.paint_quad(fill(bounds, active_line_bg));
5818 }
5819 }
5820 }
5821
5822 let mut paint_highlight = |highlight_row_start: DisplayRow,
5823 highlight_row_end: DisplayRow,
5824 highlight: crate::LineHighlight,
5825 edges| {
5826 let mut origin_x = layout.hitbox.left();
5827 let mut width = layout.hitbox.size.width;
5828 if !highlight.include_gutter {
5829 origin_x += layout.gutter_hitbox.size.width;
5830 width -= layout.gutter_hitbox.size.width;
5831 }
5832
5833 let origin = point(
5834 origin_x,
5835 layout.hitbox.origin.y
5836 + Pixels::from(
5837 (highlight_row_start.as_f64() - scroll_top)
5838 * ScrollPixelOffset::from(layout.position_map.line_height),
5839 ),
5840 );
5841 let size = size(
5842 width,
5843 layout.position_map.line_height
5844 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5845 );
5846 let mut quad = fill(Bounds { origin, size }, highlight.background);
5847 if let Some(border_color) = highlight.border {
5848 quad.border_color = border_color;
5849 quad.border_widths = edges
5850 }
5851 window.paint_quad(quad);
5852 };
5853
5854 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5855 None;
5856 for (&new_row, &new_background) in &layout.highlighted_rows {
5857 match &mut current_paint {
5858 &mut Some((current_background, ref mut current_range, mut edges)) => {
5859 let new_range_started = current_background != new_background
5860 || current_range.end.next_row() != new_row;
5861 if new_range_started {
5862 if current_range.end.next_row() == new_row {
5863 edges.bottom = px(0.);
5864 };
5865 paint_highlight(
5866 current_range.start,
5867 current_range.end,
5868 current_background,
5869 edges,
5870 );
5871 let edges = Edges {
5872 top: if current_range.end.next_row() != new_row {
5873 px(1.)
5874 } else {
5875 px(0.)
5876 },
5877 bottom: px(1.),
5878 ..Default::default()
5879 };
5880 current_paint = Some((new_background, new_row..new_row, edges));
5881 continue;
5882 } else {
5883 current_range.end = current_range.end.next_row();
5884 }
5885 }
5886 None => {
5887 let edges = Edges {
5888 top: px(1.),
5889 bottom: px(1.),
5890 ..Default::default()
5891 };
5892 current_paint = Some((new_background, new_row..new_row, edges))
5893 }
5894 };
5895 }
5896 if let Some((color, range, edges)) = current_paint {
5897 paint_highlight(range.start, range.end, color, edges);
5898 }
5899
5900 for (guide_x, active) in layout.wrap_guides.iter() {
5901 let color = if *active {
5902 cx.theme().colors().editor_active_wrap_guide
5903 } else {
5904 cx.theme().colors().editor_wrap_guide
5905 };
5906 window.paint_quad(fill(
5907 Bounds {
5908 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5909 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5910 },
5911 color,
5912 ));
5913 }
5914 }
5915 })
5916 }
5917
5918 fn paint_indent_guides(
5919 &mut self,
5920 layout: &mut EditorLayout,
5921 window: &mut Window,
5922 cx: &mut App,
5923 ) {
5924 let Some(indent_guides) = &layout.indent_guides else {
5925 return;
5926 };
5927
5928 let faded_color = |color: Hsla, alpha: f32| {
5929 let mut faded = color;
5930 faded.a = alpha;
5931 faded
5932 };
5933
5934 for indent_guide in indent_guides {
5935 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
5936 let settings = &indent_guide.settings;
5937
5938 // TODO fixed for now, expose them through themes later
5939 const INDENT_AWARE_ALPHA: f32 = 0.2;
5940 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
5941 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
5942 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
5943
5944 let line_color = match (settings.coloring, indent_guide.active) {
5945 (IndentGuideColoring::Disabled, _) => None,
5946 (IndentGuideColoring::Fixed, false) => {
5947 Some(cx.theme().colors().editor_indent_guide)
5948 }
5949 (IndentGuideColoring::Fixed, true) => {
5950 Some(cx.theme().colors().editor_indent_guide_active)
5951 }
5952 (IndentGuideColoring::IndentAware, false) => {
5953 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
5954 }
5955 (IndentGuideColoring::IndentAware, true) => {
5956 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
5957 }
5958 };
5959
5960 let background_color = match (settings.background_coloring, indent_guide.active) {
5961 (IndentGuideBackgroundColoring::Disabled, _) => None,
5962 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
5963 indent_accent_colors,
5964 INDENT_AWARE_BACKGROUND_ALPHA,
5965 )),
5966 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
5967 indent_accent_colors,
5968 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
5969 )),
5970 };
5971
5972 let requested_line_width = if indent_guide.active {
5973 settings.active_line_width
5974 } else {
5975 settings.line_width
5976 }
5977 .clamp(1, 10);
5978 let mut line_indicator_width = 0.;
5979 if let Some(color) = line_color {
5980 window.paint_quad(fill(
5981 Bounds {
5982 origin: indent_guide.origin,
5983 size: size(px(requested_line_width as f32), indent_guide.length),
5984 },
5985 color,
5986 ));
5987 line_indicator_width = requested_line_width as f32;
5988 }
5989
5990 if let Some(color) = background_color {
5991 let width = indent_guide.single_indent_width - px(line_indicator_width);
5992 window.paint_quad(fill(
5993 Bounds {
5994 origin: point(
5995 indent_guide.origin.x + px(line_indicator_width),
5996 indent_guide.origin.y,
5997 ),
5998 size: size(width, indent_guide.length),
5999 },
6000 color,
6001 ));
6002 }
6003 }
6004 }
6005
6006 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6007 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
6008
6009 let line_height = layout.position_map.line_height;
6010 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
6011
6012 for line_layout in layout.line_numbers.values() {
6013 for LineNumberSegment {
6014 shaped_line,
6015 hitbox,
6016 } in &line_layout.segments
6017 {
6018 let Some(hitbox) = hitbox else {
6019 continue;
6020 };
6021
6022 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
6023 let color = cx.theme().colors().editor_hover_line_number;
6024
6025 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
6026 line.paint(
6027 hitbox.origin,
6028 line_height,
6029 TextAlign::Left,
6030 None,
6031 window,
6032 cx,
6033 )
6034 .log_err()
6035 } else {
6036 shaped_line
6037 .paint(
6038 hitbox.origin,
6039 line_height,
6040 TextAlign::Left,
6041 None,
6042 window,
6043 cx,
6044 )
6045 .log_err()
6046 }) else {
6047 continue;
6048 };
6049
6050 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
6051 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
6052 if is_singleton {
6053 window.set_cursor_style(CursorStyle::IBeam, hitbox);
6054 } else {
6055 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
6056 }
6057 }
6058 }
6059 }
6060
6061 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6062 if layout.display_hunks.is_empty() {
6063 return;
6064 }
6065
6066 let line_height = layout.position_map.line_height;
6067 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6068 for (hunk, hitbox) in &layout.display_hunks {
6069 let hunk_to_paint = match hunk {
6070 DisplayDiffHunk::Folded { .. } => {
6071 let hunk_bounds = Self::diff_hunk_bounds(
6072 &layout.position_map.snapshot,
6073 line_height,
6074 layout.gutter_hitbox.bounds,
6075 hunk,
6076 );
6077 Some((
6078 hunk_bounds,
6079 cx.theme().colors().version_control_modified,
6080 Corners::all(px(0.)),
6081 DiffHunkStatus::modified_none(),
6082 ))
6083 }
6084 DisplayDiffHunk::Unfolded {
6085 status,
6086 display_row_range,
6087 ..
6088 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
6089 DiffHunkStatusKind::Added => (
6090 hunk_hitbox.bounds,
6091 cx.theme().colors().version_control_added,
6092 Corners::all(px(0.)),
6093 *status,
6094 ),
6095 DiffHunkStatusKind::Modified => (
6096 hunk_hitbox.bounds,
6097 cx.theme().colors().version_control_modified,
6098 Corners::all(px(0.)),
6099 *status,
6100 ),
6101 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
6102 hunk_hitbox.bounds,
6103 cx.theme().colors().version_control_deleted,
6104 Corners::all(px(0.)),
6105 *status,
6106 ),
6107 DiffHunkStatusKind::Deleted => (
6108 Bounds::new(
6109 point(
6110 hunk_hitbox.origin.x - hunk_hitbox.size.width,
6111 hunk_hitbox.origin.y,
6112 ),
6113 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
6114 ),
6115 cx.theme().colors().version_control_deleted,
6116 Corners::all(1. * line_height),
6117 *status,
6118 ),
6119 }),
6120 };
6121
6122 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
6123 // Flatten the background color with the editor color to prevent
6124 // elements below transparent hunks from showing through
6125 let flattened_background_color = cx
6126 .theme()
6127 .colors()
6128 .editor_background
6129 .blend(background_color);
6130
6131 if !Self::diff_hunk_hollow(status, cx) {
6132 window.paint_quad(quad(
6133 hunk_bounds,
6134 corner_radii,
6135 flattened_background_color,
6136 Edges::default(),
6137 transparent_black(),
6138 BorderStyle::default(),
6139 ));
6140 } else {
6141 let flattened_unstaged_background_color = cx
6142 .theme()
6143 .colors()
6144 .editor_background
6145 .blend(background_color.opacity(0.3));
6146
6147 window.paint_quad(quad(
6148 hunk_bounds,
6149 corner_radii,
6150 flattened_unstaged_background_color,
6151 Edges::all(px(1.0)),
6152 flattened_background_color,
6153 BorderStyle::Solid,
6154 ));
6155 }
6156 }
6157 }
6158 });
6159 }
6160
6161 fn gutter_strip_width(line_height: Pixels) -> Pixels {
6162 (0.275 * line_height).floor()
6163 }
6164
6165 fn diff_hunk_bounds(
6166 snapshot: &EditorSnapshot,
6167 line_height: Pixels,
6168 gutter_bounds: Bounds<Pixels>,
6169 hunk: &DisplayDiffHunk,
6170 ) -> Bounds<Pixels> {
6171 let scroll_position = snapshot.scroll_position();
6172 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
6173 let gutter_strip_width = Self::gutter_strip_width(line_height);
6174
6175 match hunk {
6176 DisplayDiffHunk::Folded { display_row, .. } => {
6177 let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
6178 - scroll_top)
6179 .into();
6180 let end_y = start_y + line_height;
6181 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6182 let highlight_size = size(gutter_strip_width, end_y - start_y);
6183 Bounds::new(highlight_origin, highlight_size)
6184 }
6185 DisplayDiffHunk::Unfolded {
6186 display_row_range,
6187 status,
6188 ..
6189 } => {
6190 if status.is_deleted() && display_row_range.is_empty() {
6191 let row = display_row_range.start;
6192
6193 let offset = ScrollPixelOffset::from(line_height / 2.);
6194 let start_y =
6195 (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
6196 .into();
6197 let end_y = start_y + line_height;
6198
6199 let width = (0.35 * line_height).floor();
6200 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6201 let highlight_size = size(width, end_y - start_y);
6202 Bounds::new(highlight_origin, highlight_size)
6203 } else {
6204 let start_row = display_row_range.start;
6205 let end_row = display_row_range.end;
6206 // If we're in a multibuffer, row range span might include an
6207 // excerpt header, so if we were to draw the marker straight away,
6208 // the hunk might include the rows of that header.
6209 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
6210 // Instead, we simply check whether the range we're dealing with includes
6211 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
6212 let end_row_in_current_excerpt = snapshot
6213 .blocks_in_range(start_row..end_row)
6214 .find_map(|(start_row, block)| {
6215 if matches!(
6216 block,
6217 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
6218 ) {
6219 Some(start_row)
6220 } else {
6221 None
6222 }
6223 })
6224 .unwrap_or(end_row);
6225
6226 let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
6227 - scroll_top)
6228 .into();
6229 let end_y = Pixels::from(
6230 end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
6231 - scroll_top,
6232 );
6233
6234 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6235 let highlight_size = size(gutter_strip_width, end_y - start_y);
6236 Bounds::new(highlight_origin, highlight_size)
6237 }
6238 }
6239 }
6240 }
6241
6242 fn paint_gutter_indicators(
6243 &self,
6244 layout: &mut EditorLayout,
6245 window: &mut Window,
6246 cx: &mut App,
6247 ) {
6248 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6249 window.with_element_namespace("crease_toggles", |window| {
6250 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
6251 crease_toggle.paint(window, cx);
6252 }
6253 });
6254
6255 window.with_element_namespace("expand_toggles", |window| {
6256 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
6257 expand_toggle.paint(window, cx);
6258 }
6259 });
6260
6261 for breakpoint in layout.breakpoints.iter_mut() {
6262 breakpoint.paint(window, cx);
6263 }
6264
6265 for test_indicator in layout.test_indicators.iter_mut() {
6266 test_indicator.paint(window, cx);
6267 }
6268
6269 if let Some(diff_review_button) = layout.diff_review_button.as_mut() {
6270 diff_review_button.paint(window, cx);
6271 }
6272 });
6273 }
6274
6275 fn paint_gutter_highlights(
6276 &self,
6277 layout: &mut EditorLayout,
6278 window: &mut Window,
6279 cx: &mut App,
6280 ) {
6281 for (_, hunk_hitbox) in &layout.display_hunks {
6282 if let Some(hunk_hitbox) = hunk_hitbox
6283 && !self
6284 .editor
6285 .read(cx)
6286 .buffer()
6287 .read(cx)
6288 .all_diff_hunks_expanded()
6289 {
6290 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
6291 }
6292 }
6293
6294 let show_git_gutter = layout
6295 .position_map
6296 .snapshot
6297 .show_git_diff_gutter
6298 .unwrap_or_else(|| {
6299 matches!(
6300 ProjectSettings::get_global(cx).git.git_gutter,
6301 GitGutterSetting::TrackedFiles
6302 )
6303 });
6304 if show_git_gutter && self.split_side.is_none() {
6305 Self::paint_gutter_diff_hunks(layout, window, cx)
6306 }
6307
6308 let highlight_width = 0.275 * layout.position_map.line_height;
6309 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
6310 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6311 for (range, color) in &layout.highlighted_gutter_ranges {
6312 let start_row = if range.start.row() < layout.visible_display_row_range.start {
6313 layout.visible_display_row_range.start - DisplayRow(1)
6314 } else {
6315 range.start.row()
6316 };
6317 let end_row = if range.end.row() > layout.visible_display_row_range.end {
6318 layout.visible_display_row_range.end + DisplayRow(1)
6319 } else {
6320 range.end.row()
6321 };
6322
6323 let start_y = layout.gutter_hitbox.top()
6324 + Pixels::from(
6325 start_row.0 as f64
6326 * ScrollPixelOffset::from(layout.position_map.line_height)
6327 - layout.position_map.scroll_pixel_position.y,
6328 );
6329 let end_y = layout.gutter_hitbox.top()
6330 + Pixels::from(
6331 (end_row.0 + 1) as f64
6332 * ScrollPixelOffset::from(layout.position_map.line_height)
6333 - layout.position_map.scroll_pixel_position.y,
6334 );
6335 let bounds = Bounds::from_corners(
6336 point(layout.gutter_hitbox.left(), start_y),
6337 point(layout.gutter_hitbox.left() + highlight_width, end_y),
6338 );
6339 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
6340 }
6341 });
6342 }
6343
6344 fn paint_blamed_display_rows(
6345 &self,
6346 layout: &mut EditorLayout,
6347 window: &mut Window,
6348 cx: &mut App,
6349 ) {
6350 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
6351 return;
6352 };
6353
6354 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6355 for mut blame_element in blamed_display_rows.into_iter() {
6356 blame_element.paint(window, cx);
6357 }
6358 })
6359 }
6360
6361 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6362 window.with_content_mask(
6363 Some(ContentMask {
6364 bounds: layout.position_map.text_hitbox.bounds,
6365 }),
6366 |window| {
6367 let editor = self.editor.read(cx);
6368 if editor.mouse_cursor_hidden {
6369 window.set_window_cursor_style(CursorStyle::None);
6370 } else if let SelectionDragState::ReadyToDrag {
6371 mouse_down_time, ..
6372 } = &editor.selection_drag_state
6373 {
6374 let drag_and_drop_delay = Duration::from_millis(
6375 EditorSettings::get_global(cx)
6376 .drag_and_drop_selection
6377 .delay
6378 .0,
6379 );
6380 if mouse_down_time.elapsed() >= drag_and_drop_delay {
6381 window.set_cursor_style(
6382 CursorStyle::DragCopy,
6383 &layout.position_map.text_hitbox,
6384 );
6385 }
6386 } else if matches!(
6387 editor.selection_drag_state,
6388 SelectionDragState::Dragging { .. }
6389 ) {
6390 window
6391 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
6392 } else if editor
6393 .hovered_link_state
6394 .as_ref()
6395 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
6396 {
6397 window.set_cursor_style(
6398 CursorStyle::PointingHand,
6399 &layout.position_map.text_hitbox,
6400 );
6401 } else {
6402 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
6403 };
6404
6405 self.paint_lines_background(layout, window, cx);
6406 let invisible_display_ranges = self.paint_highlights(layout, window, cx);
6407 self.paint_document_colors(layout, window);
6408 self.paint_lines(&invisible_display_ranges, layout, window, cx);
6409 self.paint_redactions(layout, window);
6410 self.paint_cursors(layout, window, cx);
6411 self.paint_inline_diagnostics(layout, window, cx);
6412 self.paint_inline_blame(layout, window, cx);
6413 self.paint_inline_code_actions(layout, window, cx);
6414 self.paint_diff_hunk_controls(layout, window, cx);
6415 window.with_element_namespace("crease_trailers", |window| {
6416 for trailer in layout.crease_trailers.iter_mut().flatten() {
6417 trailer.element.paint(window, cx);
6418 }
6419 });
6420 },
6421 )
6422 }
6423
6424 fn paint_highlights(
6425 &mut self,
6426 layout: &mut EditorLayout,
6427 window: &mut Window,
6428 cx: &mut App,
6429 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6430 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6431 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6432 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6433 for (range, color) in &layout.highlighted_ranges {
6434 self.paint_highlighted_range(
6435 range.clone(),
6436 true,
6437 *color,
6438 Pixels::ZERO,
6439 line_end_overshoot,
6440 layout,
6441 window,
6442 );
6443 }
6444
6445 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
6446 0.15 * layout.position_map.line_height
6447 } else {
6448 Pixels::ZERO
6449 };
6450
6451 for (player_color, selections) in &layout.selections {
6452 for selection in selections.iter() {
6453 self.paint_highlighted_range(
6454 selection.range.clone(),
6455 true,
6456 player_color.selection,
6457 corner_radius,
6458 corner_radius * 2.,
6459 layout,
6460 window,
6461 );
6462
6463 if selection.is_local && !selection.range.is_empty() {
6464 invisible_display_ranges.push(selection.range.clone());
6465 }
6466 }
6467 }
6468 invisible_display_ranges
6469 })
6470 }
6471
6472 fn paint_lines(
6473 &mut self,
6474 invisible_display_ranges: &[Range<DisplayPoint>],
6475 layout: &mut EditorLayout,
6476 window: &mut Window,
6477 cx: &mut App,
6478 ) {
6479 let whitespace_setting = self
6480 .editor
6481 .read(cx)
6482 .buffer
6483 .read(cx)
6484 .language_settings(cx)
6485 .show_whitespaces;
6486
6487 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6488 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6489 line_with_invisibles.draw(
6490 layout,
6491 row,
6492 layout.content_origin,
6493 whitespace_setting,
6494 invisible_display_ranges,
6495 window,
6496 cx,
6497 )
6498 }
6499
6500 for line_element in &mut layout.line_elements {
6501 line_element.paint(window, cx);
6502 }
6503 }
6504
6505 fn paint_sticky_headers(
6506 &mut self,
6507 layout: &mut EditorLayout,
6508 window: &mut Window,
6509 cx: &mut App,
6510 ) {
6511 let Some(mut sticky_headers) = layout.sticky_headers.take() else {
6512 return;
6513 };
6514
6515 if sticky_headers.lines.is_empty() {
6516 layout.sticky_headers = Some(sticky_headers);
6517 return;
6518 }
6519
6520 let whitespace_setting = self
6521 .editor
6522 .read(cx)
6523 .buffer
6524 .read(cx)
6525 .language_settings(cx)
6526 .show_whitespaces;
6527 sticky_headers.paint(layout, whitespace_setting, window, cx);
6528
6529 let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
6530 .lines
6531 .iter()
6532 .map(|line| line.hitbox.clone())
6533 .collect();
6534 let hovered_hitbox = sticky_header_hitboxes
6535 .iter()
6536 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6537
6538 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
6539 if !phase.bubble() {
6540 return;
6541 }
6542
6543 let current_hover = sticky_header_hitboxes
6544 .iter()
6545 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6546 if hovered_hitbox != current_hover {
6547 window.refresh();
6548 }
6549 });
6550
6551 for (line_index, line) in sticky_headers.lines.iter().enumerate() {
6552 let editor = self.editor.clone();
6553 let hitbox = line.hitbox.clone();
6554 let target_anchor = line.target_anchor;
6555 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
6556 if !phase.bubble() {
6557 return;
6558 }
6559
6560 if event.button == MouseButton::Left && hitbox.is_hovered(window) {
6561 editor.update(cx, |editor, cx| {
6562 editor.change_selections(
6563 SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
6564 window,
6565 cx,
6566 |selections| selections.select_ranges([target_anchor..target_anchor]),
6567 );
6568 cx.stop_propagation();
6569 });
6570 }
6571 });
6572 }
6573
6574 let text_bounds = layout.position_map.text_hitbox.bounds;
6575 let border_top = text_bounds.top()
6576 + sticky_headers.lines.last().unwrap().offset
6577 + layout.position_map.line_height;
6578 let separator_height = px(1.);
6579 let border_bounds = Bounds::from_corners(
6580 point(layout.gutter_hitbox.bounds.left(), border_top),
6581 point(text_bounds.right(), border_top + separator_height),
6582 );
6583 window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
6584
6585 layout.sticky_headers = Some(sticky_headers);
6586 }
6587
6588 fn paint_lines_background(
6589 &mut self,
6590 layout: &mut EditorLayout,
6591 window: &mut Window,
6592 cx: &mut App,
6593 ) {
6594 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6595 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6596 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6597 }
6598 }
6599
6600 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6601 if layout.redacted_ranges.is_empty() {
6602 return;
6603 }
6604
6605 let line_end_overshoot = layout.line_end_overshoot();
6606
6607 // A softer than perfect black
6608 let redaction_color = gpui::rgb(0x0e1111);
6609
6610 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6611 for range in layout.redacted_ranges.iter() {
6612 self.paint_highlighted_range(
6613 range.clone(),
6614 true,
6615 redaction_color.into(),
6616 Pixels::ZERO,
6617 line_end_overshoot,
6618 layout,
6619 window,
6620 );
6621 }
6622 });
6623 }
6624
6625 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6626 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6627 return;
6628 };
6629 if image_colors.is_empty()
6630 || colors_render_mode == &DocumentColorsRenderMode::None
6631 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6632 {
6633 return;
6634 }
6635
6636 let line_end_overshoot = layout.line_end_overshoot();
6637
6638 for (range, color) in image_colors {
6639 match colors_render_mode {
6640 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6641 DocumentColorsRenderMode::Background => {
6642 self.paint_highlighted_range(
6643 range.clone(),
6644 true,
6645 *color,
6646 Pixels::ZERO,
6647 line_end_overshoot,
6648 layout,
6649 window,
6650 );
6651 }
6652 DocumentColorsRenderMode::Border => {
6653 self.paint_highlighted_range(
6654 range.clone(),
6655 false,
6656 *color,
6657 Pixels::ZERO,
6658 line_end_overshoot,
6659 layout,
6660 window,
6661 );
6662 }
6663 }
6664 }
6665 }
6666
6667 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6668 for cursor in &mut layout.visible_cursors {
6669 cursor.paint(layout.content_origin, window, cx);
6670 }
6671 }
6672
6673 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6674 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6675 return;
6676 };
6677 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6678
6679 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6680 let hitbox = &scrollbar_layout.hitbox;
6681 if scrollbars_layout.visible {
6682 let scrollbar_edges = match axis {
6683 ScrollbarAxis::Horizontal => Edges {
6684 top: Pixels::ZERO,
6685 right: Pixels::ZERO,
6686 bottom: Pixels::ZERO,
6687 left: Pixels::ZERO,
6688 },
6689 ScrollbarAxis::Vertical => Edges {
6690 top: Pixels::ZERO,
6691 right: Pixels::ZERO,
6692 bottom: Pixels::ZERO,
6693 left: ScrollbarLayout::BORDER_WIDTH,
6694 },
6695 };
6696
6697 window.paint_layer(hitbox.bounds, |window| {
6698 window.paint_quad(quad(
6699 hitbox.bounds,
6700 Corners::default(),
6701 cx.theme().colors().scrollbar_track_background,
6702 scrollbar_edges,
6703 cx.theme().colors().scrollbar_track_border,
6704 BorderStyle::Solid,
6705 ));
6706
6707 if axis == ScrollbarAxis::Vertical {
6708 let fast_markers =
6709 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6710 // Refresh slow scrollbar markers in the background. Below, we
6711 // paint whatever markers have already been computed.
6712 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6713
6714 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6715 for marker in markers.iter().chain(&fast_markers) {
6716 let mut marker = marker.clone();
6717 marker.bounds.origin += hitbox.origin;
6718 window.paint_quad(marker);
6719 }
6720 }
6721
6722 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6723 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6724 ScrollbarThumbState::Dragging => {
6725 cx.theme().colors().scrollbar_thumb_active_background
6726 }
6727 ScrollbarThumbState::Hovered => {
6728 cx.theme().colors().scrollbar_thumb_hover_background
6729 }
6730 ScrollbarThumbState::Idle => {
6731 cx.theme().colors().scrollbar_thumb_background
6732 }
6733 };
6734 window.paint_quad(quad(
6735 thumb_bounds,
6736 Corners::default(),
6737 scrollbar_thumb_color,
6738 scrollbar_edges,
6739 cx.theme().colors().scrollbar_thumb_border,
6740 BorderStyle::Solid,
6741 ));
6742
6743 if any_scrollbar_dragged {
6744 window.set_window_cursor_style(CursorStyle::Arrow);
6745 } else {
6746 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6747 }
6748 }
6749 })
6750 }
6751 }
6752
6753 window.on_mouse_event({
6754 let editor = self.editor.clone();
6755 let scrollbars_layout = scrollbars_layout.clone();
6756
6757 let mut mouse_position = window.mouse_position();
6758 move |event: &MouseMoveEvent, phase, window, cx| {
6759 if phase == DispatchPhase::Capture {
6760 return;
6761 }
6762
6763 editor.update(cx, |editor, cx| {
6764 if let Some((scrollbar_layout, axis)) = event
6765 .pressed_button
6766 .filter(|button| *button == MouseButton::Left)
6767 .and(editor.scroll_manager.dragging_scrollbar_axis())
6768 .and_then(|axis| {
6769 scrollbars_layout
6770 .iter_scrollbars()
6771 .find(|(_, a)| *a == axis)
6772 })
6773 {
6774 let ScrollbarLayout {
6775 hitbox,
6776 text_unit_size,
6777 ..
6778 } = scrollbar_layout;
6779
6780 let old_position = mouse_position.along(axis);
6781 let new_position = event.position.along(axis);
6782 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6783 .contains(&old_position)
6784 {
6785 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6786 (p + ScrollOffset::from(
6787 (new_position - old_position) / *text_unit_size,
6788 ))
6789 .max(0.)
6790 });
6791 editor.set_scroll_position(position, window, cx);
6792 }
6793
6794 editor.scroll_manager.show_scrollbars(window, cx);
6795 cx.stop_propagation();
6796 } else if let Some((layout, axis)) = scrollbars_layout
6797 .get_hovered_axis(window)
6798 .filter(|_| !event.dragging())
6799 {
6800 if layout.thumb_hovered(&event.position) {
6801 editor
6802 .scroll_manager
6803 .set_hovered_scroll_thumb_axis(axis, cx);
6804 } else {
6805 editor.scroll_manager.reset_scrollbar_state(cx);
6806 }
6807
6808 editor.scroll_manager.show_scrollbars(window, cx);
6809 } else {
6810 editor.scroll_manager.reset_scrollbar_state(cx);
6811 }
6812
6813 mouse_position = event.position;
6814 })
6815 }
6816 });
6817
6818 if any_scrollbar_dragged {
6819 window.on_mouse_event({
6820 let editor = self.editor.clone();
6821 move |_: &MouseUpEvent, phase, window, cx| {
6822 if phase == DispatchPhase::Capture {
6823 return;
6824 }
6825
6826 editor.update(cx, |editor, cx| {
6827 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6828 editor
6829 .scroll_manager
6830 .set_hovered_scroll_thumb_axis(axis, cx);
6831 } else {
6832 editor.scroll_manager.reset_scrollbar_state(cx);
6833 }
6834 cx.stop_propagation();
6835 });
6836 }
6837 });
6838 } else {
6839 window.on_mouse_event({
6840 let editor = self.editor.clone();
6841
6842 move |event: &MouseDownEvent, phase, window, cx| {
6843 if phase == DispatchPhase::Capture {
6844 return;
6845 }
6846 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6847 else {
6848 return;
6849 };
6850
6851 let ScrollbarLayout {
6852 hitbox,
6853 visible_range,
6854 text_unit_size,
6855 thumb_bounds,
6856 ..
6857 } = scrollbar_layout;
6858
6859 let Some(thumb_bounds) = thumb_bounds else {
6860 return;
6861 };
6862
6863 editor.update(cx, |editor, cx| {
6864 editor
6865 .scroll_manager
6866 .set_dragged_scroll_thumb_axis(axis, cx);
6867
6868 let event_position = event.position.along(axis);
6869
6870 if event_position < thumb_bounds.origin.along(axis)
6871 || thumb_bounds.bottom_right().along(axis) < event_position
6872 {
6873 let center_position = ((event_position - hitbox.origin.along(axis))
6874 / *text_unit_size)
6875 .round() as u32;
6876 let start_position = center_position.saturating_sub(
6877 (visible_range.end - visible_range.start) as u32 / 2,
6878 );
6879
6880 let position = editor
6881 .scroll_position(cx)
6882 .apply_along(axis, |_| start_position as ScrollOffset);
6883
6884 editor.set_scroll_position(position, window, cx);
6885 } else {
6886 editor.scroll_manager.show_scrollbars(window, cx);
6887 }
6888
6889 cx.stop_propagation();
6890 });
6891 }
6892 });
6893 }
6894 }
6895
6896 fn collect_fast_scrollbar_markers(
6897 &self,
6898 layout: &EditorLayout,
6899 scrollbar_layout: &ScrollbarLayout,
6900 cx: &mut App,
6901 ) -> Vec<PaintQuad> {
6902 const LIMIT: usize = 100;
6903 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6904 return vec![];
6905 }
6906 let cursor_ranges = layout
6907 .cursors
6908 .iter()
6909 .map(|(point, color)| ColoredRange {
6910 start: point.row(),
6911 end: point.row(),
6912 color: *color,
6913 })
6914 .collect_vec();
6915 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6916 }
6917
6918 fn refresh_slow_scrollbar_markers(
6919 &self,
6920 layout: &EditorLayout,
6921 scrollbar_layout: &ScrollbarLayout,
6922 window: &mut Window,
6923 cx: &mut App,
6924 ) {
6925 self.editor.update(cx, |editor, cx| {
6926 if editor.buffer_kind(cx) != ItemBufferKind::Singleton
6927 || !editor
6928 .scrollbar_marker_state
6929 .should_refresh(scrollbar_layout.hitbox.size)
6930 {
6931 return;
6932 }
6933
6934 let scrollbar_layout = scrollbar_layout.clone();
6935 let background_highlights = editor.background_highlights.clone();
6936 let snapshot = layout.position_map.snapshot.clone();
6937 let theme = cx.theme().clone();
6938 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6939
6940 editor.scrollbar_marker_state.dirty = false;
6941 editor.scrollbar_marker_state.pending_refresh =
6942 Some(cx.spawn_in(window, async move |editor, cx| {
6943 let scrollbar_size = scrollbar_layout.hitbox.size;
6944 let scrollbar_markers = cx
6945 .background_spawn(async move {
6946 let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
6947 let mut marker_quads = Vec::new();
6948 if scrollbar_settings.git_diff {
6949 let marker_row_ranges =
6950 snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
6951 let start_display_row =
6952 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6953 .to_display_point(&snapshot.display_snapshot)
6954 .row();
6955 let mut end_display_row =
6956 MultiBufferPoint::new(hunk.row_range.end.0, 0)
6957 .to_display_point(&snapshot.display_snapshot)
6958 .row();
6959 if end_display_row != start_display_row {
6960 end_display_row.0 -= 1;
6961 }
6962 let color = match &hunk.status().kind {
6963 DiffHunkStatusKind::Added => {
6964 theme.colors().version_control_added
6965 }
6966 DiffHunkStatusKind::Modified => {
6967 theme.colors().version_control_modified
6968 }
6969 DiffHunkStatusKind::Deleted => {
6970 theme.colors().version_control_deleted
6971 }
6972 };
6973 ColoredRange {
6974 start: start_display_row,
6975 end: end_display_row,
6976 color,
6977 }
6978 });
6979
6980 marker_quads.extend(
6981 scrollbar_layout
6982 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
6983 );
6984 }
6985
6986 for (background_highlight_id, (_, background_ranges)) in
6987 background_highlights.iter()
6988 {
6989 let is_search_highlights = *background_highlight_id
6990 == HighlightKey::BufferSearchHighlights;
6991 let is_text_highlights =
6992 *background_highlight_id == HighlightKey::SelectedTextHighlight;
6993 let is_symbol_occurrences = *background_highlight_id
6994 == HighlightKey::DocumentHighlightRead
6995 || *background_highlight_id
6996 == HighlightKey::DocumentHighlightWrite;
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 use_tree_sitter =
11713 !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
11714 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), use_tree_sitter, style);
11715 LineWithInvisibles::from_chunks(
11716 chunks,
11717 style,
11718 MAX_LINE_LEN,
11719 1,
11720 &snapshot.mode,
11721 text_width,
11722 is_row_soft_wrapped,
11723 &[],
11724 window,
11725 cx,
11726 )
11727 .pop()
11728 .unwrap()
11729}
11730
11731#[derive(Debug)]
11732pub struct IndentGuideLayout {
11733 origin: gpui::Point<Pixels>,
11734 length: Pixels,
11735 single_indent_width: Pixels,
11736 depth: u32,
11737 active: bool,
11738 settings: IndentGuideSettings,
11739}
11740
11741pub struct CursorLayout {
11742 origin: gpui::Point<Pixels>,
11743 block_width: Pixels,
11744 line_height: Pixels,
11745 color: Hsla,
11746 shape: CursorShape,
11747 block_text: Option<ShapedLine>,
11748 cursor_name: Option<AnyElement>,
11749}
11750
11751#[derive(Debug)]
11752pub struct CursorName {
11753 string: SharedString,
11754 color: Hsla,
11755 is_top_row: bool,
11756}
11757
11758impl CursorLayout {
11759 pub fn new(
11760 origin: gpui::Point<Pixels>,
11761 block_width: Pixels,
11762 line_height: Pixels,
11763 color: Hsla,
11764 shape: CursorShape,
11765 block_text: Option<ShapedLine>,
11766 ) -> CursorLayout {
11767 CursorLayout {
11768 origin,
11769 block_width,
11770 line_height,
11771 color,
11772 shape,
11773 block_text,
11774 cursor_name: None,
11775 }
11776 }
11777
11778 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11779 Bounds {
11780 origin: self.origin + origin,
11781 size: size(self.block_width, self.line_height),
11782 }
11783 }
11784
11785 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11786 match self.shape {
11787 CursorShape::Bar => Bounds {
11788 origin: self.origin + origin,
11789 size: size(px(2.0), self.line_height),
11790 },
11791 CursorShape::Block | CursorShape::Hollow => Bounds {
11792 origin: self.origin + origin,
11793 size: size(self.block_width, self.line_height),
11794 },
11795 CursorShape::Underline => Bounds {
11796 origin: self.origin
11797 + origin
11798 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11799 size: size(self.block_width, px(2.0)),
11800 },
11801 }
11802 }
11803
11804 pub fn layout(
11805 &mut self,
11806 origin: gpui::Point<Pixels>,
11807 cursor_name: Option<CursorName>,
11808 window: &mut Window,
11809 cx: &mut App,
11810 ) {
11811 if let Some(cursor_name) = cursor_name {
11812 let bounds = self.bounds(origin);
11813 let text_size = self.line_height / 1.5;
11814
11815 let name_origin = if cursor_name.is_top_row {
11816 point(bounds.right() - px(1.), bounds.top())
11817 } else {
11818 match self.shape {
11819 CursorShape::Bar => point(
11820 bounds.right() - px(2.),
11821 bounds.top() - text_size / 2. - px(1.),
11822 ),
11823 _ => point(
11824 bounds.right() - px(1.),
11825 bounds.top() - text_size / 2. - px(1.),
11826 ),
11827 }
11828 };
11829 let mut name_element = div()
11830 .bg(self.color)
11831 .text_size(text_size)
11832 .px_0p5()
11833 .line_height(text_size + px(2.))
11834 .text_color(cursor_name.color)
11835 .child(cursor_name.string)
11836 .into_any_element();
11837
11838 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11839
11840 self.cursor_name = Some(name_element);
11841 }
11842 }
11843
11844 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11845 let bounds = self.bounds(origin);
11846
11847 //Draw background or border quad
11848 let cursor = if matches!(self.shape, CursorShape::Hollow) {
11849 outline(bounds, self.color, BorderStyle::Solid)
11850 } else {
11851 fill(bounds, self.color)
11852 };
11853
11854 if let Some(name) = &mut self.cursor_name {
11855 name.paint(window, cx);
11856 }
11857
11858 window.paint_quad(cursor);
11859
11860 if let Some(block_text) = &self.block_text {
11861 block_text
11862 .paint(
11863 self.origin + origin,
11864 self.line_height,
11865 TextAlign::Left,
11866 None,
11867 window,
11868 cx,
11869 )
11870 .log_err();
11871 }
11872 }
11873
11874 pub fn shape(&self) -> CursorShape {
11875 self.shape
11876 }
11877}
11878
11879#[derive(Debug)]
11880pub struct HighlightedRange {
11881 pub start_y: Pixels,
11882 pub line_height: Pixels,
11883 pub lines: Vec<HighlightedRangeLine>,
11884 pub color: Hsla,
11885 pub corner_radius: Pixels,
11886}
11887
11888#[derive(Debug)]
11889pub struct HighlightedRangeLine {
11890 pub start_x: Pixels,
11891 pub end_x: Pixels,
11892}
11893
11894impl HighlightedRange {
11895 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
11896 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
11897 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
11898 self.paint_lines(
11899 self.start_y + self.line_height,
11900 &self.lines[1..],
11901 fill,
11902 bounds,
11903 window,
11904 );
11905 } else {
11906 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
11907 }
11908 }
11909
11910 fn paint_lines(
11911 &self,
11912 start_y: Pixels,
11913 lines: &[HighlightedRangeLine],
11914 fill: bool,
11915 _bounds: Bounds<Pixels>,
11916 window: &mut Window,
11917 ) {
11918 if lines.is_empty() {
11919 return;
11920 }
11921
11922 let first_line = lines.first().unwrap();
11923 let last_line = lines.last().unwrap();
11924
11925 let first_top_left = point(first_line.start_x, start_y);
11926 let first_top_right = point(first_line.end_x, start_y);
11927
11928 let curve_height = point(Pixels::ZERO, self.corner_radius);
11929 let curve_width = |start_x: Pixels, end_x: Pixels| {
11930 let max = (end_x - start_x) / 2.;
11931 let width = if max < self.corner_radius {
11932 max
11933 } else {
11934 self.corner_radius
11935 };
11936
11937 point(width, Pixels::ZERO)
11938 };
11939
11940 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
11941 let mut builder = if fill {
11942 gpui::PathBuilder::fill()
11943 } else {
11944 gpui::PathBuilder::stroke(px(1.))
11945 };
11946 builder.move_to(first_top_right - top_curve_width);
11947 builder.curve_to(first_top_right + curve_height, first_top_right);
11948
11949 let mut iter = lines.iter().enumerate().peekable();
11950 while let Some((ix, line)) = iter.next() {
11951 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
11952
11953 if let Some((_, next_line)) = iter.peek() {
11954 let next_top_right = point(next_line.end_x, bottom_right.y);
11955
11956 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
11957 Ordering::Equal => {
11958 builder.line_to(bottom_right);
11959 }
11960 Ordering::Less => {
11961 let curve_width = curve_width(next_top_right.x, bottom_right.x);
11962 builder.line_to(bottom_right - curve_height);
11963 if self.corner_radius > Pixels::ZERO {
11964 builder.curve_to(bottom_right - curve_width, bottom_right);
11965 }
11966 builder.line_to(next_top_right + curve_width);
11967 if self.corner_radius > Pixels::ZERO {
11968 builder.curve_to(next_top_right + curve_height, next_top_right);
11969 }
11970 }
11971 Ordering::Greater => {
11972 let curve_width = curve_width(bottom_right.x, next_top_right.x);
11973 builder.line_to(bottom_right - curve_height);
11974 if self.corner_radius > Pixels::ZERO {
11975 builder.curve_to(bottom_right + curve_width, bottom_right);
11976 }
11977 builder.line_to(next_top_right - curve_width);
11978 if self.corner_radius > Pixels::ZERO {
11979 builder.curve_to(next_top_right + curve_height, next_top_right);
11980 }
11981 }
11982 }
11983 } else {
11984 let curve_width = curve_width(line.start_x, line.end_x);
11985 builder.line_to(bottom_right - curve_height);
11986 if self.corner_radius > Pixels::ZERO {
11987 builder.curve_to(bottom_right - curve_width, bottom_right);
11988 }
11989
11990 let bottom_left = point(line.start_x, bottom_right.y);
11991 builder.line_to(bottom_left + curve_width);
11992 if self.corner_radius > Pixels::ZERO {
11993 builder.curve_to(bottom_left - curve_height, bottom_left);
11994 }
11995 }
11996 }
11997
11998 if first_line.start_x > last_line.start_x {
11999 let curve_width = curve_width(last_line.start_x, first_line.start_x);
12000 let second_top_left = point(last_line.start_x, start_y + self.line_height);
12001 builder.line_to(second_top_left + curve_height);
12002 if self.corner_radius > Pixels::ZERO {
12003 builder.curve_to(second_top_left + curve_width, second_top_left);
12004 }
12005 let first_bottom_left = point(first_line.start_x, second_top_left.y);
12006 builder.line_to(first_bottom_left - curve_width);
12007 if self.corner_radius > Pixels::ZERO {
12008 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12009 }
12010 }
12011
12012 builder.line_to(first_top_left + curve_height);
12013 if self.corner_radius > Pixels::ZERO {
12014 builder.curve_to(first_top_left + top_curve_width, first_top_left);
12015 }
12016 builder.line_to(first_top_right - top_curve_width);
12017
12018 if let Ok(path) = builder.build() {
12019 window.paint_path(path, self.color);
12020 }
12021 }
12022}
12023
12024pub(crate) struct StickyHeader {
12025 pub item: language::OutlineItem<Anchor>,
12026 pub sticky_row: DisplayRow,
12027 pub start_point: Point,
12028 pub offset: ScrollOffset,
12029}
12030
12031enum CursorPopoverType {
12032 CodeContextMenu,
12033 EditPrediction,
12034}
12035
12036pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12037 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12038}
12039
12040fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12041 (delta.pow(1.2) / 300.0).into()
12042}
12043
12044pub fn register_action<T: Action>(
12045 editor: &Entity<Editor>,
12046 window: &mut Window,
12047 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12048) {
12049 let editor = editor.clone();
12050 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12051 let action = action.downcast_ref().unwrap();
12052 if phase == DispatchPhase::Bubble {
12053 editor.update(cx, |editor, cx| {
12054 listener(editor, action, window, cx);
12055 })
12056 }
12057 })
12058}
12059
12060fn compute_auto_height_layout(
12061 editor: &mut Editor,
12062 min_lines: usize,
12063 max_lines: Option<usize>,
12064 known_dimensions: Size<Option<Pixels>>,
12065 available_width: AvailableSpace,
12066 window: &mut Window,
12067 cx: &mut Context<Editor>,
12068) -> Option<Size<Pixels>> {
12069 let width = known_dimensions.width.or({
12070 if let AvailableSpace::Definite(available_width) = available_width {
12071 Some(available_width)
12072 } else {
12073 None
12074 }
12075 })?;
12076 if let Some(height) = known_dimensions.height {
12077 return Some(size(width, height));
12078 }
12079
12080 let style = editor.style.as_ref().unwrap();
12081 let font_id = window.text_system().resolve_font(&style.text.font());
12082 let font_size = style.text.font_size.to_pixels(window.rem_size());
12083 let line_height = style.text.line_height_in_pixels(window.rem_size());
12084 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12085
12086 let mut snapshot = editor.snapshot(window, cx);
12087 let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12088
12089 editor.gutter_dimensions = gutter_dimensions;
12090 let text_width = width - gutter_dimensions.width;
12091 let overscroll = size(em_width, px(0.));
12092
12093 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12094 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
12095 && editor.set_wrap_width(Some(editor_width), cx)
12096 {
12097 snapshot = editor.snapshot(window, cx);
12098 }
12099
12100 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12101
12102 let min_height = line_height * min_lines as f32;
12103 let content_height = scroll_height.max(min_height);
12104
12105 let final_height = if let Some(max_lines) = max_lines {
12106 let max_height = line_height * max_lines as f32;
12107 content_height.min(max_height)
12108 } else {
12109 content_height
12110 };
12111
12112 Some(size(width, final_height))
12113}
12114
12115#[cfg(test)]
12116mod tests {
12117 use super::*;
12118 use crate::{
12119 Editor, MultiBuffer, SelectionEffects,
12120 display_map::{BlockPlacement, BlockProperties},
12121 editor_tests::{init_test, update_test_language_settings},
12122 };
12123 use gpui::{TestAppContext, VisualTestContext};
12124 use language::{Buffer, language_settings, tree_sitter_python};
12125 use log::info;
12126 use std::num::NonZeroU32;
12127 use util::test::sample_text;
12128
12129 #[gpui::test]
12130 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12131 init_test(cx, |_| {});
12132 // Ensure wrap completes synchronously by giving block_with_timeout enough ticks
12133 cx.dispatcher.scheduler().set_timeout_ticks(1000..=1000);
12134
12135 let window = cx.add_window(|window, cx| {
12136 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12137 let mut editor = Editor::new(
12138 EditorMode::AutoHeight {
12139 min_lines: 1,
12140 max_lines: None,
12141 },
12142 buffer,
12143 None,
12144 window,
12145 cx,
12146 );
12147 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12148 editor
12149 });
12150 let cx = &mut VisualTestContext::from_window(*window, cx);
12151 let editor = window.root(cx).unwrap();
12152 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12153
12154 for x in 1..=100 {
12155 let (_, state) = cx.draw(
12156 Default::default(),
12157 size(px(200. + 0.13 * x as f32), px(500.)),
12158 |_, _| EditorElement::new(&editor, style.clone()),
12159 );
12160
12161 assert!(
12162 state.position_map.scroll_max.x == 0.,
12163 "Soft wrapped editor should have no horizontal scrolling!"
12164 );
12165 }
12166 }
12167
12168 #[gpui::test]
12169 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12170 init_test(cx, |_| {});
12171 // Ensure wrap completes synchronously by giving block_with_timeout enough ticks
12172 cx.dispatcher.scheduler().set_timeout_ticks(1000..=1000);
12173
12174 let window = cx.add_window(|window, cx| {
12175 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12176 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12177 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12178 editor
12179 });
12180 let cx = &mut VisualTestContext::from_window(*window, cx);
12181 let editor = window.root(cx).unwrap();
12182 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12183
12184 for x in 1..=100 {
12185 let (_, state) = cx.draw(
12186 Default::default(),
12187 size(px(200. + 0.13 * x as f32), px(500.)),
12188 |_, _| EditorElement::new(&editor, style.clone()),
12189 );
12190
12191 assert!(
12192 state.position_map.scroll_max.x == 0.,
12193 "Soft wrapped editor should have no horizontal scrolling!"
12194 );
12195 }
12196 }
12197
12198 #[gpui::test]
12199 fn test_layout_line_numbers(cx: &mut TestAppContext) {
12200 init_test(cx, |_| {});
12201 let window = cx.add_window(|window, cx| {
12202 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12203 Editor::new(EditorMode::full(), buffer, None, window, cx)
12204 });
12205
12206 let editor = window.root(cx).unwrap();
12207 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12208 let line_height = window
12209 .update(cx, |_, window, _| {
12210 style.text.line_height_in_pixels(window.rem_size())
12211 })
12212 .unwrap();
12213 let element = EditorElement::new(&editor, style);
12214 let snapshot = window
12215 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12216 .unwrap();
12217
12218 let layouts = cx
12219 .update_window(*window, |_, window, cx| {
12220 element.layout_line_numbers(
12221 None,
12222 GutterDimensions {
12223 left_padding: Pixels::ZERO,
12224 right_padding: Pixels::ZERO,
12225 width: px(30.0),
12226 margin: Pixels::ZERO,
12227 git_blame_entries_width: None,
12228 },
12229 line_height,
12230 gpui::Point::default(),
12231 DisplayRow(0)..DisplayRow(6),
12232 &(0..6)
12233 .map(|row| RowInfo {
12234 buffer_row: Some(row),
12235 ..Default::default()
12236 })
12237 .collect::<Vec<_>>(),
12238 &BTreeMap::default(),
12239 Some(DisplayRow(0)),
12240 &snapshot,
12241 window,
12242 cx,
12243 )
12244 })
12245 .unwrap();
12246 assert_eq!(layouts.len(), 6);
12247
12248 let relative_rows = window
12249 .update(cx, |editor, window, cx| {
12250 let snapshot = editor.snapshot(window, cx);
12251 snapshot.calculate_relative_line_numbers(
12252 &(DisplayRow(0)..DisplayRow(6)),
12253 DisplayRow(3),
12254 false,
12255 )
12256 })
12257 .unwrap();
12258 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12259 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12260 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12261 // current line has no relative number
12262 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12263 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12264 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12265
12266 // works if cursor is before screen
12267 let relative_rows = window
12268 .update(cx, |editor, window, cx| {
12269 let snapshot = editor.snapshot(window, cx);
12270 snapshot.calculate_relative_line_numbers(
12271 &(DisplayRow(3)..DisplayRow(6)),
12272 DisplayRow(1),
12273 false,
12274 )
12275 })
12276 .unwrap();
12277 assert_eq!(relative_rows.len(), 3);
12278 assert_eq!(relative_rows[&DisplayRow(3)], 2);
12279 assert_eq!(relative_rows[&DisplayRow(4)], 3);
12280 assert_eq!(relative_rows[&DisplayRow(5)], 4);
12281
12282 // works if cursor is after screen
12283 let relative_rows = window
12284 .update(cx, |editor, window, cx| {
12285 let snapshot = editor.snapshot(window, cx);
12286 snapshot.calculate_relative_line_numbers(
12287 &(DisplayRow(0)..DisplayRow(3)),
12288 DisplayRow(6),
12289 false,
12290 )
12291 })
12292 .unwrap();
12293 assert_eq!(relative_rows.len(), 3);
12294 assert_eq!(relative_rows[&DisplayRow(0)], 5);
12295 assert_eq!(relative_rows[&DisplayRow(1)], 4);
12296 assert_eq!(relative_rows[&DisplayRow(2)], 3);
12297
12298 const DELETED_LINE: u32 = 3;
12299 let layouts = cx
12300 .update_window(*window, |_, window, cx| {
12301 element.layout_line_numbers(
12302 None,
12303 GutterDimensions {
12304 left_padding: Pixels::ZERO,
12305 right_padding: Pixels::ZERO,
12306 width: px(30.0),
12307 margin: Pixels::ZERO,
12308 git_blame_entries_width: None,
12309 },
12310 line_height,
12311 gpui::Point::default(),
12312 DisplayRow(0)..DisplayRow(6),
12313 &(0..6)
12314 .map(|row| RowInfo {
12315 buffer_row: Some(row),
12316 diff_status: (row == DELETED_LINE).then(|| {
12317 DiffHunkStatus::deleted(
12318 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12319 )
12320 }),
12321 ..Default::default()
12322 })
12323 .collect::<Vec<_>>(),
12324 &BTreeMap::default(),
12325 Some(DisplayRow(0)),
12326 &snapshot,
12327 window,
12328 cx,
12329 )
12330 })
12331 .unwrap();
12332 assert_eq!(layouts.len(), 5,);
12333 assert!(
12334 layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12335 "Deleted line should not have a line number"
12336 );
12337 }
12338
12339 #[gpui::test]
12340 async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12341 init_test(cx, |_| {});
12342
12343 let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12344
12345 let window = cx.add_window(|window, cx| {
12346 let buffer = cx.new(|cx| {
12347 Buffer::local(
12348 indoc::indoc! {"
12349 fn test() -> int {
12350 return 2;
12351 }
12352
12353 fn another_test() -> int {
12354 # This is a very peculiar method that is hard to grasp.
12355 return 4;
12356 }
12357 "},
12358 cx,
12359 )
12360 .with_language(python_lang, cx)
12361 });
12362
12363 let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12364 Editor::new(EditorMode::full(), buffer, None, window, cx)
12365 });
12366
12367 let editor = window.root(cx).unwrap();
12368 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12369 let line_height = window
12370 .update(cx, |_, window, _| {
12371 style.text.line_height_in_pixels(window.rem_size())
12372 })
12373 .unwrap();
12374 let element = EditorElement::new(&editor, style);
12375 let snapshot = window
12376 .update(cx, |editor, window, cx| {
12377 editor.fold_at(MultiBufferRow(0), window, cx);
12378 editor.snapshot(window, cx)
12379 })
12380 .unwrap();
12381
12382 let layouts = cx
12383 .update_window(*window, |_, window, cx| {
12384 element.layout_line_numbers(
12385 None,
12386 GutterDimensions {
12387 left_padding: Pixels::ZERO,
12388 right_padding: Pixels::ZERO,
12389 width: px(30.0),
12390 margin: Pixels::ZERO,
12391 git_blame_entries_width: None,
12392 },
12393 line_height,
12394 gpui::Point::default(),
12395 DisplayRow(0)..DisplayRow(6),
12396 &(0..6)
12397 .map(|row| RowInfo {
12398 buffer_row: Some(row),
12399 ..Default::default()
12400 })
12401 .collect::<Vec<_>>(),
12402 &BTreeMap::default(),
12403 Some(DisplayRow(3)),
12404 &snapshot,
12405 window,
12406 cx,
12407 )
12408 })
12409 .unwrap();
12410 assert_eq!(layouts.len(), 6);
12411
12412 let relative_rows = window
12413 .update(cx, |editor, window, cx| {
12414 let snapshot = editor.snapshot(window, cx);
12415 snapshot.calculate_relative_line_numbers(
12416 &(DisplayRow(0)..DisplayRow(6)),
12417 DisplayRow(3),
12418 false,
12419 )
12420 })
12421 .unwrap();
12422 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12423 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12424 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12425 // current line has no relative number
12426 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12427 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12428 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12429 }
12430
12431 #[gpui::test]
12432 fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12433 init_test(cx, |_| {});
12434 let window = cx.add_window(|window, cx| {
12435 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12436 Editor::new(EditorMode::full(), buffer, None, window, cx)
12437 });
12438
12439 update_test_language_settings(cx, |s| {
12440 s.defaults.preferred_line_length = Some(5_u32);
12441 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12442 });
12443
12444 let editor = window.root(cx).unwrap();
12445 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12446 let line_height = window
12447 .update(cx, |_, window, _| {
12448 style.text.line_height_in_pixels(window.rem_size())
12449 })
12450 .unwrap();
12451 let element = EditorElement::new(&editor, style);
12452 let snapshot = window
12453 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12454 .unwrap();
12455
12456 let layouts = cx
12457 .update_window(*window, |_, window, cx| {
12458 element.layout_line_numbers(
12459 None,
12460 GutterDimensions {
12461 left_padding: Pixels::ZERO,
12462 right_padding: Pixels::ZERO,
12463 width: px(30.0),
12464 margin: Pixels::ZERO,
12465 git_blame_entries_width: None,
12466 },
12467 line_height,
12468 gpui::Point::default(),
12469 DisplayRow(0)..DisplayRow(6),
12470 &(0..6)
12471 .map(|row| RowInfo {
12472 buffer_row: Some(row),
12473 ..Default::default()
12474 })
12475 .collect::<Vec<_>>(),
12476 &BTreeMap::default(),
12477 Some(DisplayRow(0)),
12478 &snapshot,
12479 window,
12480 cx,
12481 )
12482 })
12483 .unwrap();
12484 assert_eq!(layouts.len(), 3);
12485
12486 let relative_rows = window
12487 .update(cx, |editor, window, cx| {
12488 let snapshot = editor.snapshot(window, cx);
12489 snapshot.calculate_relative_line_numbers(
12490 &(DisplayRow(0)..DisplayRow(6)),
12491 DisplayRow(3),
12492 true,
12493 )
12494 })
12495 .unwrap();
12496
12497 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12498 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12499 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12500 // current line has no relative number
12501 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12502 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12503 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12504
12505 let layouts = cx
12506 .update_window(*window, |_, window, cx| {
12507 element.layout_line_numbers(
12508 None,
12509 GutterDimensions {
12510 left_padding: Pixels::ZERO,
12511 right_padding: Pixels::ZERO,
12512 width: px(30.0),
12513 margin: Pixels::ZERO,
12514 git_blame_entries_width: None,
12515 },
12516 line_height,
12517 gpui::Point::default(),
12518 DisplayRow(0)..DisplayRow(6),
12519 &(0..6)
12520 .map(|row| RowInfo {
12521 buffer_row: Some(row),
12522 diff_status: Some(DiffHunkStatus::deleted(
12523 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12524 )),
12525 ..Default::default()
12526 })
12527 .collect::<Vec<_>>(),
12528 &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12529 Some(DisplayRow(0)),
12530 &snapshot,
12531 window,
12532 cx,
12533 )
12534 })
12535 .unwrap();
12536 assert!(
12537 layouts.is_empty(),
12538 "Deleted lines should have no line number"
12539 );
12540
12541 let relative_rows = window
12542 .update(cx, |editor, window, cx| {
12543 let snapshot = editor.snapshot(window, cx);
12544 snapshot.calculate_relative_line_numbers(
12545 &(DisplayRow(0)..DisplayRow(6)),
12546 DisplayRow(3),
12547 true,
12548 )
12549 })
12550 .unwrap();
12551
12552 // Deleted lines should still have relative numbers
12553 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12554 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12555 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12556 // current line, even if deleted, has no relative number
12557 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12558 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12559 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12560 }
12561
12562 #[gpui::test]
12563 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12564 init_test(cx, |_| {});
12565
12566 let window = cx.add_window(|window, cx| {
12567 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12568 Editor::new(EditorMode::full(), buffer, None, window, cx)
12569 });
12570 let cx = &mut VisualTestContext::from_window(*window, cx);
12571 let editor = window.root(cx).unwrap();
12572 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12573
12574 window
12575 .update(cx, |editor, window, cx| {
12576 editor.cursor_offset_on_selection = true;
12577 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12578 s.select_ranges([
12579 Point::new(0, 0)..Point::new(1, 0),
12580 Point::new(3, 2)..Point::new(3, 3),
12581 Point::new(5, 6)..Point::new(6, 0),
12582 ]);
12583 });
12584 })
12585 .unwrap();
12586
12587 let (_, state) = cx.draw(
12588 point(px(500.), px(500.)),
12589 size(px(500.), px(500.)),
12590 |_, _| EditorElement::new(&editor, style),
12591 );
12592
12593 assert_eq!(state.selections.len(), 1);
12594 let local_selections = &state.selections[0].1;
12595 assert_eq!(local_selections.len(), 3);
12596 // moves cursor back one line
12597 assert_eq!(
12598 local_selections[0].head,
12599 DisplayPoint::new(DisplayRow(0), 6)
12600 );
12601 assert_eq!(
12602 local_selections[0].range,
12603 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12604 );
12605
12606 // moves cursor back one column
12607 assert_eq!(
12608 local_selections[1].range,
12609 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12610 );
12611 assert_eq!(
12612 local_selections[1].head,
12613 DisplayPoint::new(DisplayRow(3), 2)
12614 );
12615
12616 // leaves cursor on the max point
12617 assert_eq!(
12618 local_selections[2].range,
12619 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12620 );
12621 assert_eq!(
12622 local_selections[2].head,
12623 DisplayPoint::new(DisplayRow(6), 0)
12624 );
12625
12626 // active lines does not include 1 (even though the range of the selection does)
12627 assert_eq!(
12628 state.active_rows.keys().cloned().collect::<Vec<_>>(),
12629 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12630 );
12631 }
12632
12633 #[gpui::test]
12634 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12635 init_test(cx, |_| {});
12636
12637 let window = cx.add_window(|window, cx| {
12638 let buffer = MultiBuffer::build_simple("", cx);
12639 Editor::new(EditorMode::full(), buffer, None, window, cx)
12640 });
12641 let cx = &mut VisualTestContext::from_window(*window, cx);
12642 let editor = window.root(cx).unwrap();
12643 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12644 window
12645 .update(cx, |editor, window, cx| {
12646 editor.set_placeholder_text("hello", window, cx);
12647 editor.insert_blocks(
12648 [BlockProperties {
12649 style: BlockStyle::Fixed,
12650 placement: BlockPlacement::Above(Anchor::min()),
12651 height: Some(3),
12652 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12653 priority: 0,
12654 }],
12655 None,
12656 cx,
12657 );
12658
12659 // Blur the editor so that it displays placeholder text.
12660 window.blur();
12661 })
12662 .unwrap();
12663
12664 let (_, state) = cx.draw(
12665 point(px(500.), px(500.)),
12666 size(px(500.), px(500.)),
12667 |_, _| EditorElement::new(&editor, style),
12668 );
12669 assert_eq!(state.position_map.line_layouts.len(), 4);
12670 assert_eq!(state.line_numbers.len(), 1);
12671 assert_eq!(
12672 state
12673 .line_numbers
12674 .get(&MultiBufferRow(0))
12675 .map(|line_number| line_number
12676 .segments
12677 .first()
12678 .unwrap()
12679 .shaped_line
12680 .text
12681 .as_ref()),
12682 Some("1")
12683 );
12684 }
12685
12686 #[gpui::test]
12687 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12688 const TAB_SIZE: u32 = 4;
12689
12690 let input_text = "\t \t|\t| a b";
12691 let expected_invisibles = vec![
12692 Invisible::Tab {
12693 line_start_offset: 0,
12694 line_end_offset: TAB_SIZE as usize,
12695 },
12696 Invisible::Whitespace {
12697 line_offset: TAB_SIZE as usize,
12698 },
12699 Invisible::Tab {
12700 line_start_offset: TAB_SIZE as usize + 1,
12701 line_end_offset: TAB_SIZE as usize * 2,
12702 },
12703 Invisible::Tab {
12704 line_start_offset: TAB_SIZE as usize * 2 + 1,
12705 line_end_offset: TAB_SIZE as usize * 3,
12706 },
12707 Invisible::Whitespace {
12708 line_offset: TAB_SIZE as usize * 3 + 1,
12709 },
12710 Invisible::Whitespace {
12711 line_offset: TAB_SIZE as usize * 3 + 3,
12712 },
12713 ];
12714 assert_eq!(
12715 expected_invisibles.len(),
12716 input_text
12717 .chars()
12718 .filter(|initial_char| initial_char.is_whitespace())
12719 .count(),
12720 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12721 );
12722
12723 for show_line_numbers in [true, false] {
12724 init_test(cx, |s| {
12725 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12726 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
12727 });
12728
12729 let actual_invisibles = collect_invisibles_from_new_editor(
12730 cx,
12731 EditorMode::full(),
12732 input_text,
12733 px(500.0),
12734 show_line_numbers,
12735 );
12736
12737 assert_eq!(expected_invisibles, actual_invisibles);
12738 }
12739 }
12740
12741 #[gpui::test]
12742 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
12743 init_test(cx, |s| {
12744 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12745 s.defaults.tab_size = NonZeroU32::new(4);
12746 });
12747
12748 for editor_mode_without_invisibles in [
12749 EditorMode::SingleLine,
12750 EditorMode::AutoHeight {
12751 min_lines: 1,
12752 max_lines: Some(100),
12753 },
12754 ] {
12755 for show_line_numbers in [true, false] {
12756 let invisibles = collect_invisibles_from_new_editor(
12757 cx,
12758 editor_mode_without_invisibles.clone(),
12759 "\t\t\t| | a b",
12760 px(500.0),
12761 show_line_numbers,
12762 );
12763 assert!(
12764 invisibles.is_empty(),
12765 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
12766 );
12767 }
12768 }
12769 }
12770
12771 #[gpui::test]
12772 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
12773 let tab_size = 4;
12774 let input_text = "a\tbcd ".repeat(9);
12775 let repeated_invisibles = [
12776 Invisible::Tab {
12777 line_start_offset: 1,
12778 line_end_offset: tab_size as usize,
12779 },
12780 Invisible::Whitespace {
12781 line_offset: tab_size as usize + 3,
12782 },
12783 Invisible::Whitespace {
12784 line_offset: tab_size as usize + 4,
12785 },
12786 Invisible::Whitespace {
12787 line_offset: tab_size as usize + 5,
12788 },
12789 Invisible::Whitespace {
12790 line_offset: tab_size as usize + 6,
12791 },
12792 Invisible::Whitespace {
12793 line_offset: tab_size as usize + 7,
12794 },
12795 ];
12796 let expected_invisibles = std::iter::once(repeated_invisibles)
12797 .cycle()
12798 .take(9)
12799 .flatten()
12800 .collect::<Vec<_>>();
12801 assert_eq!(
12802 expected_invisibles.len(),
12803 input_text
12804 .chars()
12805 .filter(|initial_char| initial_char.is_whitespace())
12806 .count(),
12807 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12808 );
12809 info!("Expected invisibles: {expected_invisibles:?}");
12810
12811 init_test(cx, |_| {});
12812
12813 // Put the same string with repeating whitespace pattern into editors of various size,
12814 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
12815 let resize_step = 10.0;
12816 let mut editor_width = 200.0;
12817 while editor_width <= 1000.0 {
12818 for show_line_numbers in [true, false] {
12819 update_test_language_settings(cx, |s| {
12820 s.defaults.tab_size = NonZeroU32::new(tab_size);
12821 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12822 s.defaults.preferred_line_length = Some(editor_width as u32);
12823 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12824 });
12825
12826 let actual_invisibles = collect_invisibles_from_new_editor(
12827 cx,
12828 EditorMode::full(),
12829 &input_text,
12830 px(editor_width),
12831 show_line_numbers,
12832 );
12833
12834 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
12835 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
12836 let mut i = 0;
12837 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
12838 i = actual_index;
12839 match expected_invisibles.get(i) {
12840 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
12841 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
12842 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
12843 _ => {
12844 panic!(
12845 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
12846 )
12847 }
12848 },
12849 None => {
12850 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
12851 }
12852 }
12853 }
12854 let missing_expected_invisibles = &expected_invisibles[i + 1..];
12855 assert!(
12856 missing_expected_invisibles.is_empty(),
12857 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
12858 );
12859
12860 editor_width += resize_step;
12861 }
12862 }
12863 }
12864
12865 fn collect_invisibles_from_new_editor(
12866 cx: &mut TestAppContext,
12867 editor_mode: EditorMode,
12868 input_text: &str,
12869 editor_width: Pixels,
12870 show_line_numbers: bool,
12871 ) -> Vec<Invisible> {
12872 info!(
12873 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
12874 f32::from(editor_width)
12875 );
12876 let window = cx.add_window(|window, cx| {
12877 let buffer = MultiBuffer::build_simple(input_text, cx);
12878 Editor::new(editor_mode, buffer, None, window, cx)
12879 });
12880 let cx = &mut VisualTestContext::from_window(*window, cx);
12881 let editor = window.root(cx).unwrap();
12882
12883 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12884 window
12885 .update(cx, |editor, _, cx| {
12886 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12887 editor.set_wrap_width(Some(editor_width), cx);
12888 editor.set_show_line_numbers(show_line_numbers, cx);
12889 })
12890 .unwrap();
12891 let (_, state) = cx.draw(
12892 point(px(500.), px(500.)),
12893 size(px(500.), px(500.)),
12894 |_, _| EditorElement::new(&editor, style),
12895 );
12896 state
12897 .position_map
12898 .line_layouts
12899 .iter()
12900 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
12901 .cloned()
12902 .collect()
12903 }
12904
12905 #[gpui::test]
12906 fn test_merge_overlapping_ranges() {
12907 let base_bg = Hsla::white();
12908 let color1 = Hsla {
12909 h: 0.0,
12910 s: 0.5,
12911 l: 0.5,
12912 a: 0.5,
12913 };
12914 let color2 = Hsla {
12915 h: 120.0,
12916 s: 0.5,
12917 l: 0.5,
12918 a: 0.5,
12919 };
12920
12921 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
12922 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
12923 v.iter()
12924 .map(|(r, _)| (r.start.column(), r.end.column()))
12925 .collect()
12926 };
12927
12928 // Test overlapping ranges blend colors
12929 let overlapping = vec![
12930 (display_point(5)..display_point(15), color1),
12931 (display_point(10)..display_point(20), color2),
12932 ];
12933 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
12934 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12935
12936 // Test middle segment should have blended color
12937 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
12938 assert_eq!(result[1].1, blended);
12939
12940 // Test adjacent same-color ranges merge
12941 let adjacent_same = vec![
12942 (display_point(5)..display_point(10), color1),
12943 (display_point(10)..display_point(15), color1),
12944 ];
12945 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
12946 assert_eq!(cols(&result), vec![(5, 15)]);
12947
12948 // Test contained range splits
12949 let contained = vec![
12950 (display_point(5)..display_point(20), color1),
12951 (display_point(10)..display_point(15), color2),
12952 ];
12953 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
12954 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12955
12956 // Test multiple overlaps split at every boundary
12957 let color3 = Hsla {
12958 h: 240.0,
12959 s: 0.5,
12960 l: 0.5,
12961 a: 0.5,
12962 };
12963 let complex = vec![
12964 (display_point(5)..display_point(12), color1),
12965 (display_point(8)..display_point(16), color2),
12966 (display_point(10)..display_point(14), color3),
12967 ];
12968 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
12969 assert_eq!(
12970 cols(&result),
12971 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
12972 );
12973 }
12974
12975 #[gpui::test]
12976 fn test_bg_segments_per_row() {
12977 let base_bg = Hsla::white();
12978
12979 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
12980 {
12981 let selection_color = Hsla {
12982 h: 200.0,
12983 s: 0.5,
12984 l: 0.5,
12985 a: 0.5,
12986 };
12987 let player_color = PlayerColor {
12988 cursor: selection_color,
12989 background: selection_color,
12990 selection: selection_color,
12991 };
12992
12993 let spanning_selection = SelectionLayout {
12994 head: DisplayPoint::new(DisplayRow(3), 7),
12995 cursor_shape: CursorShape::Bar,
12996 is_newest: true,
12997 is_local: true,
12998 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
12999 active_rows: DisplayRow(1)..DisplayRow(4),
13000 user_name: None,
13001 };
13002
13003 let selections = vec![(player_color, vec![spanning_selection])];
13004 let result = EditorElement::bg_segments_per_row(
13005 DisplayRow(0)..DisplayRow(5),
13006 &selections,
13007 &[],
13008 base_bg,
13009 );
13010
13011 assert_eq!(result.len(), 5);
13012 assert!(result[0].is_empty());
13013 assert_eq!(result[1].len(), 1);
13014 assert_eq!(result[2].len(), 1);
13015 assert_eq!(result[3].len(), 1);
13016 assert!(result[4].is_empty());
13017
13018 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13019 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13020 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13021 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13022 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13023 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13024 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13025 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13026 }
13027
13028 // Case B: selection ends exactly at the start of row 3, excluding row 3
13029 {
13030 let selection_color = Hsla {
13031 h: 120.0,
13032 s: 0.5,
13033 l: 0.5,
13034 a: 0.5,
13035 };
13036 let player_color = PlayerColor {
13037 cursor: selection_color,
13038 background: selection_color,
13039 selection: selection_color,
13040 };
13041
13042 let selection = SelectionLayout {
13043 head: DisplayPoint::new(DisplayRow(2), 0),
13044 cursor_shape: CursorShape::Bar,
13045 is_newest: true,
13046 is_local: true,
13047 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13048 active_rows: DisplayRow(1)..DisplayRow(3),
13049 user_name: None,
13050 };
13051
13052 let selections = vec![(player_color, vec![selection])];
13053 let result = EditorElement::bg_segments_per_row(
13054 DisplayRow(0)..DisplayRow(4),
13055 &selections,
13056 &[],
13057 base_bg,
13058 );
13059
13060 assert_eq!(result.len(), 4);
13061 assert!(result[0].is_empty());
13062 assert_eq!(result[1].len(), 1);
13063 assert_eq!(result[2].len(), 1);
13064 assert!(result[3].is_empty());
13065
13066 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13067 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13068 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13069 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13070 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13071 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13072 }
13073 }
13074
13075 #[cfg(test)]
13076 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13077 TextRun {
13078 len,
13079 color,
13080 ..Default::default()
13081 }
13082 }
13083
13084 #[gpui::test]
13085 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13086 init_test(cx, |_| {});
13087
13088 let dx = |start: u32, end: u32| {
13089 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13090 };
13091
13092 let text_color = Hsla {
13093 h: 210.0,
13094 s: 0.1,
13095 l: 0.4,
13096 a: 1.0,
13097 };
13098 let bg_1 = Hsla {
13099 h: 30.0,
13100 s: 0.6,
13101 l: 0.8,
13102 a: 1.0,
13103 };
13104 let bg_2 = Hsla {
13105 h: 200.0,
13106 s: 0.6,
13107 l: 0.2,
13108 a: 1.0,
13109 };
13110 let min_contrast = 45.0;
13111 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13112 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13113
13114 // Case A: single run; disjoint segments inside the run
13115 {
13116 let runs = vec![generate_test_run(20, text_color)];
13117 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13118 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13119 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13120 assert_eq!(
13121 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13122 vec![5, 5, 2, 4, 4]
13123 );
13124 assert_eq!(out[0].color, text_color);
13125 assert_eq!(out[1].color, adjusted_bg1);
13126 assert_eq!(out[2].color, text_color);
13127 assert_eq!(out[3].color, adjusted_bg2);
13128 assert_eq!(out[4].color, text_color);
13129 }
13130
13131 // Case B: multiple runs; segment extends to end of line (u32::MAX)
13132 {
13133 let runs = vec![
13134 generate_test_run(8, text_color),
13135 generate_test_run(7, text_color),
13136 ];
13137 let segs = vec![(dx(6, u32::MAX), bg_1)];
13138 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13139 // Expected slices across runs: [0,6) [6,8) | [0,7)
13140 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13141 assert_eq!(out[0].color, text_color);
13142 assert_eq!(out[1].color, adjusted_bg1);
13143 assert_eq!(out[2].color, adjusted_bg1);
13144 }
13145
13146 // Case C: multi-byte characters
13147 {
13148 // for text: "Hello π δΈη!"
13149 let runs = vec![
13150 generate_test_run(5, text_color), // "Hello"
13151 generate_test_run(6, text_color), // " π "
13152 generate_test_run(6, text_color), // "δΈη"
13153 generate_test_run(1, text_color), // "!"
13154 ];
13155 // selecting "π δΈ"
13156 let segs = vec![(dx(6, 14), bg_1)];
13157 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13158 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
13159 assert_eq!(
13160 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13161 vec![5, 1, 5, 3, 3, 1]
13162 );
13163 assert_eq!(out[0].color, text_color); // "Hello"
13164 assert_eq!(out[2].color, adjusted_bg1); // "π "
13165 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
13166 assert_eq!(out[4].color, text_color); // "η"
13167 assert_eq!(out[5].color, text_color); // "!"
13168 }
13169
13170 // Case D: split multiple consecutive text runs with segments
13171 {
13172 let segs = vec![
13173 (dx(2, 4), bg_1), // selecting "cd"
13174 (dx(4, 8), bg_2), // selecting "efgh"
13175 (dx(9, 11), bg_1), // selecting "jk"
13176 (dx(12, 16), bg_2), // selecting "mnop"
13177 (dx(18, 19), bg_1), // selecting "s"
13178 ];
13179
13180 // for text: "abcdef"
13181 let runs = vec![
13182 generate_test_run(2, text_color), // ab
13183 generate_test_run(4, text_color), // cdef
13184 ];
13185 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13186 // new splits "ab", "cd", "ef"
13187 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13188 assert_eq!(out[0].color, text_color);
13189 assert_eq!(out[1].color, adjusted_bg1);
13190 assert_eq!(out[2].color, adjusted_bg2);
13191
13192 // for text: "ghijklmn"
13193 let runs = vec![
13194 generate_test_run(3, text_color), // ghi
13195 generate_test_run(2, text_color), // jk
13196 generate_test_run(3, text_color), // lmn
13197 ];
13198 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13199 // new splits "gh", "i", "jk", "l", "mn"
13200 assert_eq!(
13201 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13202 vec![2, 1, 2, 1, 2]
13203 );
13204 assert_eq!(out[0].color, adjusted_bg2);
13205 assert_eq!(out[1].color, text_color);
13206 assert_eq!(out[2].color, adjusted_bg1);
13207 assert_eq!(out[3].color, text_color);
13208 assert_eq!(out[4].color, adjusted_bg2);
13209
13210 // for text: "opqrs"
13211 let runs = vec![
13212 generate_test_run(1, text_color), // o
13213 generate_test_run(4, text_color), // pqrs
13214 ];
13215 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13216 // new splits "o", "p", "qr", "s"
13217 assert_eq!(
13218 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13219 vec![1, 1, 2, 1]
13220 );
13221 assert_eq!(out[0].color, adjusted_bg2);
13222 assert_eq!(out[1].color, adjusted_bg2);
13223 assert_eq!(out[2].color, text_color);
13224 assert_eq!(out[3].color, adjusted_bg1);
13225 }
13226 }
13227}