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