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