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