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