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 .size_full()
8143 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
8144 .pl_1()
8145 .pr_2()
8146 .rounded_sm()
8147 .gap_1p5()
8148 .when(is_sticky, |el| el.shadow_md())
8149 .border_1()
8150 .map(|border| {
8151 let border_color =
8152 if is_selected && is_folded && focus_handle.contains_focused(window, cx) {
8153 colors.border_focused
8154 } else {
8155 colors.border
8156 };
8157 border.border_color(border_color)
8158 })
8159 .bg(colors.editor_subheader_background)
8160 .hover(|style| style.bg(colors.element_hover))
8161 .map(|header| {
8162 let editor = editor.clone();
8163 let buffer_id = for_excerpt.buffer_id;
8164 let toggle_chevron_icon =
8165 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
8166 let button_size = rems_from_px(28.);
8167
8168 header.child(
8169 div()
8170 .hover(|style| style.bg(colors.element_selected))
8171 .rounded_xs()
8172 .child(
8173 ButtonLike::new("toggle-buffer-fold")
8174 .style(ButtonStyle::Transparent)
8175 .height(button_size.into())
8176 .width(button_size)
8177 .children(toggle_chevron_icon)
8178 .tooltip({
8179 let focus_handle = focus_handle.clone();
8180 let is_folded_for_tooltip = is_folded;
8181 move |_window, cx| {
8182 Tooltip::with_meta_in(
8183 if is_folded_for_tooltip {
8184 "Unfold Excerpt"
8185 } else {
8186 "Fold Excerpt"
8187 },
8188 Some(&ToggleFold),
8189 format!(
8190 "{} to toggle all",
8191 text_for_keystroke(
8192 &Modifiers::alt(),
8193 "click",
8194 cx
8195 )
8196 ),
8197 &focus_handle,
8198 cx,
8199 )
8200 }
8201 })
8202 .on_click(move |event, window, cx| {
8203 if event.modifiers().alt {
8204 editor.update(cx, |editor, cx| {
8205 editor.toggle_fold_all(&ToggleFoldAll, window, cx);
8206 });
8207 } else {
8208 if is_folded {
8209 editor.update(cx, |editor, cx| {
8210 editor.unfold_buffer(buffer_id, cx);
8211 });
8212 } else {
8213 editor.update(cx, |editor, cx| {
8214 editor.fold_buffer(buffer_id, cx);
8215 });
8216 }
8217 }
8218 }),
8219 ),
8220 )
8221 })
8222 .children(
8223 editor_read
8224 .addons
8225 .values()
8226 .filter_map(|addon| {
8227 addon.render_buffer_header_controls(for_excerpt, window, cx)
8228 })
8229 .take(1),
8230 )
8231 .when(!is_read_only, |this| {
8232 this.child(
8233 h_flex()
8234 .size_3()
8235 .justify_center()
8236 .flex_shrink_0()
8237 .children(indicator),
8238 )
8239 })
8240 .child(
8241 h_flex()
8242 .cursor_pointer()
8243 .id("path_header_block")
8244 .min_w_0()
8245 .size_full()
8246 .gap_1()
8247 .justify_between()
8248 .overflow_hidden()
8249 .child(h_flex().min_w_0().flex_1().gap_0p5().overflow_hidden().map(
8250 |path_header| {
8251 let filename = filename
8252 .map(SharedString::from)
8253 .unwrap_or_else(|| "untitled".into());
8254
8255 let full_path = match parent_path.as_deref() {
8256 Some(parent) if !parent.is_empty() => {
8257 format!("{}{}", parent, filename.as_str())
8258 }
8259 _ => filename.as_str().to_string(),
8260 };
8261
8262 path_header
8263 .child(
8264 ButtonLike::new("filename-button")
8265 .when(ItemSettings::get_global(cx).file_icons, |this| {
8266 let path = path::Path::new(filename.as_str());
8267 let icon = FileIcons::get_icon(path, cx)
8268 .unwrap_or_default();
8269
8270 this.child(
8271 Icon::from_path(icon).color(Color::Muted),
8272 )
8273 })
8274 .child(
8275 Label::new(filename)
8276 .single_line()
8277 .color(file_status_label_color(file_status))
8278 .buffer_font(cx)
8279 .when(
8280 file_status.is_some_and(|s| s.is_deleted()),
8281 |label| label.strikethrough(),
8282 ),
8283 )
8284 .tooltip(move |_, cx| {
8285 Tooltip::with_meta(
8286 "Open File",
8287 None,
8288 full_path.clone(),
8289 cx,
8290 )
8291 })
8292 .on_click(window.listener_for(editor, {
8293 let jump_data = jump_data.clone();
8294 move |editor, e: &ClickEvent, window, cx| {
8295 editor.open_excerpts_common(
8296 Some(jump_data.clone()),
8297 e.modifiers().secondary(),
8298 window,
8299 cx,
8300 );
8301 }
8302 })),
8303 )
8304 .when_some(parent_path, |then, path| {
8305 then.child(
8306 Label::new(path)
8307 .buffer_font(cx)
8308 .truncate_start()
8309 .color(
8310 if file_status
8311 .is_some_and(FileStatus::is_deleted)
8312 {
8313 Color::Custom(colors.text_disabled)
8314 } else {
8315 Color::Custom(colors.text_muted)
8316 },
8317 ),
8318 )
8319 })
8320 .when(!for_excerpt.buffer.capability.editable(), |el| {
8321 el.child(Icon::new(IconName::FileLock).color(Color::Muted))
8322 })
8323 .when_some(breadcrumbs, |then, breadcrumbs| {
8324 then.child(render_breadcrumb_text(
8325 breadcrumbs,
8326 None,
8327 editor_handle,
8328 true,
8329 window,
8330 cx,
8331 ))
8332 })
8333 },
8334 ))
8335 .when(
8336 can_open_excerpts && is_selected && relative_path.is_some(),
8337 |el| {
8338 el.child(
8339 Button::new("open-file-button", "Open File")
8340 .style(ButtonStyle::OutlinedGhost)
8341 .key_binding(KeyBinding::for_action_in(
8342 &OpenExcerpts,
8343 &focus_handle,
8344 cx,
8345 ))
8346 .on_click(window.listener_for(editor, {
8347 let jump_data = jump_data.clone();
8348 move |editor, e: &ClickEvent, window, cx| {
8349 editor.open_excerpts_common(
8350 Some(jump_data.clone()),
8351 e.modifiers().secondary(),
8352 window,
8353 cx,
8354 );
8355 }
8356 })),
8357 )
8358 },
8359 )
8360 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
8361 .on_click(window.listener_for(editor, {
8362 let buffer_id = for_excerpt.buffer_id;
8363 move |editor, e: &ClickEvent, window, cx| {
8364 if e.modifiers().alt {
8365 editor.open_excerpts_common(
8366 Some(jump_data.clone()),
8367 e.modifiers().secondary(),
8368 window,
8369 cx,
8370 );
8371 return;
8372 }
8373
8374 if is_folded {
8375 editor.unfold_buffer(buffer_id, cx);
8376 } else {
8377 editor.fold_buffer(buffer_id, cx);
8378 }
8379 }
8380 })),
8381 ),
8382 );
8383
8384 let file = for_excerpt.buffer.file().cloned();
8385 let editor = editor.clone();
8386
8387 right_click_menu("buffer-header-context-menu")
8388 .trigger(move |_, _, _| header)
8389 .menu(move |window, cx| {
8390 let menu_context = focus_handle.clone();
8391 let editor = editor.clone();
8392 let file = file.clone();
8393 ContextMenu::build(window, cx, move |mut menu, window, cx| {
8394 if let Some(file) = file
8395 && let Some(project) = editor.read(cx).project()
8396 && let Some(worktree) =
8397 project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
8398 {
8399 let path_style = file.path_style(cx);
8400 let worktree = worktree.read(cx);
8401 let relative_path = file.path();
8402 let entry_for_path = worktree.entry_for_path(relative_path);
8403 let abs_path = entry_for_path.map(|e| {
8404 e.canonical_path
8405 .as_deref()
8406 .map_or_else(|| worktree.absolutize(relative_path), Path::to_path_buf)
8407 });
8408 let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
8409
8410 let parent_abs_path = abs_path
8411 .as_ref()
8412 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
8413 let relative_path = has_relative_path
8414 .then_some(relative_path)
8415 .map(ToOwned::to_owned);
8416
8417 let visible_in_project_panel = relative_path.is_some() && worktree.is_visible();
8418 let reveal_in_project_panel = entry_for_path
8419 .filter(|_| visible_in_project_panel)
8420 .map(|entry| entry.id);
8421 menu = menu
8422 .when_some(abs_path, |menu, abs_path| {
8423 menu.entry(
8424 "Copy Path",
8425 Some(Box::new(zed_actions::workspace::CopyPath)),
8426 window.handler_for(&editor, move |_, _, cx| {
8427 cx.write_to_clipboard(ClipboardItem::new_string(
8428 abs_path.to_string_lossy().into_owned(),
8429 ));
8430 }),
8431 )
8432 })
8433 .when_some(relative_path, |menu, relative_path| {
8434 menu.entry(
8435 "Copy Relative Path",
8436 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
8437 window.handler_for(&editor, move |_, _, cx| {
8438 cx.write_to_clipboard(ClipboardItem::new_string(
8439 relative_path.display(path_style).to_string(),
8440 ));
8441 }),
8442 )
8443 })
8444 .when(
8445 reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
8446 |menu| menu.separator(),
8447 )
8448 .when_some(reveal_in_project_panel, |menu, entry_id| {
8449 menu.entry(
8450 "Reveal In Project Panel",
8451 Some(Box::new(RevealInProjectPanel::default())),
8452 window.handler_for(&editor, move |editor, _, cx| {
8453 if let Some(project) = &mut editor.project {
8454 project.update(cx, |_, cx| {
8455 cx.emit(project::Event::RevealInProjectPanel(entry_id))
8456 });
8457 }
8458 }),
8459 )
8460 })
8461 .when_some(parent_abs_path, |menu, parent_abs_path| {
8462 menu.entry(
8463 "Open in Terminal",
8464 Some(Box::new(OpenInTerminal)),
8465 window.handler_for(&editor, move |_, window, cx| {
8466 window.dispatch_action(
8467 OpenTerminal {
8468 working_directory: parent_abs_path.clone(),
8469 local: false,
8470 }
8471 .boxed_clone(),
8472 cx,
8473 );
8474 }),
8475 )
8476 });
8477 }
8478
8479 menu.context(menu_context)
8480 })
8481 })
8482}
8483
8484pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
8485
8486impl AcceptEditPredictionBinding {
8487 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
8488 if let Some(binding) = self.0.as_ref() {
8489 match &binding.keystrokes() {
8490 [keystroke, ..] => Some(keystroke),
8491 _ => None,
8492 }
8493 } else {
8494 None
8495 }
8496 }
8497}
8498
8499fn prepaint_gutter_button(
8500 mut button: AnyElement,
8501 row: DisplayRow,
8502 line_height: Pixels,
8503 gutter_dimensions: &GutterDimensions,
8504 scroll_position: gpui::Point<ScrollOffset>,
8505 gutter_hitbox: &Hitbox,
8506 window: &mut Window,
8507 cx: &mut App,
8508) -> AnyElement {
8509 let available_space = size(
8510 AvailableSpace::MinContent,
8511 AvailableSpace::Definite(line_height),
8512 );
8513 let indicator_size = button.layout_as_root(available_space, window, cx);
8514 let git_gutter_width = EditorElement::gutter_strip_width(line_height)
8515 + gutter_dimensions
8516 .git_blame_entries_width
8517 .unwrap_or_default();
8518
8519 let x = git_gutter_width + px(2.);
8520
8521 let mut y =
8522 Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
8523 y += (line_height - indicator_size.height) / 2.;
8524
8525 button.prepaint_as_root(
8526 gutter_hitbox.origin + point(x, y),
8527 available_space,
8528 window,
8529 cx,
8530 );
8531 button
8532}
8533
8534fn render_inline_blame_entry(
8535 blame_entry: BlameEntry,
8536 style: &EditorStyle,
8537 cx: &mut App,
8538) -> Option<AnyElement> {
8539 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8540 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
8541}
8542
8543fn render_blame_entry_popover(
8544 blame_entry: BlameEntry,
8545 scroll_handle: ScrollHandle,
8546 commit_message: Option<ParsedCommitMessage>,
8547 markdown: Entity<Markdown>,
8548 workspace: WeakEntity<Workspace>,
8549 blame: &Entity<GitBlame>,
8550 buffer: BufferId,
8551 window: &mut Window,
8552 cx: &mut App,
8553) -> Option<AnyElement> {
8554 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8555 let blame = blame.read(cx);
8556 let repository = blame.repository(cx, buffer)?;
8557 renderer.render_blame_entry_popover(
8558 blame_entry,
8559 scroll_handle,
8560 commit_message,
8561 markdown,
8562 repository,
8563 workspace,
8564 window,
8565 cx,
8566 )
8567}
8568
8569fn render_blame_entry(
8570 ix: usize,
8571 blame: &Entity<GitBlame>,
8572 blame_entry: BlameEntry,
8573 style: &EditorStyle,
8574 last_used_color: &mut Option<(Hsla, Oid)>,
8575 editor: Entity<Editor>,
8576 workspace: Entity<Workspace>,
8577 buffer: BufferId,
8578 renderer: &dyn BlameRenderer,
8579 window: &mut Window,
8580 cx: &mut App,
8581) -> Option<AnyElement> {
8582 let index: u32 = blame_entry.sha.into();
8583 let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
8584
8585 // If the last color we used is the same as the one we get for this line, but
8586 // the commit SHAs are different, then we try again to get a different color.
8587 if let Some((color, sha)) = *last_used_color
8588 && sha != blame_entry.sha
8589 && color == sha_color
8590 {
8591 sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
8592 }
8593 last_used_color.replace((sha_color, blame_entry.sha));
8594
8595 let blame = blame.read(cx);
8596 let details = blame.details_for_entry(buffer, &blame_entry);
8597 let repository = blame.repository(cx, buffer)?;
8598 renderer.render_blame_entry(
8599 &style.text,
8600 blame_entry,
8601 details,
8602 repository,
8603 workspace.downgrade(),
8604 editor,
8605 ix,
8606 sha_color,
8607 window,
8608 cx,
8609 )
8610}
8611
8612#[derive(Debug)]
8613pub(crate) struct LineWithInvisibles {
8614 fragments: SmallVec<[LineFragment; 1]>,
8615 invisibles: Vec<Invisible>,
8616 len: usize,
8617 pub(crate) width: Pixels,
8618 font_size: Pixels,
8619}
8620
8621enum LineFragment {
8622 Text(ShapedLine),
8623 Element {
8624 id: ChunkRendererId,
8625 element: Option<AnyElement>,
8626 size: Size<Pixels>,
8627 len: usize,
8628 },
8629}
8630
8631impl fmt::Debug for LineFragment {
8632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8633 match self {
8634 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
8635 LineFragment::Element { size, len, .. } => f
8636 .debug_struct("Element")
8637 .field("size", size)
8638 .field("len", len)
8639 .finish(),
8640 }
8641 }
8642}
8643
8644impl LineWithInvisibles {
8645 fn from_chunks<'a>(
8646 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
8647 editor_style: &EditorStyle,
8648 max_line_len: usize,
8649 max_line_count: usize,
8650 editor_mode: &EditorMode,
8651 text_width: Pixels,
8652 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8653 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
8654 window: &mut Window,
8655 cx: &mut App,
8656 ) -> Vec<Self> {
8657 let text_style = &editor_style.text;
8658 let mut layouts = Vec::with_capacity(max_line_count);
8659 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
8660 let mut line = String::new();
8661 let mut invisibles = Vec::new();
8662 let mut width = Pixels::ZERO;
8663 let mut len = 0;
8664 let mut styles = Vec::new();
8665 let mut non_whitespace_added = false;
8666 let mut row = 0;
8667 let mut line_exceeded_max_len = false;
8668 let font_size = text_style.font_size.to_pixels(window.rem_size());
8669 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
8670
8671 let ellipsis = SharedString::from("β―");
8672
8673 for highlighted_chunk in chunks.chain([HighlightedChunk {
8674 text: "\n",
8675 style: None,
8676 is_tab: false,
8677 is_inlay: false,
8678 replacement: None,
8679 }]) {
8680 if let Some(replacement) = highlighted_chunk.replacement {
8681 if !line.is_empty() {
8682 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8683 let text_runs: &[TextRun] = if segments.is_empty() {
8684 &styles
8685 } else {
8686 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8687 };
8688 let shaped_line = window.text_system().shape_line(
8689 line.clone().into(),
8690 font_size,
8691 text_runs,
8692 None,
8693 );
8694 width += shaped_line.width;
8695 len += shaped_line.len;
8696 fragments.push(LineFragment::Text(shaped_line));
8697 line.clear();
8698 styles.clear();
8699 }
8700
8701 match replacement {
8702 ChunkReplacement::Renderer(renderer) => {
8703 let available_width = if renderer.constrain_width {
8704 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
8705 ellipsis.clone()
8706 } else {
8707 SharedString::from(Arc::from(highlighted_chunk.text))
8708 };
8709 let shaped_line = window.text_system().shape_line(
8710 chunk,
8711 font_size,
8712 &[text_style.to_run(highlighted_chunk.text.len())],
8713 None,
8714 );
8715 AvailableSpace::Definite(shaped_line.width)
8716 } else {
8717 AvailableSpace::MinContent
8718 };
8719
8720 let mut element = (renderer.render)(&mut ChunkRendererContext {
8721 context: cx,
8722 window,
8723 max_width: text_width,
8724 });
8725 let line_height = text_style.line_height_in_pixels(window.rem_size());
8726 let size = element.layout_as_root(
8727 size(available_width, AvailableSpace::Definite(line_height)),
8728 window,
8729 cx,
8730 );
8731
8732 width += size.width;
8733 len += highlighted_chunk.text.len();
8734 fragments.push(LineFragment::Element {
8735 id: renderer.id,
8736 element: Some(element),
8737 size,
8738 len: highlighted_chunk.text.len(),
8739 });
8740 }
8741 ChunkReplacement::Str(x) => {
8742 let text_style = if let Some(style) = highlighted_chunk.style {
8743 Cow::Owned(text_style.clone().highlight(style))
8744 } else {
8745 Cow::Borrowed(text_style)
8746 };
8747
8748 let run = TextRun {
8749 len: x.len(),
8750 font: text_style.font(),
8751 color: text_style.color,
8752 background_color: text_style.background_color,
8753 underline: text_style.underline,
8754 strikethrough: text_style.strikethrough,
8755 };
8756 let line_layout = window
8757 .text_system()
8758 .shape_line(x, font_size, &[run], None)
8759 .with_len(highlighted_chunk.text.len());
8760
8761 width += line_layout.width;
8762 len += highlighted_chunk.text.len();
8763 fragments.push(LineFragment::Text(line_layout))
8764 }
8765 }
8766 } else {
8767 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
8768 if ix > 0 {
8769 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8770 let text_runs = if segments.is_empty() {
8771 &styles
8772 } else {
8773 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8774 };
8775 let shaped_line = window.text_system().shape_line(
8776 line.clone().into(),
8777 font_size,
8778 text_runs,
8779 None,
8780 );
8781 width += shaped_line.width;
8782 len += shaped_line.len;
8783 fragments.push(LineFragment::Text(shaped_line));
8784 layouts.push(Self {
8785 width: mem::take(&mut width),
8786 len: mem::take(&mut len),
8787 fragments: mem::take(&mut fragments),
8788 invisibles: std::mem::take(&mut invisibles),
8789 font_size,
8790 });
8791
8792 line.clear();
8793 styles.clear();
8794 row += 1;
8795 line_exceeded_max_len = false;
8796 non_whitespace_added = false;
8797 if row == max_line_count {
8798 return layouts;
8799 }
8800 }
8801
8802 if !line_chunk.is_empty() && !line_exceeded_max_len {
8803 let text_style = if let Some(style) = highlighted_chunk.style {
8804 Cow::Owned(text_style.clone().highlight(style))
8805 } else {
8806 Cow::Borrowed(text_style)
8807 };
8808
8809 if line.len() + line_chunk.len() > max_line_len {
8810 let mut chunk_len = max_line_len - line.len();
8811 while !line_chunk.is_char_boundary(chunk_len) {
8812 chunk_len -= 1;
8813 }
8814 line_chunk = &line_chunk[..chunk_len];
8815 line_exceeded_max_len = true;
8816 }
8817
8818 styles.push(TextRun {
8819 len: line_chunk.len(),
8820 font: text_style.font(),
8821 color: text_style.color,
8822 background_color: text_style.background_color,
8823 underline: text_style.underline,
8824 strikethrough: text_style.strikethrough,
8825 });
8826
8827 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
8828 // Line wrap pads its contents with fake whitespaces,
8829 // avoid printing them
8830 let is_soft_wrapped = is_row_soft_wrapped(row);
8831 if highlighted_chunk.is_tab {
8832 if non_whitespace_added || !is_soft_wrapped {
8833 invisibles.push(Invisible::Tab {
8834 line_start_offset: line.len(),
8835 line_end_offset: line.len() + line_chunk.len(),
8836 });
8837 }
8838 } else {
8839 invisibles.extend(line_chunk.char_indices().filter_map(
8840 |(index, c)| {
8841 let is_whitespace = c.is_whitespace();
8842 non_whitespace_added |= !is_whitespace;
8843 if is_whitespace
8844 && (non_whitespace_added || !is_soft_wrapped)
8845 {
8846 Some(Invisible::Whitespace {
8847 line_offset: line.len() + index,
8848 })
8849 } else {
8850 None
8851 }
8852 },
8853 ))
8854 }
8855 }
8856
8857 line.push_str(line_chunk);
8858 }
8859 }
8860 }
8861 }
8862
8863 layouts
8864 }
8865
8866 /// Takes text runs and non-overlapping left-to-right background ranges with color.
8867 /// Returns new text runs with adjusted contrast as per background ranges.
8868 fn split_runs_by_bg_segments(
8869 text_runs: &[TextRun],
8870 bg_segments: &[(Range<DisplayPoint>, Hsla)],
8871 min_contrast: f32,
8872 start_col_offset: usize,
8873 ) -> Vec<TextRun> {
8874 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
8875 let mut line_col = start_col_offset;
8876 let mut segment_ix = 0usize;
8877
8878 for text_run in text_runs.iter() {
8879 let run_start_col = line_col;
8880 let run_end_col = run_start_col + text_run.len;
8881 while segment_ix < bg_segments.len()
8882 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
8883 {
8884 segment_ix += 1;
8885 }
8886 let mut cursor_col = run_start_col;
8887 let mut local_segment_ix = segment_ix;
8888 while local_segment_ix < bg_segments.len() {
8889 let (range, segment_color) = &bg_segments[local_segment_ix];
8890 let segment_start_col = range.start.column() as usize;
8891 let segment_end_col = range.end.column() as usize;
8892 if segment_start_col >= run_end_col {
8893 break;
8894 }
8895 if segment_start_col > cursor_col {
8896 let span_len = segment_start_col - cursor_col;
8897 output_runs.push(TextRun {
8898 len: span_len,
8899 font: text_run.font.clone(),
8900 color: text_run.color,
8901 background_color: text_run.background_color,
8902 underline: text_run.underline,
8903 strikethrough: text_run.strikethrough,
8904 });
8905 cursor_col = segment_start_col;
8906 }
8907 let segment_slice_end_col = segment_end_col.min(run_end_col);
8908 if segment_slice_end_col > cursor_col {
8909 let new_text_color =
8910 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
8911 output_runs.push(TextRun {
8912 len: segment_slice_end_col - cursor_col,
8913 font: text_run.font.clone(),
8914 color: new_text_color,
8915 background_color: text_run.background_color,
8916 underline: text_run.underline,
8917 strikethrough: text_run.strikethrough,
8918 });
8919 cursor_col = segment_slice_end_col;
8920 }
8921 if segment_end_col >= run_end_col {
8922 break;
8923 }
8924 local_segment_ix += 1;
8925 }
8926 if cursor_col < run_end_col {
8927 output_runs.push(TextRun {
8928 len: run_end_col - cursor_col,
8929 font: text_run.font.clone(),
8930 color: text_run.color,
8931 background_color: text_run.background_color,
8932 underline: text_run.underline,
8933 strikethrough: text_run.strikethrough,
8934 });
8935 }
8936 line_col = run_end_col;
8937 segment_ix = local_segment_ix;
8938 }
8939 output_runs
8940 }
8941
8942 fn prepaint(
8943 &mut self,
8944 line_height: Pixels,
8945 scroll_position: gpui::Point<ScrollOffset>,
8946 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8947 row: DisplayRow,
8948 content_origin: gpui::Point<Pixels>,
8949 line_elements: &mut SmallVec<[AnyElement; 1]>,
8950 window: &mut Window,
8951 cx: &mut App,
8952 ) {
8953 let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
8954 self.prepaint_with_custom_offset(
8955 line_height,
8956 scroll_pixel_position,
8957 content_origin,
8958 line_y,
8959 line_elements,
8960 window,
8961 cx,
8962 );
8963 }
8964
8965 fn prepaint_with_custom_offset(
8966 &mut self,
8967 line_height: Pixels,
8968 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8969 content_origin: gpui::Point<Pixels>,
8970 line_y: Pixels,
8971 line_elements: &mut SmallVec<[AnyElement; 1]>,
8972 window: &mut Window,
8973 cx: &mut App,
8974 ) {
8975 let mut fragment_origin =
8976 content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
8977 for fragment in &mut self.fragments {
8978 match fragment {
8979 LineFragment::Text(line) => {
8980 fragment_origin.x += line.width;
8981 }
8982 LineFragment::Element { element, size, .. } => {
8983 let mut element = element
8984 .take()
8985 .expect("you can't prepaint LineWithInvisibles twice");
8986
8987 // Center the element vertically within the line.
8988 let mut element_origin = fragment_origin;
8989 element_origin.y += (line_height - size.height) / 2.;
8990 element.prepaint_at(element_origin, window, cx);
8991 line_elements.push(element);
8992
8993 fragment_origin.x += size.width;
8994 }
8995 }
8996 }
8997 }
8998
8999 fn draw(
9000 &self,
9001 layout: &EditorLayout,
9002 row: DisplayRow,
9003 content_origin: gpui::Point<Pixels>,
9004 whitespace_setting: ShowWhitespaceSetting,
9005 selection_ranges: &[Range<DisplayPoint>],
9006 window: &mut Window,
9007 cx: &mut App,
9008 ) {
9009 self.draw_with_custom_offset(
9010 layout,
9011 row,
9012 content_origin,
9013 layout.position_map.line_height
9014 * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
9015 whitespace_setting,
9016 selection_ranges,
9017 window,
9018 cx,
9019 );
9020 }
9021
9022 fn draw_with_custom_offset(
9023 &self,
9024 layout: &EditorLayout,
9025 row: DisplayRow,
9026 content_origin: gpui::Point<Pixels>,
9027 line_y: Pixels,
9028 whitespace_setting: ShowWhitespaceSetting,
9029 selection_ranges: &[Range<DisplayPoint>],
9030 window: &mut Window,
9031 cx: &mut App,
9032 ) {
9033 let line_height = layout.position_map.line_height;
9034 let mut fragment_origin = content_origin
9035 + gpui::point(
9036 Pixels::from(-layout.position_map.scroll_pixel_position.x),
9037 line_y,
9038 );
9039
9040 for fragment in &self.fragments {
9041 match fragment {
9042 LineFragment::Text(line) => {
9043 line.paint(
9044 fragment_origin,
9045 line_height,
9046 layout.text_align,
9047 Some(layout.content_width),
9048 window,
9049 cx,
9050 )
9051 .log_err();
9052 fragment_origin.x += line.width;
9053 }
9054 LineFragment::Element { size, .. } => {
9055 fragment_origin.x += size.width;
9056 }
9057 }
9058 }
9059
9060 self.draw_invisibles(
9061 selection_ranges,
9062 layout,
9063 content_origin,
9064 line_y,
9065 row,
9066 line_height,
9067 whitespace_setting,
9068 window,
9069 cx,
9070 );
9071 }
9072
9073 fn draw_background(
9074 &self,
9075 layout: &EditorLayout,
9076 row: DisplayRow,
9077 content_origin: gpui::Point<Pixels>,
9078 window: &mut Window,
9079 cx: &mut App,
9080 ) {
9081 let line_height = layout.position_map.line_height;
9082 let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
9083
9084 let mut fragment_origin = content_origin
9085 + gpui::point(
9086 Pixels::from(-layout.position_map.scroll_pixel_position.x),
9087 line_y,
9088 );
9089
9090 for fragment in &self.fragments {
9091 match fragment {
9092 LineFragment::Text(line) => {
9093 line.paint_background(
9094 fragment_origin,
9095 line_height,
9096 layout.text_align,
9097 Some(layout.content_width),
9098 window,
9099 cx,
9100 )
9101 .log_err();
9102 fragment_origin.x += line.width;
9103 }
9104 LineFragment::Element { size, .. } => {
9105 fragment_origin.x += size.width;
9106 }
9107 }
9108 }
9109 }
9110
9111 fn draw_invisibles(
9112 &self,
9113 selection_ranges: &[Range<DisplayPoint>],
9114 layout: &EditorLayout,
9115 content_origin: gpui::Point<Pixels>,
9116 line_y: Pixels,
9117 row: DisplayRow,
9118 line_height: Pixels,
9119 whitespace_setting: ShowWhitespaceSetting,
9120 window: &mut Window,
9121 cx: &mut App,
9122 ) {
9123 let extract_whitespace_info = |invisible: &Invisible| {
9124 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
9125 Invisible::Tab {
9126 line_start_offset,
9127 line_end_offset,
9128 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
9129 Invisible::Whitespace { line_offset } => {
9130 (*line_offset, line_offset + 1, &layout.space_invisible)
9131 }
9132 };
9133
9134 let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
9135 let invisible_offset: ScrollPixelOffset =
9136 ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
9137 .into();
9138 let origin = content_origin
9139 + gpui::point(
9140 Pixels::from(
9141 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
9142 ),
9143 line_y,
9144 );
9145
9146 (
9147 [token_offset, token_end_offset],
9148 Box::new(move |window: &mut Window, cx: &mut App| {
9149 invisible_symbol
9150 .paint(origin, line_height, TextAlign::Left, None, window, cx)
9151 .log_err();
9152 }),
9153 )
9154 };
9155
9156 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
9157 match whitespace_setting {
9158 ShowWhitespaceSetting::None => (),
9159 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
9160 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
9161 let invisible_point = DisplayPoint::new(row, start as u32);
9162 if !selection_ranges
9163 .iter()
9164 .any(|region| region.start <= invisible_point && invisible_point < region.end)
9165 {
9166 return;
9167 }
9168
9169 paint(window, cx);
9170 }),
9171
9172 ShowWhitespaceSetting::Trailing => {
9173 let mut previous_start = self.len;
9174 for ([start, end], paint) in invisible_iter.rev() {
9175 if previous_start != end {
9176 break;
9177 }
9178 previous_start = start;
9179 paint(window, cx);
9180 }
9181 }
9182
9183 // For a whitespace to be on a boundary, any of the following conditions need to be met:
9184 // - It is a tab
9185 // - It is adjacent to an edge (start or end)
9186 // - It is adjacent to a whitespace (left or right)
9187 ShowWhitespaceSetting::Boundary => {
9188 // 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
9189 // the above cases.
9190 // Note: We zip in the original `invisibles` to check for tab equality
9191 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
9192 for (([start, end], paint), invisible) in
9193 invisible_iter.zip_eq(self.invisibles.iter())
9194 {
9195 let should_render = match (&last_seen, invisible) {
9196 (_, Invisible::Tab { .. }) => true,
9197 (Some((_, last_end, _)), _) => *last_end == start,
9198 _ => false,
9199 };
9200
9201 if should_render || start == 0 || end == self.len {
9202 paint(window, cx);
9203
9204 // Since we are scanning from the left, we will skip over the first available whitespace that is part
9205 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
9206 if let Some((should_render_last, last_end, paint_last)) = last_seen {
9207 // Note that we need to make sure that the last one is actually adjacent
9208 if !should_render_last && last_end == start {
9209 paint_last(window, cx);
9210 }
9211 }
9212 }
9213
9214 // Manually render anything within a selection
9215 let invisible_point = DisplayPoint::new(row, start as u32);
9216 if selection_ranges.iter().any(|region| {
9217 region.start <= invisible_point && invisible_point < region.end
9218 }) {
9219 paint(window, cx);
9220 }
9221
9222 last_seen = Some((should_render, end, paint));
9223 }
9224 }
9225 }
9226 }
9227
9228 pub fn x_for_index(&self, index: usize) -> Pixels {
9229 let mut fragment_start_x = Pixels::ZERO;
9230 let mut fragment_start_index = 0;
9231
9232 for fragment in &self.fragments {
9233 match fragment {
9234 LineFragment::Text(shaped_line) => {
9235 let fragment_end_index = fragment_start_index + shaped_line.len;
9236 if index < fragment_end_index {
9237 return fragment_start_x
9238 + shaped_line.x_for_index(index - fragment_start_index);
9239 }
9240 fragment_start_x += shaped_line.width;
9241 fragment_start_index = fragment_end_index;
9242 }
9243 LineFragment::Element { len, size, .. } => {
9244 let fragment_end_index = fragment_start_index + len;
9245 if index < fragment_end_index {
9246 return fragment_start_x;
9247 }
9248 fragment_start_x += size.width;
9249 fragment_start_index = fragment_end_index;
9250 }
9251 }
9252 }
9253
9254 fragment_start_x
9255 }
9256
9257 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
9258 let mut fragment_start_x = Pixels::ZERO;
9259 let mut fragment_start_index = 0;
9260
9261 for fragment in &self.fragments {
9262 match fragment {
9263 LineFragment::Text(shaped_line) => {
9264 let fragment_end_x = fragment_start_x + shaped_line.width;
9265 if x < fragment_end_x {
9266 return Some(
9267 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
9268 );
9269 }
9270 fragment_start_x = fragment_end_x;
9271 fragment_start_index += shaped_line.len;
9272 }
9273 LineFragment::Element { len, size, .. } => {
9274 let fragment_end_x = fragment_start_x + size.width;
9275 if x < fragment_end_x {
9276 return Some(fragment_start_index);
9277 }
9278 fragment_start_index += len;
9279 fragment_start_x = fragment_end_x;
9280 }
9281 }
9282 }
9283
9284 None
9285 }
9286
9287 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
9288 let mut fragment_start_index = 0;
9289
9290 for fragment in &self.fragments {
9291 match fragment {
9292 LineFragment::Text(shaped_line) => {
9293 let fragment_end_index = fragment_start_index + shaped_line.len;
9294 if index < fragment_end_index {
9295 return shaped_line.font_id_for_index(index - fragment_start_index);
9296 }
9297 fragment_start_index = fragment_end_index;
9298 }
9299 LineFragment::Element { len, .. } => {
9300 let fragment_end_index = fragment_start_index + len;
9301 if index < fragment_end_index {
9302 return None;
9303 }
9304 fragment_start_index = fragment_end_index;
9305 }
9306 }
9307 }
9308
9309 None
9310 }
9311
9312 pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
9313 let line_width = self.width;
9314 match text_align {
9315 TextAlign::Left => px(0.0),
9316 TextAlign::Center => (content_width - line_width) / 2.0,
9317 TextAlign::Right => content_width - line_width,
9318 }
9319 }
9320}
9321
9322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9323enum Invisible {
9324 /// A tab character
9325 ///
9326 /// A tab character is internally represented by spaces (configured by the user's tab width)
9327 /// aligned to the nearest column, so it's necessary to store the start and end offset for
9328 /// adjacency checks.
9329 Tab {
9330 line_start_offset: usize,
9331 line_end_offset: usize,
9332 },
9333 Whitespace {
9334 line_offset: usize,
9335 },
9336}
9337
9338impl EditorElement {
9339 /// Returns the rem size to use when rendering the [`EditorElement`].
9340 ///
9341 /// This allows UI elements to scale based on the `buffer_font_size`.
9342 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
9343 match self.editor.read(cx).mode {
9344 EditorMode::Full {
9345 scale_ui_elements_with_buffer_font_size: true,
9346 ..
9347 }
9348 | EditorMode::Minimap { .. } => {
9349 let buffer_font_size = self.style.text.font_size;
9350 match buffer_font_size {
9351 AbsoluteLength::Pixels(pixels) => {
9352 let rem_size_scale = {
9353 // Our default UI font size is 14px on a 16px base scale.
9354 // This means the default UI font size is 0.875rems.
9355 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
9356
9357 // We then determine the delta between a single rem and the default font
9358 // size scale.
9359 let default_font_size_delta = 1. - default_font_size_scale;
9360
9361 // Finally, we add this delta to 1rem to get the scale factor that
9362 // should be used to scale up the UI.
9363 1. + default_font_size_delta
9364 };
9365
9366 Some(pixels * rem_size_scale)
9367 }
9368 AbsoluteLength::Rems(rems) => {
9369 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
9370 }
9371 }
9372 }
9373 // We currently use single-line and auto-height editors in UI contexts,
9374 // so we don't want to scale everything with the buffer font size, as it
9375 // ends up looking off.
9376 _ => None,
9377 }
9378 }
9379
9380 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
9381 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
9382 parent.upgrade()
9383 } else {
9384 Some(self.editor.clone())
9385 }
9386 }
9387}
9388
9389#[derive(Default)]
9390pub struct EditorRequestLayoutState {
9391 // We use prepaint depth to limit the number of times prepaint is
9392 // called recursively. We need this so that we can update stale
9393 // data for e.g. block heights in block map.
9394 prepaint_depth: Rc<Cell<usize>>,
9395}
9396
9397impl EditorRequestLayoutState {
9398 // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
9399 // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
9400 // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
9401 // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
9402 // that subsequent shrinking does not lead to incorrect block placing.
9403 const MAX_PREPAINT_DEPTH: usize = 5;
9404
9405 fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
9406 let depth = self.prepaint_depth.get();
9407 self.prepaint_depth.set(depth + 1);
9408 EditorPrepaintGuard {
9409 prepaint_depth: self.prepaint_depth.clone(),
9410 }
9411 }
9412
9413 fn can_prepaint(&self) -> bool {
9414 self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
9415 }
9416}
9417
9418struct EditorPrepaintGuard {
9419 prepaint_depth: Rc<Cell<usize>>,
9420}
9421
9422impl Drop for EditorPrepaintGuard {
9423 fn drop(&mut self) {
9424 let depth = self.prepaint_depth.get();
9425 self.prepaint_depth.set(depth.saturating_sub(1));
9426 }
9427}
9428
9429impl Element for EditorElement {
9430 type RequestLayoutState = EditorRequestLayoutState;
9431 type PrepaintState = EditorLayout;
9432
9433 fn id(&self) -> Option<ElementId> {
9434 None
9435 }
9436
9437 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
9438 None
9439 }
9440
9441 fn request_layout(
9442 &mut self,
9443 _: Option<&GlobalElementId>,
9444 _inspector_id: Option<&gpui::InspectorElementId>,
9445 window: &mut Window,
9446 cx: &mut App,
9447 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
9448 let rem_size = self.rem_size(cx);
9449 window.with_rem_size(rem_size, |window| {
9450 self.editor.update(cx, |editor, cx| {
9451 editor.set_style(self.style.clone(), window, cx);
9452
9453 let layout_id = match editor.mode {
9454 EditorMode::SingleLine => {
9455 let rem_size = window.rem_size();
9456 let height = self.style.text.line_height_in_pixels(rem_size);
9457 let mut style = Style::default();
9458 style.size.height = height.into();
9459 style.size.width = relative(1.).into();
9460 window.request_layout(style, None, cx)
9461 }
9462 EditorMode::AutoHeight {
9463 min_lines,
9464 max_lines,
9465 } => {
9466 let editor_handle = cx.entity();
9467 window.request_measured_layout(
9468 Style::default(),
9469 move |known_dimensions, available_space, window, cx| {
9470 editor_handle
9471 .update(cx, |editor, cx| {
9472 compute_auto_height_layout(
9473 editor,
9474 min_lines,
9475 max_lines,
9476 known_dimensions,
9477 available_space.width,
9478 window,
9479 cx,
9480 )
9481 })
9482 .unwrap_or_default()
9483 },
9484 )
9485 }
9486 EditorMode::Minimap { .. } => {
9487 let mut style = Style::default();
9488 style.size.width = relative(1.).into();
9489 style.size.height = relative(1.).into();
9490 window.request_layout(style, None, cx)
9491 }
9492 EditorMode::Full {
9493 sizing_behavior, ..
9494 } => {
9495 let mut style = Style::default();
9496 style.size.width = relative(1.).into();
9497 if sizing_behavior == SizingBehavior::SizeByContent {
9498 let snapshot = editor.snapshot(window, cx);
9499 let line_height =
9500 self.style.text.line_height_in_pixels(window.rem_size());
9501 let scroll_height =
9502 (snapshot.max_point().row().next_row().0 as f32) * line_height;
9503 style.size.height = scroll_height.into();
9504 } else {
9505 style.size.height = relative(1.).into();
9506 }
9507 window.request_layout(style, None, cx)
9508 }
9509 };
9510
9511 (layout_id, EditorRequestLayoutState::default())
9512 })
9513 })
9514 }
9515
9516 fn prepaint(
9517 &mut self,
9518 _: Option<&GlobalElementId>,
9519 _inspector_id: Option<&gpui::InspectorElementId>,
9520 bounds: Bounds<Pixels>,
9521 request_layout: &mut Self::RequestLayoutState,
9522 window: &mut Window,
9523 cx: &mut App,
9524 ) -> Self::PrepaintState {
9525 let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
9526 let text_style = TextStyleRefinement {
9527 font_size: Some(self.style.text.font_size),
9528 line_height: Some(self.style.text.line_height),
9529 ..Default::default()
9530 };
9531
9532 let is_minimap = self.editor.read(cx).mode.is_minimap();
9533 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
9534
9535 if !is_minimap {
9536 let focus_handle = self.editor.focus_handle(cx);
9537 window.set_view_id(self.editor.entity_id());
9538 window.set_focus_handle(&focus_handle, cx);
9539 }
9540
9541 let rem_size = self.rem_size(cx);
9542 window.with_rem_size(rem_size, |window| {
9543 window.with_text_style(Some(text_style), |window| {
9544 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9545 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
9546 (editor.snapshot(window, cx), editor.read_only(cx))
9547 });
9548 let style = &self.style;
9549
9550 let rem_size = window.rem_size();
9551 let font_id = window.text_system().resolve_font(&style.text.font());
9552 let font_size = style.text.font_size.to_pixels(rem_size);
9553 let line_height = style.text.line_height_in_pixels(rem_size);
9554 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
9555 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
9556 let em_layout_width = window.text_system().em_layout_width(font_id, font_size);
9557 let glyph_grid_cell = size(em_advance, line_height);
9558
9559 let gutter_dimensions =
9560 snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
9561 let text_width = bounds.size.width - gutter_dimensions.width;
9562
9563 let settings = EditorSettings::get_global(cx);
9564 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
9565 let vertical_scrollbar_width = (scrollbars_shown
9566 && settings.scrollbar.axes.vertical
9567 && self.editor.read(cx).show_scrollbars.vertical)
9568 .then_some(style.scrollbar_width)
9569 .unwrap_or_default();
9570 let minimap_width = self
9571 .get_minimap_width(
9572 &settings.minimap,
9573 scrollbars_shown,
9574 text_width,
9575 em_width,
9576 font_size,
9577 rem_size,
9578 cx,
9579 )
9580 .unwrap_or_default();
9581
9582 let right_margin = minimap_width + vertical_scrollbar_width;
9583
9584 let editor_width =
9585 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
9586 let editor_margins = EditorMargins {
9587 gutter: gutter_dimensions,
9588 right: right_margin,
9589 };
9590
9591 snapshot = self.editor.update(cx, |editor, cx| {
9592 editor.last_bounds = Some(bounds);
9593 editor.gutter_dimensions = gutter_dimensions;
9594 editor.set_visible_line_count(
9595 (bounds.size.height / line_height) as f64,
9596 window,
9597 cx,
9598 );
9599 editor.set_visible_column_count(f64::from(editor_width / em_advance));
9600
9601 if matches!(
9602 editor.mode,
9603 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
9604 ) {
9605 snapshot
9606 } else {
9607 let wrap_width = calculate_wrap_width(
9608 editor.soft_wrap_mode(cx),
9609 editor_width,
9610 em_layout_width,
9611 );
9612
9613 if editor.set_wrap_width(wrap_width, cx) {
9614 editor.snapshot(window, cx)
9615 } else {
9616 snapshot
9617 }
9618 }
9619 });
9620
9621 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
9622 let gutter_hitbox = window.insert_hitbox(
9623 gutter_bounds(bounds, gutter_dimensions),
9624 HitboxBehavior::Normal,
9625 );
9626 let text_hitbox = window.insert_hitbox(
9627 Bounds {
9628 origin: gutter_hitbox.top_right(),
9629 size: size(text_width, bounds.size.height),
9630 },
9631 HitboxBehavior::Normal,
9632 );
9633
9634 // Offset the content_bounds from the text_bounds by the gutter margin (which
9635 // is roughly half a character wide) to make hit testing work more like how we want.
9636 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
9637 let content_origin = text_hitbox.origin + content_offset;
9638
9639 let height_in_lines = f64::from(bounds.size.height / line_height);
9640 let max_row = snapshot.max_point().row().as_f64();
9641
9642 // Calculate how much of the editor is clipped by parent containers (e.g., List).
9643 // This allows us to only render lines that are actually visible, which is
9644 // critical for performance when large AutoHeight editors are inside Lists.
9645 let visible_bounds = window.content_mask().bounds;
9646 let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
9647 let clipped_top_in_lines = f64::from(clipped_top / line_height);
9648 let visible_height_in_lines =
9649 f64::from(visible_bounds.size.height / line_height);
9650
9651 // The max scroll position for the top of the window
9652 let max_scroll_top = if matches!(
9653 snapshot.mode,
9654 EditorMode::SingleLine
9655 | EditorMode::AutoHeight { .. }
9656 | EditorMode::Full {
9657 sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
9658 | SizingBehavior::SizeByContent,
9659 ..
9660 }
9661 ) {
9662 (max_row - height_in_lines + 1.).max(0.)
9663 } else {
9664 let settings = EditorSettings::get_global(cx);
9665 match settings.scroll_beyond_last_line {
9666 ScrollBeyondLastLine::OnePage => max_row,
9667 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
9668 ScrollBeyondLastLine::VerticalScrollMargin => {
9669 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
9670 .max(0.)
9671 }
9672 }
9673 };
9674
9675 let (
9676 autoscroll_request,
9677 autoscroll_containing_element,
9678 needs_horizontal_autoscroll,
9679 ) = self.editor.update(cx, |editor, cx| {
9680 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
9681
9682 let autoscroll_containing_element =
9683 autoscroll_request.is_some() || editor.has_pending_selection();
9684
9685 let (needs_horizontal_autoscroll, was_scrolled) = editor
9686 .autoscroll_vertically(
9687 bounds,
9688 line_height,
9689 max_scroll_top,
9690 autoscroll_request,
9691 window,
9692 cx,
9693 );
9694 if was_scrolled.0 {
9695 snapshot = editor.snapshot(window, cx);
9696 }
9697 (
9698 autoscroll_request,
9699 autoscroll_containing_element,
9700 needs_horizontal_autoscroll,
9701 )
9702 });
9703
9704 let mut scroll_position = snapshot.scroll_position();
9705 // The scroll position is a fractional point, the whole number of which represents
9706 // the top of the window in terms of display rows.
9707 // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
9708 // but we don't modify scroll_position itself since the parent handles positioning.
9709 let max_row = snapshot.max_point().row();
9710 let start_row = cmp::min(
9711 DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
9712 max_row,
9713 );
9714 let end_row = cmp::min(
9715 (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
9716 as u32,
9717 max_row.next_row().0,
9718 );
9719 let end_row = DisplayRow(end_row);
9720
9721 let row_infos = snapshot // note we only get the visual range
9722 .row_infos(start_row)
9723 .take((start_row..end_row).len())
9724 .collect::<Vec<RowInfo>>();
9725 let is_row_soft_wrapped = |row: usize| {
9726 row_infos
9727 .get(row)
9728 .is_none_or(|info| info.buffer_row.is_none())
9729 };
9730
9731 let start_anchor = if start_row == Default::default() {
9732 Anchor::min()
9733 } else {
9734 snapshot.buffer_snapshot().anchor_before(
9735 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
9736 )
9737 };
9738 let end_anchor = if end_row > max_row {
9739 Anchor::max()
9740 } else {
9741 snapshot.buffer_snapshot().anchor_before(
9742 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
9743 )
9744 };
9745
9746 let mut highlighted_rows = self
9747 .editor
9748 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
9749
9750 let is_light = cx.theme().appearance().is_light();
9751
9752 let mut highlighted_ranges = self
9753 .editor_with_selections(cx)
9754 .map(|editor| {
9755 editor.read(cx).background_highlights_in_range(
9756 start_anchor..end_anchor,
9757 &snapshot.display_snapshot,
9758 cx.theme(),
9759 )
9760 })
9761 .unwrap_or_default();
9762
9763 for (ix, row_info) in row_infos.iter().enumerate() {
9764 let Some(diff_status) = row_info.diff_status else {
9765 continue;
9766 };
9767
9768 let background_color = match diff_status.kind {
9769 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
9770 DiffHunkStatusKind::Deleted => {
9771 cx.theme().colors().version_control_deleted
9772 }
9773 DiffHunkStatusKind::Modified => {
9774 debug_panic!("modified diff status for row info");
9775 continue;
9776 }
9777 };
9778
9779 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
9780
9781 let hollow_highlight = LineHighlight {
9782 background: (background_color.opacity(if is_light {
9783 0.08
9784 } else {
9785 0.06
9786 }))
9787 .into(),
9788 border: Some(if is_light {
9789 background_color.opacity(0.48)
9790 } else {
9791 background_color.opacity(0.36)
9792 }),
9793 include_gutter: true,
9794 type_id: None,
9795 };
9796
9797 let filled_highlight = LineHighlight {
9798 background: solid_background(background_color.opacity(hunk_opacity)),
9799 border: None,
9800 include_gutter: true,
9801 type_id: None,
9802 };
9803
9804 let background = if Self::diff_hunk_hollow(diff_status, cx) {
9805 hollow_highlight
9806 } else {
9807 filled_highlight
9808 };
9809
9810 let base_display_point =
9811 DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
9812
9813 highlighted_rows
9814 .entry(base_display_point.row())
9815 .or_insert(background);
9816 }
9817
9818 // Add diff review drag selection highlight to text area
9819 if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
9820 let range = drag_state.row_range(&snapshot.display_snapshot);
9821 let start_row = range.start().0;
9822 let end_row = range.end().0;
9823 let drag_highlight_color =
9824 cx.theme().colors().editor_active_line_background;
9825 let drag_highlight = LineHighlight {
9826 background: solid_background(drag_highlight_color),
9827 border: Some(cx.theme().colors().border_focused),
9828 include_gutter: true,
9829 type_id: None,
9830 };
9831 for row_num in start_row..=end_row {
9832 highlighted_rows
9833 .entry(DisplayRow(row_num))
9834 .or_insert(drag_highlight);
9835 }
9836 }
9837
9838 let highlighted_gutter_ranges =
9839 self.editor.read(cx).gutter_highlights_in_range(
9840 start_anchor..end_anchor,
9841 &snapshot.display_snapshot,
9842 cx,
9843 );
9844
9845 let document_colors = self
9846 .editor
9847 .read(cx)
9848 .colors
9849 .as_ref()
9850 .map(|colors| colors.editor_display_highlights(&snapshot));
9851 let redacted_ranges = self.editor.read(cx).redacted_ranges(
9852 start_anchor..end_anchor,
9853 &snapshot.display_snapshot,
9854 cx,
9855 );
9856
9857 let (local_selections, selected_buffer_ids, latest_selection_anchors): (
9858 Vec<Selection<Point>>,
9859 Vec<BufferId>,
9860 HashMap<BufferId, Anchor>,
9861 ) = self
9862 .editor_with_selections(cx)
9863 .map(|editor| {
9864 editor.update(cx, |editor, cx| {
9865 let all_selections =
9866 editor.selections.all::<Point>(&snapshot.display_snapshot);
9867 let all_anchor_selections =
9868 editor.selections.all_anchors(&snapshot.display_snapshot);
9869 let selected_buffer_ids =
9870 if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
9871 Vec::new()
9872 } else {
9873 let mut selected_buffer_ids =
9874 Vec::with_capacity(all_selections.len());
9875
9876 for selection in all_selections {
9877 for buffer_id in snapshot
9878 .buffer_snapshot()
9879 .buffer_ids_for_range(selection.range())
9880 {
9881 if selected_buffer_ids.last() != Some(&buffer_id) {
9882 selected_buffer_ids.push(buffer_id);
9883 }
9884 }
9885 }
9886
9887 selected_buffer_ids
9888 };
9889
9890 let mut selections = editor.selections.disjoint_in_range(
9891 start_anchor..end_anchor,
9892 &snapshot.display_snapshot,
9893 );
9894 selections
9895 .extend(editor.selections.pending(&snapshot.display_snapshot));
9896
9897 let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
9898 HashMap::default();
9899 for selection in all_anchor_selections.iter() {
9900 let head = selection.head();
9901 if let Some(buffer_id) = head.text_anchor.buffer_id {
9902 anchors_by_buffer
9903 .entry(buffer_id)
9904 .and_modify(|(latest_id, latest_anchor)| {
9905 if selection.id > *latest_id {
9906 *latest_id = selection.id;
9907 *latest_anchor = head;
9908 }
9909 })
9910 .or_insert((selection.id, head));
9911 }
9912 }
9913 let latest_selection_anchors = anchors_by_buffer
9914 .into_iter()
9915 .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
9916 .collect();
9917
9918 (selections, selected_buffer_ids, latest_selection_anchors)
9919 })
9920 })
9921 .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
9922
9923 let (selections, mut active_rows, newest_selection_head) = self
9924 .layout_selections(
9925 start_anchor,
9926 end_anchor,
9927 &local_selections,
9928 &snapshot,
9929 start_row,
9930 end_row,
9931 window,
9932 cx,
9933 );
9934
9935 // relative rows are based on newest selection, even outside the visible area
9936 let current_selection_head = self.editor.update(cx, |editor, cx| {
9937 (editor.selections.count() != 0).then(|| {
9938 let newest = editor
9939 .selections
9940 .newest::<Point>(&editor.display_snapshot(cx));
9941
9942 SelectionLayout::new(
9943 newest,
9944 editor.selections.line_mode(),
9945 editor.cursor_offset_on_selection,
9946 editor.cursor_shape,
9947 &snapshot,
9948 true,
9949 true,
9950 None,
9951 )
9952 .head
9953 .row()
9954 })
9955 });
9956
9957 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
9958 editor.active_breakpoints(start_row..end_row, window, cx)
9959 });
9960 for (display_row, (_, bp, state)) in &breakpoint_rows {
9961 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
9962 active_rows.entry(*display_row).or_default().breakpoint = true;
9963 }
9964 }
9965
9966 let line_numbers = self.layout_line_numbers(
9967 Some(&gutter_hitbox),
9968 gutter_dimensions,
9969 line_height,
9970 scroll_position,
9971 start_row..end_row,
9972 &row_infos,
9973 &active_rows,
9974 current_selection_head,
9975 &snapshot,
9976 window,
9977 cx,
9978 );
9979
9980 // We add the gutter breakpoint indicator to breakpoint_rows after painting
9981 // line numbers so we don't paint a line number debug accent color if a user
9982 // has their mouse over that line when a breakpoint isn't there
9983 self.editor.update(cx, |editor, _| {
9984 if let Some(phantom_breakpoint) = &mut editor
9985 .gutter_breakpoint_indicator
9986 .0
9987 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
9988 {
9989 // Is there a non-phantom breakpoint on this line?
9990 phantom_breakpoint.collides_with_existing_breakpoint = true;
9991 breakpoint_rows
9992 .entry(phantom_breakpoint.display_row)
9993 .or_insert_with(|| {
9994 let position = snapshot.display_point_to_anchor(
9995 DisplayPoint::new(phantom_breakpoint.display_row, 0),
9996 Bias::Right,
9997 );
9998 let breakpoint = Breakpoint::new_standard();
9999 phantom_breakpoint.collides_with_existing_breakpoint = false;
10000 (position, breakpoint, None)
10001 });
10002 }
10003 });
10004
10005 let mut expand_toggles =
10006 window.with_element_namespace("expand_toggles", |window| {
10007 self.layout_expand_toggles(
10008 &gutter_hitbox,
10009 gutter_dimensions,
10010 em_width,
10011 line_height,
10012 scroll_position,
10013 &row_infos,
10014 window,
10015 cx,
10016 )
10017 });
10018
10019 let mut crease_toggles =
10020 window.with_element_namespace("crease_toggles", |window| {
10021 self.layout_crease_toggles(
10022 start_row..end_row,
10023 &row_infos,
10024 &active_rows,
10025 &snapshot,
10026 window,
10027 cx,
10028 )
10029 });
10030 let crease_trailers =
10031 window.with_element_namespace("crease_trailers", |window| {
10032 self.layout_crease_trailers(
10033 row_infos.iter().cloned(),
10034 &snapshot,
10035 window,
10036 cx,
10037 )
10038 });
10039
10040 let display_hunks = self.layout_gutter_diff_hunks(
10041 line_height,
10042 &gutter_hitbox,
10043 start_row..end_row,
10044 &snapshot,
10045 window,
10046 cx,
10047 );
10048
10049 Self::layout_word_diff_highlights(
10050 &display_hunks,
10051 &row_infos,
10052 start_row,
10053 &snapshot,
10054 &mut highlighted_ranges,
10055 cx,
10056 );
10057
10058 let merged_highlighted_ranges =
10059 if let Some((_, colors)) = document_colors.as_ref() {
10060 &highlighted_ranges
10061 .clone()
10062 .into_iter()
10063 .chain(colors.clone())
10064 .collect()
10065 } else {
10066 &highlighted_ranges
10067 };
10068 let bg_segments_per_row = Self::bg_segments_per_row(
10069 start_row..end_row,
10070 &selections,
10071 &merged_highlighted_ranges,
10072 self.style.background,
10073 );
10074
10075 let mut line_layouts = Self::layout_lines(
10076 start_row..end_row,
10077 &snapshot,
10078 &self.style,
10079 editor_width,
10080 is_row_soft_wrapped,
10081 &bg_segments_per_row,
10082 window,
10083 cx,
10084 );
10085 let new_renderer_widths = (!is_minimap).then(|| {
10086 line_layouts
10087 .iter()
10088 .flat_map(|layout| &layout.fragments)
10089 .filter_map(|fragment| {
10090 if let LineFragment::Element { id, size, .. } = fragment {
10091 Some((*id, size.width))
10092 } else {
10093 None
10094 }
10095 })
10096 });
10097 if new_renderer_widths.is_some_and(|new_renderer_widths| {
10098 self.editor.update(cx, |editor, cx| {
10099 editor.update_renderer_widths(new_renderer_widths, cx)
10100 })
10101 }) {
10102 // If the fold widths have changed, we need to prepaint
10103 // the element again to account for any changes in
10104 // wrapping.
10105 if request_layout.can_prepaint() {
10106 return self.prepaint(
10107 None,
10108 _inspector_id,
10109 bounds,
10110 request_layout,
10111 window,
10112 cx,
10113 );
10114 } else {
10115 debug_panic!(concat!(
10116 "skipping recursive prepaint at max depth. ",
10117 "renderer widths may be stale."
10118 ));
10119 }
10120 }
10121
10122 let longest_line_blame_width = self
10123 .editor
10124 .update(cx, |editor, cx| {
10125 if !editor.show_git_blame_inline {
10126 return None;
10127 }
10128 let blame = editor.blame.as_ref()?;
10129 let (_, blame_entry) = blame
10130 .update(cx, |blame, cx| {
10131 let row_infos =
10132 snapshot.row_infos(snapshot.longest_row()).next()?;
10133 blame.blame_for_rows(&[row_infos], cx).next()
10134 })
10135 .flatten()?;
10136 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
10137 let inline_blame_padding =
10138 ProjectSettings::get_global(cx).git.inline_blame.padding as f32
10139 * em_advance;
10140 Some(
10141 element
10142 .layout_as_root(AvailableSpace::min_size(), window, cx)
10143 .width
10144 + inline_blame_padding,
10145 )
10146 })
10147 .unwrap_or(Pixels::ZERO);
10148
10149 let longest_line_width = layout_line(
10150 snapshot.longest_row(),
10151 &snapshot,
10152 style,
10153 editor_width,
10154 is_row_soft_wrapped,
10155 window,
10156 cx,
10157 )
10158 .width;
10159
10160 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
10161 text_hitbox.bounds,
10162 glyph_grid_cell,
10163 size(
10164 longest_line_width,
10165 Pixels::from(max_row.as_f64() * f64::from(line_height)),
10166 ),
10167 longest_line_blame_width,
10168 EditorSettings::get_global(cx),
10169 );
10170
10171 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
10172
10173 let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
10174 snapshot.sticky_header_excerpt(scroll_position.y)
10175 } else {
10176 None
10177 };
10178 let sticky_header_excerpt_id =
10179 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
10180
10181 let blocks = (!is_minimap)
10182 .then(|| {
10183 window.with_element_namespace("blocks", |window| {
10184 self.render_blocks(
10185 start_row..end_row,
10186 &snapshot,
10187 &hitbox,
10188 &text_hitbox,
10189 editor_width,
10190 &mut scroll_width,
10191 &editor_margins,
10192 em_width,
10193 gutter_dimensions.full_width(),
10194 line_height,
10195 &mut line_layouts,
10196 &local_selections,
10197 &selected_buffer_ids,
10198 &latest_selection_anchors,
10199 is_row_soft_wrapped,
10200 sticky_header_excerpt_id,
10201 window,
10202 cx,
10203 )
10204 })
10205 })
10206 .unwrap_or_default();
10207 let RenderBlocksOutput {
10208 mut blocks,
10209 row_block_types,
10210 resized_blocks,
10211 } = blocks;
10212 if let Some(resized_blocks) = resized_blocks {
10213 self.editor.update(cx, |editor, cx| {
10214 editor.resize_blocks(
10215 resized_blocks,
10216 autoscroll_request.map(|(autoscroll, _)| autoscroll),
10217 cx,
10218 )
10219 });
10220 if request_layout.can_prepaint() {
10221 return self.prepaint(
10222 None,
10223 _inspector_id,
10224 bounds,
10225 request_layout,
10226 window,
10227 cx,
10228 );
10229 } else {
10230 debug_panic!(concat!(
10231 "skipping recursive prepaint at max depth. ",
10232 "block layout may be stale."
10233 ));
10234 }
10235 }
10236
10237 let sticky_buffer_header = if self.should_show_buffer_headers() {
10238 sticky_header_excerpt.map(|sticky_header_excerpt| {
10239 window.with_element_namespace("blocks", |window| {
10240 self.layout_sticky_buffer_header(
10241 sticky_header_excerpt,
10242 scroll_position,
10243 line_height,
10244 right_margin,
10245 &snapshot,
10246 &hitbox,
10247 &selected_buffer_ids,
10248 &blocks,
10249 &latest_selection_anchors,
10250 window,
10251 cx,
10252 )
10253 })
10254 })
10255 } else {
10256 None
10257 };
10258
10259 let start_buffer_row =
10260 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot()).row);
10261 let end_buffer_row =
10262 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot()).row);
10263
10264 let scroll_max: gpui::Point<ScrollPixelOffset> = point(
10265 ScrollPixelOffset::from(
10266 ((scroll_width - editor_width) / em_layout_width).max(0.0),
10267 ),
10268 max_scroll_top,
10269 );
10270
10271 self.editor.update(cx, |editor, cx| {
10272 if editor.scroll_manager.clamp_scroll_left(scroll_max.x, cx) {
10273 scroll_position.x = scroll_max.x.min(scroll_position.x);
10274 }
10275
10276 if needs_horizontal_autoscroll.0
10277 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
10278 start_row,
10279 editor_width,
10280 scroll_width,
10281 em_advance,
10282 &line_layouts,
10283 autoscroll_request,
10284 window,
10285 cx,
10286 )
10287 {
10288 scroll_position = new_scroll_position;
10289 }
10290 });
10291
10292 let scroll_pixel_position = point(
10293 scroll_position.x * f64::from(em_layout_width),
10294 scroll_position.y * f64::from(line_height),
10295 );
10296 let sticky_headers = if !is_minimap
10297 && is_singleton
10298 && EditorSettings::get_global(cx).sticky_scroll.enabled
10299 {
10300 let relative = self.editor.read(cx).relative_line_numbers(cx);
10301 self.layout_sticky_headers(
10302 &snapshot,
10303 editor_width,
10304 is_row_soft_wrapped,
10305 line_height,
10306 scroll_pixel_position,
10307 content_origin,
10308 &gutter_dimensions,
10309 &gutter_hitbox,
10310 &text_hitbox,
10311 relative,
10312 current_selection_head,
10313 window,
10314 cx,
10315 )
10316 } else {
10317 None
10318 };
10319 self.editor.update(cx, |editor, _| {
10320 editor.scroll_manager.set_sticky_header_line_count(
10321 sticky_headers.as_ref().map_or(0, |h| h.lines.len()),
10322 );
10323 });
10324 let indent_guides = self.layout_indent_guides(
10325 content_origin,
10326 text_hitbox.origin,
10327 start_buffer_row..end_buffer_row,
10328 scroll_pixel_position,
10329 line_height,
10330 &snapshot,
10331 window,
10332 cx,
10333 );
10334
10335 let crease_trailers =
10336 window.with_element_namespace("crease_trailers", |window| {
10337 self.prepaint_crease_trailers(
10338 crease_trailers,
10339 &line_layouts,
10340 line_height,
10341 content_origin,
10342 scroll_pixel_position,
10343 em_width,
10344 window,
10345 cx,
10346 )
10347 });
10348
10349 let (edit_prediction_popover, edit_prediction_popover_origin) = self
10350 .editor
10351 .update(cx, |editor, cx| {
10352 editor.render_edit_prediction_popover(
10353 &text_hitbox.bounds,
10354 content_origin,
10355 right_margin,
10356 &snapshot,
10357 start_row..end_row,
10358 scroll_position.y,
10359 scroll_position.y + height_in_lines,
10360 &line_layouts,
10361 line_height,
10362 scroll_position,
10363 scroll_pixel_position,
10364 newest_selection_head,
10365 editor_width,
10366 style,
10367 window,
10368 cx,
10369 )
10370 })
10371 .unzip();
10372
10373 let mut inline_diagnostics = self.layout_inline_diagnostics(
10374 &line_layouts,
10375 &crease_trailers,
10376 &row_block_types,
10377 content_origin,
10378 scroll_position,
10379 scroll_pixel_position,
10380 edit_prediction_popover_origin,
10381 start_row,
10382 end_row,
10383 line_height,
10384 em_width,
10385 style,
10386 window,
10387 cx,
10388 );
10389
10390 let mut inline_blame_layout = None;
10391 let mut inline_code_actions = None;
10392 if let Some(newest_selection_head) = newest_selection_head {
10393 let display_row = newest_selection_head.row();
10394 if (start_row..end_row).contains(&display_row)
10395 && !row_block_types.contains_key(&display_row)
10396 {
10397 inline_code_actions = self.layout_inline_code_actions(
10398 newest_selection_head,
10399 content_origin,
10400 scroll_position,
10401 scroll_pixel_position,
10402 line_height,
10403 &snapshot,
10404 window,
10405 cx,
10406 );
10407
10408 let line_ix = display_row.minus(start_row) as usize;
10409 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10410 row_infos.get(line_ix),
10411 line_layouts.get(line_ix),
10412 crease_trailers.get(line_ix),
10413 ) {
10414 let crease_trailer_layout = crease_trailer.as_ref();
10415 if let Some(layout) = self.layout_inline_blame(
10416 display_row,
10417 row_info,
10418 line_layout,
10419 crease_trailer_layout,
10420 em_width,
10421 content_origin,
10422 scroll_position,
10423 scroll_pixel_position,
10424 line_height,
10425 window,
10426 cx,
10427 ) {
10428 inline_blame_layout = Some(layout);
10429 // Blame overrides inline diagnostics
10430 inline_diagnostics.remove(&display_row);
10431 }
10432 } else {
10433 log::error!(
10434 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10435 line_layouts.len(): {}, \
10436 crease_trailers.len(): {}",
10437 line_ix,
10438 row_infos.len(),
10439 line_layouts.len(),
10440 crease_trailers.len(),
10441 );
10442 }
10443 }
10444 }
10445
10446 let blamed_display_rows = self.layout_blame_entries(
10447 &row_infos,
10448 em_width,
10449 scroll_position,
10450 line_height,
10451 &gutter_hitbox,
10452 gutter_dimensions.git_blame_entries_width,
10453 window,
10454 cx,
10455 );
10456
10457 let line_elements = self.prepaint_lines(
10458 start_row,
10459 &mut line_layouts,
10460 line_height,
10461 scroll_position,
10462 scroll_pixel_position,
10463 content_origin,
10464 window,
10465 cx,
10466 );
10467
10468 window.with_element_namespace("blocks", |window| {
10469 self.layout_blocks(
10470 &mut blocks,
10471 &hitbox,
10472 line_height,
10473 scroll_position,
10474 scroll_pixel_position,
10475 window,
10476 cx,
10477 );
10478 });
10479
10480 let cursors = self.collect_cursors(&snapshot, cx);
10481 let visible_row_range = start_row..end_row;
10482 let non_visible_cursors = cursors
10483 .iter()
10484 .any(|c| !visible_row_range.contains(&c.0.row()));
10485
10486 let visible_cursors = self.layout_visible_cursors(
10487 &snapshot,
10488 &selections,
10489 &row_block_types,
10490 start_row..end_row,
10491 &line_layouts,
10492 &text_hitbox,
10493 content_origin,
10494 scroll_position,
10495 scroll_pixel_position,
10496 line_height,
10497 em_width,
10498 em_advance,
10499 autoscroll_containing_element,
10500 &redacted_ranges,
10501 window,
10502 cx,
10503 );
10504
10505 let scrollbars_layout = self.layout_scrollbars(
10506 &snapshot,
10507 &scrollbar_layout_information,
10508 content_offset,
10509 scroll_position,
10510 non_visible_cursors,
10511 right_margin,
10512 editor_width,
10513 window,
10514 cx,
10515 );
10516
10517 let gutter_settings = EditorSettings::get_global(cx).gutter;
10518
10519 let context_menu_layout =
10520 if let Some(newest_selection_head) = newest_selection_head {
10521 let newest_selection_point =
10522 newest_selection_head.to_point(&snapshot.display_snapshot);
10523 if (start_row..end_row).contains(&newest_selection_head.row()) {
10524 self.layout_cursor_popovers(
10525 line_height,
10526 &text_hitbox,
10527 content_origin,
10528 right_margin,
10529 start_row,
10530 scroll_pixel_position,
10531 &line_layouts,
10532 newest_selection_head,
10533 newest_selection_point,
10534 style,
10535 window,
10536 cx,
10537 )
10538 } else {
10539 None
10540 }
10541 } else {
10542 None
10543 };
10544
10545 self.layout_gutter_menu(
10546 line_height,
10547 &text_hitbox,
10548 content_origin,
10549 right_margin,
10550 scroll_pixel_position,
10551 gutter_dimensions.width - gutter_dimensions.left_padding,
10552 window,
10553 cx,
10554 );
10555
10556 let test_indicators = if gutter_settings.runnables {
10557 self.layout_run_indicators(
10558 line_height,
10559 start_row..end_row,
10560 &row_infos,
10561 scroll_position,
10562 &gutter_dimensions,
10563 &gutter_hitbox,
10564 &snapshot,
10565 &mut breakpoint_rows,
10566 window,
10567 cx,
10568 )
10569 } else {
10570 Vec::new()
10571 };
10572
10573 let show_breakpoints = snapshot
10574 .show_breakpoints
10575 .unwrap_or(gutter_settings.breakpoints);
10576 let breakpoints = if show_breakpoints {
10577 self.layout_breakpoints(
10578 line_height,
10579 start_row..end_row,
10580 scroll_position,
10581 &gutter_dimensions,
10582 &gutter_hitbox,
10583 &snapshot,
10584 breakpoint_rows,
10585 &row_infos,
10586 window,
10587 cx,
10588 )
10589 } else {
10590 Vec::new()
10591 };
10592
10593 let git_gutter_width = Self::gutter_strip_width(line_height)
10594 + gutter_dimensions
10595 .git_blame_entries_width
10596 .unwrap_or_default();
10597 let available_width = gutter_dimensions.left_padding - git_gutter_width;
10598
10599 let max_line_number_length = self
10600 .editor
10601 .read(cx)
10602 .buffer()
10603 .read(cx)
10604 .snapshot(cx)
10605 .widest_line_number()
10606 .ilog10()
10607 + 1;
10608
10609 let diff_review_button = self
10610 .should_render_diff_review_button(
10611 start_row..end_row,
10612 &row_infos,
10613 &snapshot,
10614 cx,
10615 )
10616 .map(|(display_row, buffer_row)| {
10617 let is_wide = max_line_number_length
10618 >= EditorSettings::get_global(cx).gutter.min_line_number_digits
10619 as u32
10620 && buffer_row.is_some_and(|row| {
10621 (row + 1).ilog10() + 1 == max_line_number_length
10622 })
10623 || gutter_dimensions.right_padding == px(0.);
10624
10625 let button_width = if is_wide {
10626 available_width - px(6.)
10627 } else {
10628 available_width + em_width - px(6.)
10629 };
10630
10631 let button = self.editor.update(cx, |editor, cx| {
10632 editor
10633 .render_diff_review_button(display_row, button_width, cx)
10634 .into_any_element()
10635 });
10636 prepaint_gutter_button(
10637 button,
10638 display_row,
10639 line_height,
10640 &gutter_dimensions,
10641 scroll_position,
10642 &gutter_hitbox,
10643 window,
10644 cx,
10645 )
10646 });
10647
10648 self.layout_signature_help(
10649 &hitbox,
10650 content_origin,
10651 scroll_pixel_position,
10652 newest_selection_head,
10653 start_row,
10654 &line_layouts,
10655 line_height,
10656 em_width,
10657 context_menu_layout,
10658 window,
10659 cx,
10660 );
10661
10662 if !cx.has_active_drag() {
10663 self.layout_hover_popovers(
10664 &snapshot,
10665 &hitbox,
10666 start_row..end_row,
10667 content_origin,
10668 scroll_pixel_position,
10669 &line_layouts,
10670 line_height,
10671 em_width,
10672 context_menu_layout,
10673 window,
10674 cx,
10675 );
10676
10677 self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10678 }
10679
10680 let mouse_context_menu = self.layout_mouse_context_menu(
10681 &snapshot,
10682 start_row..end_row,
10683 content_origin,
10684 window,
10685 cx,
10686 );
10687
10688 window.with_element_namespace("crease_toggles", |window| {
10689 self.prepaint_crease_toggles(
10690 &mut crease_toggles,
10691 line_height,
10692 &gutter_dimensions,
10693 gutter_settings,
10694 scroll_pixel_position,
10695 &gutter_hitbox,
10696 window,
10697 cx,
10698 )
10699 });
10700
10701 window.with_element_namespace("expand_toggles", |window| {
10702 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10703 });
10704
10705 let wrap_guides = self.layout_wrap_guides(
10706 em_advance,
10707 scroll_position,
10708 content_origin,
10709 scrollbars_layout.as_ref(),
10710 vertical_scrollbar_width,
10711 &hitbox,
10712 window,
10713 cx,
10714 );
10715
10716 let minimap = window.with_element_namespace("minimap", |window| {
10717 self.layout_minimap(
10718 &snapshot,
10719 minimap_width,
10720 scroll_position,
10721 &scrollbar_layout_information,
10722 scrollbars_layout.as_ref(),
10723 window,
10724 cx,
10725 )
10726 });
10727
10728 let invisible_symbol_font_size = font_size / 2.;
10729 let whitespace_map = &self
10730 .editor
10731 .read(cx)
10732 .buffer
10733 .read(cx)
10734 .language_settings(cx)
10735 .whitespace_map;
10736
10737 let tab_char = whitespace_map.tab.clone();
10738 let tab_len = tab_char.len();
10739 let tab_invisible = window.text_system().shape_line(
10740 tab_char,
10741 invisible_symbol_font_size,
10742 &[TextRun {
10743 len: tab_len,
10744 font: self.style.text.font(),
10745 color: cx.theme().colors().editor_invisible,
10746 ..Default::default()
10747 }],
10748 None,
10749 );
10750
10751 let space_char = whitespace_map.space.clone();
10752 let space_len = space_char.len();
10753 let space_invisible = window.text_system().shape_line(
10754 space_char,
10755 invisible_symbol_font_size,
10756 &[TextRun {
10757 len: space_len,
10758 font: self.style.text.font(),
10759 color: cx.theme().colors().editor_invisible,
10760 ..Default::default()
10761 }],
10762 None,
10763 );
10764
10765 let mode = snapshot.mode.clone();
10766
10767 let sticky_scroll_header_height = sticky_headers
10768 .as_ref()
10769 .and_then(|headers| headers.lines.last())
10770 .map_or(Pixels::ZERO, |last| last.offset + line_height);
10771
10772 let sticky_header_height = if sticky_buffer_header.is_some() {
10773 let full_height = FILE_HEADER_HEIGHT as f32 * line_height;
10774 let display_row = blocks
10775 .iter()
10776 .filter(|block| block.is_buffer_header)
10777 .find_map(|block| {
10778 block.row.filter(|row| row.0 > scroll_position.y as u32)
10779 });
10780 let offset = match display_row {
10781 Some(display_row) => {
10782 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
10783 let offset = (scroll_position.y - max_row as f64).max(0.0);
10784 let slide_up =
10785 Pixels::from(offset * ScrollPixelOffset::from(line_height));
10786
10787 (full_height - slide_up).max(Pixels::ZERO)
10788 }
10789 None => full_height,
10790 };
10791 sticky_scroll_header_height + offset
10792 } else {
10793 sticky_scroll_header_height
10794 };
10795
10796 let (diff_hunk_controls, diff_hunk_control_bounds) =
10797 if is_read_only && !self.editor.read(cx).delegate_stage_and_restore {
10798 (vec![], vec![])
10799 } else {
10800 self.layout_diff_hunk_controls(
10801 start_row..end_row,
10802 &row_infos,
10803 &text_hitbox,
10804 current_selection_head,
10805 line_height,
10806 right_margin,
10807 scroll_pixel_position,
10808 sticky_header_height,
10809 &display_hunks,
10810 &highlighted_rows,
10811 self.editor.clone(),
10812 window,
10813 cx,
10814 )
10815 };
10816
10817 let position_map = Rc::new(PositionMap {
10818 size: bounds.size,
10819 visible_row_range,
10820 scroll_position,
10821 scroll_pixel_position,
10822 scroll_max,
10823 line_layouts,
10824 line_height,
10825 em_width,
10826 em_advance,
10827 em_layout_width,
10828 snapshot,
10829 text_align: self.style.text.text_align,
10830 content_width: text_hitbox.size.width,
10831 gutter_hitbox: gutter_hitbox.clone(),
10832 text_hitbox: text_hitbox.clone(),
10833 inline_blame_bounds: inline_blame_layout
10834 .as_ref()
10835 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
10836 display_hunks: display_hunks.clone(),
10837 diff_hunk_control_bounds,
10838 });
10839
10840 self.editor.update(cx, |editor, _| {
10841 editor.last_position_map = Some(position_map.clone())
10842 });
10843
10844 EditorLayout {
10845 mode,
10846 position_map,
10847 visible_display_row_range: start_row..end_row,
10848 wrap_guides,
10849 indent_guides,
10850 hitbox,
10851 gutter_hitbox,
10852 display_hunks,
10853 content_origin,
10854 scrollbars_layout,
10855 minimap,
10856 active_rows,
10857 highlighted_rows,
10858 highlighted_ranges,
10859 highlighted_gutter_ranges,
10860 redacted_ranges,
10861 document_colors,
10862 line_elements,
10863 line_numbers,
10864 blamed_display_rows,
10865 inline_diagnostics,
10866 inline_blame_layout,
10867 inline_code_actions,
10868 blocks,
10869 cursors,
10870 visible_cursors,
10871 selections,
10872 edit_prediction_popover,
10873 diff_hunk_controls,
10874 mouse_context_menu,
10875 test_indicators,
10876 breakpoints,
10877 diff_review_button,
10878 crease_toggles,
10879 crease_trailers,
10880 tab_invisible,
10881 space_invisible,
10882 sticky_buffer_header,
10883 sticky_headers,
10884 expand_toggles,
10885 text_align: self.style.text.text_align,
10886 content_width: text_hitbox.size.width,
10887 }
10888 })
10889 })
10890 })
10891 }
10892
10893 fn paint(
10894 &mut self,
10895 _: Option<&GlobalElementId>,
10896 _inspector_id: Option<&gpui::InspectorElementId>,
10897 bounds: Bounds<gpui::Pixels>,
10898 _: &mut Self::RequestLayoutState,
10899 layout: &mut Self::PrepaintState,
10900 window: &mut Window,
10901 cx: &mut App,
10902 ) {
10903 if !layout.mode.is_minimap() {
10904 let focus_handle = self.editor.focus_handle(cx);
10905 let key_context = self
10906 .editor
10907 .update(cx, |editor, cx| editor.key_context(window, cx));
10908
10909 window.set_key_context(key_context);
10910 window.handle_input(
10911 &focus_handle,
10912 ElementInputHandler::new(bounds, self.editor.clone()),
10913 cx,
10914 );
10915 self.register_actions(window, cx);
10916 self.register_key_listeners(window, cx, layout);
10917 }
10918
10919 let text_style = TextStyleRefinement {
10920 font_size: Some(self.style.text.font_size),
10921 line_height: Some(self.style.text.line_height),
10922 ..Default::default()
10923 };
10924 let rem_size = self.rem_size(cx);
10925 window.with_rem_size(rem_size, |window| {
10926 window.with_text_style(Some(text_style), |window| {
10927 window.with_content_mask(Some(ContentMask { bounds }), |window| {
10928 self.paint_mouse_listeners(layout, window, cx);
10929 self.paint_background(layout, window, cx);
10930 self.paint_indent_guides(layout, window, cx);
10931
10932 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10933 self.paint_blamed_display_rows(layout, window, cx);
10934 self.paint_line_numbers(layout, window, cx);
10935 }
10936
10937 self.paint_text(layout, window, cx);
10938
10939 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10940 self.paint_gutter_highlights(layout, window, cx);
10941 self.paint_gutter_indicators(layout, window, cx);
10942 }
10943
10944 if !layout.blocks.is_empty() {
10945 window.with_element_namespace("blocks", |window| {
10946 self.paint_blocks(layout, window, cx);
10947 });
10948 }
10949
10950 window.with_element_namespace("blocks", |window| {
10951 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
10952 sticky_header.paint(window, cx)
10953 }
10954 });
10955
10956 self.paint_sticky_headers(layout, window, cx);
10957 self.paint_minimap(layout, window, cx);
10958 self.paint_scrollbars(layout, window, cx);
10959 self.paint_edit_prediction_popover(layout, window, cx);
10960 self.paint_mouse_context_menu(layout, window, cx);
10961 });
10962 })
10963 })
10964 }
10965}
10966
10967pub(super) fn gutter_bounds(
10968 editor_bounds: Bounds<Pixels>,
10969 gutter_dimensions: GutterDimensions,
10970) -> Bounds<Pixels> {
10971 Bounds {
10972 origin: editor_bounds.origin,
10973 size: size(gutter_dimensions.width, editor_bounds.size.height),
10974 }
10975}
10976
10977#[derive(Clone, Copy)]
10978struct ContextMenuLayout {
10979 y_flipped: bool,
10980 bounds: Bounds<Pixels>,
10981}
10982
10983/// Holds information required for layouting the editor scrollbars.
10984struct ScrollbarLayoutInformation {
10985 /// The bounds of the editor area (excluding the content offset).
10986 editor_bounds: Bounds<Pixels>,
10987 /// The available range to scroll within the document.
10988 scroll_range: Size<Pixels>,
10989 /// The space available for one glyph in the editor.
10990 glyph_grid_cell: Size<Pixels>,
10991}
10992
10993impl ScrollbarLayoutInformation {
10994 pub fn new(
10995 editor_bounds: Bounds<Pixels>,
10996 glyph_grid_cell: Size<Pixels>,
10997 document_size: Size<Pixels>,
10998 longest_line_blame_width: Pixels,
10999 settings: &EditorSettings,
11000 ) -> Self {
11001 let vertical_overscroll = match settings.scroll_beyond_last_line {
11002 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
11003 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
11004 ScrollBeyondLastLine::VerticalScrollMargin => {
11005 (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
11006 }
11007 };
11008
11009 let overscroll = size(longest_line_blame_width, vertical_overscroll);
11010
11011 ScrollbarLayoutInformation {
11012 editor_bounds,
11013 scroll_range: document_size + overscroll,
11014 glyph_grid_cell,
11015 }
11016 }
11017}
11018
11019impl IntoElement for EditorElement {
11020 type Element = Self;
11021
11022 fn into_element(self) -> Self::Element {
11023 self
11024 }
11025}
11026
11027pub struct EditorLayout {
11028 position_map: Rc<PositionMap>,
11029 hitbox: Hitbox,
11030 gutter_hitbox: Hitbox,
11031 content_origin: gpui::Point<Pixels>,
11032 scrollbars_layout: Option<EditorScrollbars>,
11033 minimap: Option<MinimapLayout>,
11034 mode: EditorMode,
11035 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
11036 indent_guides: Option<Vec<IndentGuideLayout>>,
11037 visible_display_row_range: Range<DisplayRow>,
11038 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
11039 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
11040 line_elements: SmallVec<[AnyElement; 1]>,
11041 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
11042 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11043 blamed_display_rows: Option<Vec<AnyElement>>,
11044 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
11045 inline_blame_layout: Option<InlineBlameLayout>,
11046 inline_code_actions: Option<AnyElement>,
11047 blocks: Vec<BlockLayout>,
11048 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11049 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11050 redacted_ranges: Vec<Range<DisplayPoint>>,
11051 cursors: Vec<(DisplayPoint, Hsla)>,
11052 visible_cursors: Vec<CursorLayout>,
11053 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
11054 test_indicators: Vec<AnyElement>,
11055 breakpoints: Vec<AnyElement>,
11056 diff_review_button: Option<AnyElement>,
11057 crease_toggles: Vec<Option<AnyElement>>,
11058 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
11059 diff_hunk_controls: Vec<AnyElement>,
11060 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
11061 edit_prediction_popover: Option<AnyElement>,
11062 mouse_context_menu: Option<AnyElement>,
11063 tab_invisible: ShapedLine,
11064 space_invisible: ShapedLine,
11065 sticky_buffer_header: Option<AnyElement>,
11066 sticky_headers: Option<StickyHeaders>,
11067 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
11068 text_align: TextAlign,
11069 content_width: Pixels,
11070}
11071
11072struct StickyHeaders {
11073 lines: Vec<StickyHeaderLine>,
11074 gutter_background: Hsla,
11075 content_background: Hsla,
11076 gutter_right_padding: Pixels,
11077}
11078
11079struct StickyHeaderLine {
11080 row: DisplayRow,
11081 offset: Pixels,
11082 line: LineWithInvisibles,
11083 line_number: Option<ShapedLine>,
11084 elements: SmallVec<[AnyElement; 1]>,
11085 available_text_width: Pixels,
11086 target_anchor: Anchor,
11087 hitbox: Hitbox,
11088}
11089
11090impl EditorLayout {
11091 fn line_end_overshoot(&self) -> Pixels {
11092 0.15 * self.position_map.line_height
11093 }
11094}
11095
11096impl StickyHeaders {
11097 fn paint(
11098 &mut self,
11099 layout: &mut EditorLayout,
11100 whitespace_setting: ShowWhitespaceSetting,
11101 window: &mut Window,
11102 cx: &mut App,
11103 ) {
11104 let line_height = layout.position_map.line_height;
11105
11106 for line in self.lines.iter_mut().rev() {
11107 window.paint_layer(
11108 Bounds::new(
11109 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11110 size(line.hitbox.size.width, line_height),
11111 ),
11112 |window| {
11113 let gutter_bounds = Bounds::new(
11114 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11115 size(layout.gutter_hitbox.size.width, line_height),
11116 );
11117 window.paint_quad(fill(gutter_bounds, self.gutter_background));
11118
11119 let text_bounds = Bounds::new(
11120 layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11121 size(line.available_text_width, line_height),
11122 );
11123 window.paint_quad(fill(text_bounds, self.content_background));
11124
11125 if line.hitbox.is_hovered(window) {
11126 let hover_overlay = cx.theme().colors().panel_overlay_hover;
11127 window.paint_quad(fill(gutter_bounds, hover_overlay));
11128 window.paint_quad(fill(text_bounds, hover_overlay));
11129 }
11130
11131 line.paint(
11132 layout,
11133 self.gutter_right_padding,
11134 line.available_text_width,
11135 layout.content_origin,
11136 line_height,
11137 whitespace_setting,
11138 window,
11139 cx,
11140 );
11141 },
11142 );
11143
11144 window.set_cursor_style(CursorStyle::PointingHand, &line.hitbox);
11145 }
11146 }
11147}
11148
11149impl StickyHeaderLine {
11150 fn new(
11151 row: DisplayRow,
11152 offset: Pixels,
11153 mut line: LineWithInvisibles,
11154 line_number: Option<ShapedLine>,
11155 target_anchor: Anchor,
11156 line_height: Pixels,
11157 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11158 content_origin: gpui::Point<Pixels>,
11159 gutter_hitbox: &Hitbox,
11160 text_hitbox: &Hitbox,
11161 window: &mut Window,
11162 cx: &mut App,
11163 ) -> Self {
11164 let mut elements = SmallVec::<[AnyElement; 1]>::new();
11165 line.prepaint_with_custom_offset(
11166 line_height,
11167 scroll_pixel_position,
11168 content_origin,
11169 offset,
11170 &mut elements,
11171 window,
11172 cx,
11173 );
11174
11175 let hitbox_bounds = Bounds::new(
11176 gutter_hitbox.origin + point(Pixels::ZERO, offset),
11177 size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11178 );
11179 let available_text_width =
11180 (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11181
11182 Self {
11183 row,
11184 offset,
11185 line,
11186 line_number,
11187 elements,
11188 available_text_width,
11189 target_anchor,
11190 hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11191 }
11192 }
11193
11194 fn paint(
11195 &mut self,
11196 layout: &EditorLayout,
11197 gutter_right_padding: Pixels,
11198 available_text_width: Pixels,
11199 content_origin: gpui::Point<Pixels>,
11200 line_height: Pixels,
11201 whitespace_setting: ShowWhitespaceSetting,
11202 window: &mut Window,
11203 cx: &mut App,
11204 ) {
11205 window.with_content_mask(
11206 Some(ContentMask {
11207 bounds: Bounds::new(
11208 layout.position_map.text_hitbox.bounds.origin
11209 + point(Pixels::ZERO, self.offset),
11210 size(available_text_width, line_height),
11211 ),
11212 }),
11213 |window| {
11214 self.line.draw_with_custom_offset(
11215 layout,
11216 self.row,
11217 content_origin,
11218 self.offset,
11219 whitespace_setting,
11220 &[],
11221 window,
11222 cx,
11223 );
11224 for element in &mut self.elements {
11225 element.paint(window, cx);
11226 }
11227 },
11228 );
11229
11230 if let Some(line_number) = &self.line_number {
11231 let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11232 let gutter_width = layout.gutter_hitbox.size.width;
11233 let origin = point(
11234 gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11235 gutter_origin.y,
11236 );
11237 line_number
11238 .paint(origin, line_height, TextAlign::Left, None, window, cx)
11239 .log_err();
11240 }
11241 }
11242}
11243
11244#[derive(Debug)]
11245struct LineNumberSegment {
11246 shaped_line: ShapedLine,
11247 hitbox: Option<Hitbox>,
11248}
11249
11250#[derive(Debug)]
11251struct LineNumberLayout {
11252 segments: SmallVec<[LineNumberSegment; 1]>,
11253}
11254
11255struct ColoredRange<T> {
11256 start: T,
11257 end: T,
11258 color: Hsla,
11259}
11260
11261impl Along for ScrollbarAxes {
11262 type Unit = bool;
11263
11264 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11265 match axis {
11266 ScrollbarAxis::Horizontal => self.horizontal,
11267 ScrollbarAxis::Vertical => self.vertical,
11268 }
11269 }
11270
11271 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11272 match axis {
11273 ScrollbarAxis::Horizontal => ScrollbarAxes {
11274 horizontal: f(self.horizontal),
11275 vertical: self.vertical,
11276 },
11277 ScrollbarAxis::Vertical => ScrollbarAxes {
11278 horizontal: self.horizontal,
11279 vertical: f(self.vertical),
11280 },
11281 }
11282 }
11283}
11284
11285#[derive(Clone)]
11286struct EditorScrollbars {
11287 pub vertical: Option<ScrollbarLayout>,
11288 pub horizontal: Option<ScrollbarLayout>,
11289 pub visible: bool,
11290}
11291
11292impl EditorScrollbars {
11293 pub fn from_scrollbar_axes(
11294 show_scrollbar: ScrollbarAxes,
11295 layout_information: &ScrollbarLayoutInformation,
11296 content_offset: gpui::Point<Pixels>,
11297 scroll_position: gpui::Point<f64>,
11298 scrollbar_width: Pixels,
11299 right_margin: Pixels,
11300 editor_width: Pixels,
11301 show_scrollbars: bool,
11302 scrollbar_state: Option<&ActiveScrollbarState>,
11303 window: &mut Window,
11304 ) -> Self {
11305 let ScrollbarLayoutInformation {
11306 editor_bounds,
11307 scroll_range,
11308 glyph_grid_cell,
11309 } = layout_information;
11310
11311 let viewport_size = size(editor_width, editor_bounds.size.height);
11312
11313 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11314 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
11315 Corner::BottomLeft,
11316 editor_bounds.bottom_left(),
11317 size(
11318 // The horizontal viewport size differs from the space available for the
11319 // horizontal scrollbar, so we have to manually stitch it together here.
11320 editor_bounds.size.width - right_margin,
11321 scrollbar_width,
11322 ),
11323 ),
11324 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
11325 Corner::TopRight,
11326 editor_bounds.top_right(),
11327 size(scrollbar_width, viewport_size.height),
11328 ),
11329 };
11330
11331 let mut create_scrollbar_layout = |axis| {
11332 let viewport_size = viewport_size.along(axis);
11333 let scroll_range = scroll_range.along(axis);
11334
11335 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11336 (show_scrollbar.along(axis)
11337 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11338 .then(|| {
11339 ScrollbarLayout::new(
11340 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11341 viewport_size,
11342 scroll_range,
11343 glyph_grid_cell.along(axis),
11344 content_offset.along(axis),
11345 scroll_position.along(axis),
11346 show_scrollbars,
11347 axis,
11348 )
11349 .with_thumb_state(
11350 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11351 )
11352 })
11353 };
11354
11355 Self {
11356 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11357 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11358 visible: show_scrollbars,
11359 }
11360 }
11361
11362 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11363 [
11364 (&self.vertical, ScrollbarAxis::Vertical),
11365 (&self.horizontal, ScrollbarAxis::Horizontal),
11366 ]
11367 .into_iter()
11368 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11369 }
11370
11371 /// Returns the currently hovered scrollbar axis, if any.
11372 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11373 self.iter_scrollbars()
11374 .find(|s| s.0.hitbox.is_hovered(window))
11375 }
11376}
11377
11378#[derive(Clone)]
11379struct ScrollbarLayout {
11380 hitbox: Hitbox,
11381 visible_range: Range<ScrollOffset>,
11382 text_unit_size: Pixels,
11383 thumb_bounds: Option<Bounds<Pixels>>,
11384 thumb_state: ScrollbarThumbState,
11385}
11386
11387impl ScrollbarLayout {
11388 const BORDER_WIDTH: Pixels = px(1.0);
11389 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11390 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11391 const MIN_THUMB_SIZE: Pixels = px(25.0);
11392
11393 fn new(
11394 scrollbar_track_hitbox: Hitbox,
11395 viewport_size: Pixels,
11396 scroll_range: Pixels,
11397 glyph_space: Pixels,
11398 content_offset: Pixels,
11399 scroll_position: ScrollOffset,
11400 show_thumb: bool,
11401 axis: ScrollbarAxis,
11402 ) -> Self {
11403 let track_bounds = scrollbar_track_hitbox.bounds;
11404 // The length of the track available to the scrollbar thumb. We deliberately
11405 // exclude the content size here so that the thumb aligns with the content.
11406 let track_length = track_bounds.size.along(axis) - content_offset;
11407
11408 Self::new_with_hitbox_and_track_length(
11409 scrollbar_track_hitbox,
11410 track_length,
11411 viewport_size,
11412 scroll_range.into(),
11413 glyph_space,
11414 content_offset.into(),
11415 scroll_position,
11416 show_thumb,
11417 axis,
11418 )
11419 }
11420
11421 fn for_minimap(
11422 minimap_track_hitbox: Hitbox,
11423 visible_lines: f64,
11424 total_editor_lines: f64,
11425 minimap_line_height: Pixels,
11426 scroll_position: ScrollOffset,
11427 minimap_scroll_top: ScrollOffset,
11428 show_thumb: bool,
11429 ) -> Self {
11430 // The scrollbar thumb size is calculated as
11431 // (visible_content/total_content) Γ scrollbar_track_length.
11432 //
11433 // For the minimap's thumb layout, we leverage this by setting the
11434 // scrollbar track length to the entire document size (using minimap line
11435 // height). This creates a thumb that exactly represents the editor
11436 // viewport scaled to minimap proportions.
11437 //
11438 // We adjust the thumb position relative to `minimap_scroll_top` to
11439 // accommodate for the deliberately oversized track.
11440 //
11441 // This approach ensures that the minimap thumb accurately reflects the
11442 // editor's current scroll position whilst nicely synchronizing the minimap
11443 // thumb and scrollbar thumb.
11444 let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11445 let viewport_size = visible_lines * f64::from(minimap_line_height);
11446
11447 let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11448
11449 Self::new_with_hitbox_and_track_length(
11450 minimap_track_hitbox,
11451 Pixels::from(scroll_range),
11452 Pixels::from(viewport_size),
11453 scroll_range,
11454 minimap_line_height,
11455 track_top_offset,
11456 scroll_position,
11457 show_thumb,
11458 ScrollbarAxis::Vertical,
11459 )
11460 }
11461
11462 fn new_with_hitbox_and_track_length(
11463 scrollbar_track_hitbox: Hitbox,
11464 track_length: Pixels,
11465 viewport_size: Pixels,
11466 scroll_range: f64,
11467 glyph_space: Pixels,
11468 content_offset: ScrollOffset,
11469 scroll_position: ScrollOffset,
11470 show_thumb: bool,
11471 axis: ScrollbarAxis,
11472 ) -> Self {
11473 let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11474 let visible_range = scroll_position..scroll_position + text_units_per_page;
11475 let total_text_units = scroll_range / glyph_space.to_f64();
11476
11477 let thumb_percentage = text_units_per_page / total_text_units;
11478 let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11479 .max(ScrollbarLayout::MIN_THUMB_SIZE)
11480 .min(track_length);
11481
11482 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11483
11484 let content_larger_than_viewport = text_unit_divisor > 0.;
11485
11486 let text_unit_size = if content_larger_than_viewport {
11487 Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11488 } else {
11489 glyph_space
11490 };
11491
11492 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11493 Self::thumb_bounds(
11494 &scrollbar_track_hitbox,
11495 content_offset,
11496 visible_range.start,
11497 text_unit_size,
11498 thumb_size,
11499 axis,
11500 )
11501 });
11502
11503 ScrollbarLayout {
11504 hitbox: scrollbar_track_hitbox,
11505 visible_range,
11506 text_unit_size,
11507 thumb_bounds,
11508 thumb_state: Default::default(),
11509 }
11510 }
11511
11512 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11513 if let Some(thumb_state) = thumb_state {
11514 Self {
11515 thumb_state,
11516 ..self
11517 }
11518 } else {
11519 self
11520 }
11521 }
11522
11523 fn thumb_bounds(
11524 scrollbar_track: &Hitbox,
11525 content_offset: f64,
11526 visible_range_start: f64,
11527 text_unit_size: Pixels,
11528 thumb_size: Pixels,
11529 axis: ScrollbarAxis,
11530 ) -> Bounds<Pixels> {
11531 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11532 origin
11533 + Pixels::from(
11534 content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11535 )
11536 });
11537 Bounds::new(
11538 thumb_origin,
11539 scrollbar_track.size.apply_along(axis, |_| thumb_size),
11540 )
11541 }
11542
11543 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11544 self.thumb_bounds
11545 .is_some_and(|bounds| bounds.contains(position))
11546 }
11547
11548 fn marker_quads_for_ranges(
11549 &self,
11550 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11551 column: Option<usize>,
11552 ) -> Vec<PaintQuad> {
11553 struct MinMax {
11554 min: Pixels,
11555 max: Pixels,
11556 }
11557 let (x_range, height_limit) = if let Some(column) = column {
11558 let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11559 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11560 let end = start + column_width;
11561 (
11562 Range { start, end },
11563 MinMax {
11564 min: Self::MIN_MARKER_HEIGHT,
11565 max: px(f32::MAX),
11566 },
11567 )
11568 } else {
11569 (
11570 Range {
11571 start: Self::BORDER_WIDTH,
11572 end: self.hitbox.size.width,
11573 },
11574 MinMax {
11575 min: Self::LINE_MARKER_HEIGHT,
11576 max: Self::LINE_MARKER_HEIGHT,
11577 },
11578 )
11579 };
11580
11581 let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11582 let mut pixel_ranges = row_ranges
11583 .into_iter()
11584 .map(|range| {
11585 let start_y = row_to_y(range.start);
11586 let end_y = row_to_y(range.end)
11587 + self
11588 .text_unit_size
11589 .max(height_limit.min)
11590 .min(height_limit.max);
11591 ColoredRange {
11592 start: start_y,
11593 end: end_y,
11594 color: range.color,
11595 }
11596 })
11597 .peekable();
11598
11599 let mut quads = Vec::new();
11600 while let Some(mut pixel_range) = pixel_ranges.next() {
11601 while let Some(next_pixel_range) = pixel_ranges.peek() {
11602 if pixel_range.end >= next_pixel_range.start - px(1.0)
11603 && pixel_range.color == next_pixel_range.color
11604 {
11605 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11606 pixel_ranges.next();
11607 } else {
11608 break;
11609 }
11610 }
11611
11612 let bounds = Bounds::from_corners(
11613 point(x_range.start, pixel_range.start),
11614 point(x_range.end, pixel_range.end),
11615 );
11616 quads.push(quad(
11617 bounds,
11618 Corners::default(),
11619 pixel_range.color,
11620 Edges::default(),
11621 Hsla::transparent_black(),
11622 BorderStyle::default(),
11623 ));
11624 }
11625
11626 quads
11627 }
11628}
11629
11630struct MinimapLayout {
11631 pub minimap: AnyElement,
11632 pub thumb_layout: ScrollbarLayout,
11633 pub minimap_scroll_top: ScrollOffset,
11634 pub minimap_line_height: Pixels,
11635 pub thumb_border_style: MinimapThumbBorder,
11636 pub max_scroll_top: ScrollOffset,
11637}
11638
11639impl MinimapLayout {
11640 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11641 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11642 /// The minimap width as a percentage of the editor width.
11643 const MINIMAP_WIDTH_PCT: f32 = 0.15;
11644 /// Calculates the scroll top offset the minimap editor has to have based on the
11645 /// current scroll progress.
11646 fn calculate_minimap_top_offset(
11647 document_lines: f64,
11648 visible_editor_lines: f64,
11649 visible_minimap_lines: f64,
11650 scroll_position: f64,
11651 ) -> ScrollOffset {
11652 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11653 if non_visible_document_lines == 0. {
11654 0.
11655 } else {
11656 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11657 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11658 }
11659 }
11660}
11661
11662struct CreaseTrailerLayout {
11663 element: AnyElement,
11664 bounds: Bounds<Pixels>,
11665}
11666
11667pub(crate) struct PositionMap {
11668 pub size: Size<Pixels>,
11669 pub line_height: Pixels,
11670 pub scroll_position: gpui::Point<ScrollOffset>,
11671 pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11672 pub scroll_max: gpui::Point<ScrollOffset>,
11673 pub em_width: Pixels,
11674 pub em_advance: Pixels,
11675 pub em_layout_width: Pixels,
11676 pub visible_row_range: Range<DisplayRow>,
11677 pub line_layouts: Vec<LineWithInvisibles>,
11678 pub snapshot: EditorSnapshot,
11679 pub text_align: TextAlign,
11680 pub content_width: Pixels,
11681 pub text_hitbox: Hitbox,
11682 pub gutter_hitbox: Hitbox,
11683 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11684 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11685 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11686}
11687
11688#[derive(Debug, Copy, Clone)]
11689pub struct PointForPosition {
11690 pub previous_valid: DisplayPoint,
11691 pub next_valid: DisplayPoint,
11692 pub exact_unclipped: DisplayPoint,
11693 pub column_overshoot_after_line_end: u32,
11694}
11695
11696impl PointForPosition {
11697 pub fn as_valid(&self) -> Option<DisplayPoint> {
11698 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11699 Some(self.previous_valid)
11700 } else {
11701 None
11702 }
11703 }
11704
11705 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11706 let Some(valid_point) = self.as_valid() else {
11707 return false;
11708 };
11709 let range = selection.range();
11710
11711 let candidate_row = valid_point.row();
11712 let candidate_col = valid_point.column();
11713
11714 let start_row = range.start.row();
11715 let start_col = range.start.column();
11716 let end_row = range.end.row();
11717 let end_col = range.end.column();
11718
11719 if candidate_row < start_row || candidate_row > end_row {
11720 false
11721 } else if start_row == end_row {
11722 candidate_col >= start_col && candidate_col < end_col
11723 } else if candidate_row == start_row {
11724 candidate_col >= start_col
11725 } else if candidate_row == end_row {
11726 candidate_col < end_col
11727 } else {
11728 true
11729 }
11730 }
11731}
11732
11733impl PositionMap {
11734 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11735 let text_bounds = self.text_hitbox.bounds;
11736 let scroll_position = self.snapshot.scroll_position();
11737 let position = position - text_bounds.origin;
11738 let y = position.y.max(px(0.)).min(self.size.height);
11739 let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11740 let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11741
11742 let (column, x_overshoot_after_line_end) = if let Some(line) = self
11743 .line_layouts
11744 .get(row as usize - scroll_position.y as usize)
11745 {
11746 let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11747 let x_relative_to_text = x - alignment_offset;
11748 if let Some(ix) = line.index_for_x(x_relative_to_text) {
11749 (ix as u32, px(0.))
11750 } else {
11751 (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11752 }
11753 } else {
11754 (0, x)
11755 };
11756
11757 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11758 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11759 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11760
11761 let column_overshoot_after_line_end =
11762 (x_overshoot_after_line_end / self.em_layout_width) as u32;
11763 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11764 PointForPosition {
11765 previous_valid,
11766 next_valid,
11767 exact_unclipped,
11768 column_overshoot_after_line_end,
11769 }
11770 }
11771}
11772
11773pub(crate) struct BlockLayout {
11774 pub(crate) id: BlockId,
11775 pub(crate) x_offset: Pixels,
11776 pub(crate) row: Option<DisplayRow>,
11777 pub(crate) element: AnyElement,
11778 pub(crate) available_space: Size<AvailableSpace>,
11779 pub(crate) style: BlockStyle,
11780 pub(crate) overlaps_gutter: bool,
11781 pub(crate) is_buffer_header: bool,
11782}
11783
11784pub fn layout_line(
11785 row: DisplayRow,
11786 snapshot: &EditorSnapshot,
11787 style: &EditorStyle,
11788 text_width: Pixels,
11789 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
11790 window: &mut Window,
11791 cx: &mut App,
11792) -> LineWithInvisibles {
11793 let use_tree_sitter =
11794 !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
11795 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), use_tree_sitter, style);
11796 LineWithInvisibles::from_chunks(
11797 chunks,
11798 style,
11799 MAX_LINE_LEN,
11800 1,
11801 &snapshot.mode,
11802 text_width,
11803 is_row_soft_wrapped,
11804 &[],
11805 window,
11806 cx,
11807 )
11808 .pop()
11809 .unwrap()
11810}
11811
11812#[derive(Debug)]
11813pub struct IndentGuideLayout {
11814 origin: gpui::Point<Pixels>,
11815 length: Pixels,
11816 single_indent_width: Pixels,
11817 depth: u32,
11818 active: bool,
11819 settings: IndentGuideSettings,
11820}
11821
11822pub struct CursorLayout {
11823 origin: gpui::Point<Pixels>,
11824 block_width: Pixels,
11825 line_height: Pixels,
11826 color: Hsla,
11827 shape: CursorShape,
11828 block_text: Option<ShapedLine>,
11829 cursor_name: Option<AnyElement>,
11830}
11831
11832#[derive(Debug)]
11833pub struct CursorName {
11834 string: SharedString,
11835 color: Hsla,
11836 is_top_row: bool,
11837}
11838
11839impl CursorLayout {
11840 pub fn new(
11841 origin: gpui::Point<Pixels>,
11842 block_width: Pixels,
11843 line_height: Pixels,
11844 color: Hsla,
11845 shape: CursorShape,
11846 block_text: Option<ShapedLine>,
11847 ) -> CursorLayout {
11848 CursorLayout {
11849 origin,
11850 block_width,
11851 line_height,
11852 color,
11853 shape,
11854 block_text,
11855 cursor_name: None,
11856 }
11857 }
11858
11859 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11860 Bounds {
11861 origin: self.origin + origin,
11862 size: size(self.block_width, self.line_height),
11863 }
11864 }
11865
11866 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11867 match self.shape {
11868 CursorShape::Bar => Bounds {
11869 origin: self.origin + origin,
11870 size: size(px(2.0), self.line_height),
11871 },
11872 CursorShape::Block | CursorShape::Hollow => Bounds {
11873 origin: self.origin + origin,
11874 size: size(self.block_width, self.line_height),
11875 },
11876 CursorShape::Underline => Bounds {
11877 origin: self.origin
11878 + origin
11879 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11880 size: size(self.block_width, px(2.0)),
11881 },
11882 }
11883 }
11884
11885 pub fn layout(
11886 &mut self,
11887 origin: gpui::Point<Pixels>,
11888 cursor_name: Option<CursorName>,
11889 window: &mut Window,
11890 cx: &mut App,
11891 ) {
11892 if let Some(cursor_name) = cursor_name {
11893 let bounds = self.bounds(origin);
11894 let text_size = self.line_height / 1.5;
11895
11896 let name_origin = if cursor_name.is_top_row {
11897 point(bounds.right() - px(1.), bounds.top())
11898 } else {
11899 match self.shape {
11900 CursorShape::Bar => point(
11901 bounds.right() - px(2.),
11902 bounds.top() - text_size / 2. - px(1.),
11903 ),
11904 _ => point(
11905 bounds.right() - px(1.),
11906 bounds.top() - text_size / 2. - px(1.),
11907 ),
11908 }
11909 };
11910 let mut name_element = div()
11911 .bg(self.color)
11912 .text_size(text_size)
11913 .px_0p5()
11914 .line_height(text_size + px(2.))
11915 .text_color(cursor_name.color)
11916 .child(cursor_name.string)
11917 .into_any_element();
11918
11919 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11920
11921 self.cursor_name = Some(name_element);
11922 }
11923 }
11924
11925 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11926 let bounds = self.bounds(origin);
11927
11928 //Draw background or border quad
11929 let cursor = if matches!(self.shape, CursorShape::Hollow) {
11930 outline(bounds, self.color, BorderStyle::Solid)
11931 } else {
11932 fill(bounds, self.color)
11933 };
11934
11935 if let Some(name) = &mut self.cursor_name {
11936 name.paint(window, cx);
11937 }
11938
11939 window.paint_quad(cursor);
11940
11941 if let Some(block_text) = &self.block_text {
11942 block_text
11943 .paint(
11944 self.origin + origin,
11945 self.line_height,
11946 TextAlign::Left,
11947 None,
11948 window,
11949 cx,
11950 )
11951 .log_err();
11952 }
11953 }
11954
11955 pub fn shape(&self) -> CursorShape {
11956 self.shape
11957 }
11958}
11959
11960#[derive(Debug)]
11961pub struct HighlightedRange {
11962 pub start_y: Pixels,
11963 pub line_height: Pixels,
11964 pub lines: Vec<HighlightedRangeLine>,
11965 pub color: Hsla,
11966 pub corner_radius: Pixels,
11967}
11968
11969#[derive(Debug)]
11970pub struct HighlightedRangeLine {
11971 pub start_x: Pixels,
11972 pub end_x: Pixels,
11973}
11974
11975impl HighlightedRange {
11976 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
11977 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
11978 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
11979 self.paint_lines(
11980 self.start_y + self.line_height,
11981 &self.lines[1..],
11982 fill,
11983 bounds,
11984 window,
11985 );
11986 } else {
11987 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
11988 }
11989 }
11990
11991 fn paint_lines(
11992 &self,
11993 start_y: Pixels,
11994 lines: &[HighlightedRangeLine],
11995 fill: bool,
11996 _bounds: Bounds<Pixels>,
11997 window: &mut Window,
11998 ) {
11999 if lines.is_empty() {
12000 return;
12001 }
12002
12003 let first_line = lines.first().unwrap();
12004 let last_line = lines.last().unwrap();
12005
12006 let first_top_left = point(first_line.start_x, start_y);
12007 let first_top_right = point(first_line.end_x, start_y);
12008
12009 let curve_height = point(Pixels::ZERO, self.corner_radius);
12010 let curve_width = |start_x: Pixels, end_x: Pixels| {
12011 let max = (end_x - start_x) / 2.;
12012 let width = if max < self.corner_radius {
12013 max
12014 } else {
12015 self.corner_radius
12016 };
12017
12018 point(width, Pixels::ZERO)
12019 };
12020
12021 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12022 let mut builder = if fill {
12023 gpui::PathBuilder::fill()
12024 } else {
12025 gpui::PathBuilder::stroke(px(1.))
12026 };
12027 builder.move_to(first_top_right - top_curve_width);
12028 builder.curve_to(first_top_right + curve_height, first_top_right);
12029
12030 let mut iter = lines.iter().enumerate().peekable();
12031 while let Some((ix, line)) = iter.next() {
12032 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12033
12034 if let Some((_, next_line)) = iter.peek() {
12035 let next_top_right = point(next_line.end_x, bottom_right.y);
12036
12037 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12038 Ordering::Equal => {
12039 builder.line_to(bottom_right);
12040 }
12041 Ordering::Less => {
12042 let curve_width = curve_width(next_top_right.x, bottom_right.x);
12043 builder.line_to(bottom_right - curve_height);
12044 if self.corner_radius > Pixels::ZERO {
12045 builder.curve_to(bottom_right - curve_width, bottom_right);
12046 }
12047 builder.line_to(next_top_right + curve_width);
12048 if self.corner_radius > Pixels::ZERO {
12049 builder.curve_to(next_top_right + curve_height, next_top_right);
12050 }
12051 }
12052 Ordering::Greater => {
12053 let curve_width = curve_width(bottom_right.x, next_top_right.x);
12054 builder.line_to(bottom_right - curve_height);
12055 if self.corner_radius > Pixels::ZERO {
12056 builder.curve_to(bottom_right + curve_width, bottom_right);
12057 }
12058 builder.line_to(next_top_right - curve_width);
12059 if self.corner_radius > Pixels::ZERO {
12060 builder.curve_to(next_top_right + curve_height, next_top_right);
12061 }
12062 }
12063 }
12064 } else {
12065 let curve_width = curve_width(line.start_x, line.end_x);
12066 builder.line_to(bottom_right - curve_height);
12067 if self.corner_radius > Pixels::ZERO {
12068 builder.curve_to(bottom_right - curve_width, bottom_right);
12069 }
12070
12071 let bottom_left = point(line.start_x, bottom_right.y);
12072 builder.line_to(bottom_left + curve_width);
12073 if self.corner_radius > Pixels::ZERO {
12074 builder.curve_to(bottom_left - curve_height, bottom_left);
12075 }
12076 }
12077 }
12078
12079 if first_line.start_x > last_line.start_x {
12080 let curve_width = curve_width(last_line.start_x, first_line.start_x);
12081 let second_top_left = point(last_line.start_x, start_y + self.line_height);
12082 builder.line_to(second_top_left + curve_height);
12083 if self.corner_radius > Pixels::ZERO {
12084 builder.curve_to(second_top_left + curve_width, second_top_left);
12085 }
12086 let first_bottom_left = point(first_line.start_x, second_top_left.y);
12087 builder.line_to(first_bottom_left - curve_width);
12088 if self.corner_radius > Pixels::ZERO {
12089 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12090 }
12091 }
12092
12093 builder.line_to(first_top_left + curve_height);
12094 if self.corner_radius > Pixels::ZERO {
12095 builder.curve_to(first_top_left + top_curve_width, first_top_left);
12096 }
12097 builder.line_to(first_top_right - top_curve_width);
12098
12099 if let Ok(path) = builder.build() {
12100 window.paint_path(path, self.color);
12101 }
12102 }
12103}
12104
12105pub(crate) struct StickyHeader {
12106 pub item: language::OutlineItem<Anchor>,
12107 pub sticky_row: DisplayRow,
12108 pub start_point: Point,
12109 pub offset: ScrollOffset,
12110}
12111
12112enum CursorPopoverType {
12113 CodeContextMenu,
12114 EditPrediction,
12115}
12116
12117pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12118 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12119}
12120
12121fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12122 (delta.pow(1.2) / 300.0).into()
12123}
12124
12125pub fn register_action<T: Action>(
12126 editor: &Entity<Editor>,
12127 window: &mut Window,
12128 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12129) {
12130 let editor = editor.clone();
12131 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12132 let action = action.downcast_ref().unwrap();
12133 if phase == DispatchPhase::Bubble {
12134 editor.update(cx, |editor, cx| {
12135 listener(editor, action, window, cx);
12136 })
12137 }
12138 })
12139}
12140
12141/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12142/// both full and auto-height editors compute wrap widths consistently.
12143fn calculate_wrap_width(
12144 soft_wrap: SoftWrap,
12145 editor_width: Pixels,
12146 em_width: Pixels,
12147) -> Option<Pixels> {
12148 let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12149
12150 match soft_wrap {
12151 SoftWrap::GitDiff => None,
12152 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12153 SoftWrap::EditorWidth => Some(editor_width),
12154 SoftWrap::Column(column) => Some(wrap_width_for(column)),
12155 SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12156 }
12157}
12158
12159fn compute_auto_height_layout(
12160 editor: &mut Editor,
12161 min_lines: usize,
12162 max_lines: Option<usize>,
12163 known_dimensions: Size<Option<Pixels>>,
12164 available_width: AvailableSpace,
12165 window: &mut Window,
12166 cx: &mut Context<Editor>,
12167) -> Option<Size<Pixels>> {
12168 let width = known_dimensions.width.or({
12169 if let AvailableSpace::Definite(available_width) = available_width {
12170 Some(available_width)
12171 } else {
12172 None
12173 }
12174 })?;
12175 if let Some(height) = known_dimensions.height {
12176 return Some(size(width, height));
12177 }
12178
12179 let style = editor.style.as_ref().unwrap();
12180 let font_id = window.text_system().resolve_font(&style.text.font());
12181 let font_size = style.text.font_size.to_pixels(window.rem_size());
12182 let line_height = style.text.line_height_in_pixels(window.rem_size());
12183 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12184
12185 let mut snapshot = editor.snapshot(window, cx);
12186 let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12187
12188 editor.gutter_dimensions = gutter_dimensions;
12189 let text_width = width - gutter_dimensions.width;
12190 let overscroll = size(em_width, px(0.));
12191
12192 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12193 let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width);
12194 if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12195 snapshot = editor.snapshot(window, cx);
12196 }
12197
12198 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12199
12200 let min_height = line_height * min_lines as f32;
12201 let content_height = scroll_height.max(min_height);
12202
12203 let final_height = if let Some(max_lines) = max_lines {
12204 let max_height = line_height * max_lines as f32;
12205 content_height.min(max_height)
12206 } else {
12207 content_height
12208 };
12209
12210 Some(size(width, final_height))
12211}
12212
12213#[cfg(test)]
12214mod tests {
12215 use super::*;
12216 use crate::{
12217 Editor, MultiBuffer, SelectionEffects,
12218 display_map::{BlockPlacement, BlockProperties},
12219 editor_tests::{init_test, update_test_language_settings},
12220 };
12221 use gpui::{TestAppContext, VisualTestContext};
12222 use language::{Buffer, language_settings, tree_sitter_python};
12223 use log::info;
12224 use rand::{RngCore, rngs::StdRng};
12225 use std::num::NonZeroU32;
12226 use util::test::sample_text;
12227
12228 #[gpui::test]
12229 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12230 init_test(cx, |_| {});
12231 // Ensure wrap completes synchronously by giving block_with_timeout enough ticks
12232 cx.dispatcher.scheduler().set_timeout_ticks(1000..=1000);
12233
12234 let window = cx.add_window(|window, cx| {
12235 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12236 let mut editor = Editor::new(
12237 EditorMode::AutoHeight {
12238 min_lines: 1,
12239 max_lines: None,
12240 },
12241 buffer,
12242 None,
12243 window,
12244 cx,
12245 );
12246 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12247 editor
12248 });
12249 let cx = &mut VisualTestContext::from_window(*window, cx);
12250 let editor = window.root(cx).unwrap();
12251 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12252
12253 for x in 1..=100 {
12254 let (_, state) = cx.draw(
12255 Default::default(),
12256 size(px(200. + 0.13 * x as f32), px(500.)),
12257 |_, _| EditorElement::new(&editor, style.clone()),
12258 );
12259
12260 assert!(
12261 state.position_map.scroll_max.x == 0.,
12262 "Soft wrapped editor should have no horizontal scrolling!"
12263 );
12264 }
12265 }
12266
12267 #[gpui::test]
12268 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12269 init_test(cx, |_| {});
12270 // Ensure wrap completes synchronously by giving block_with_timeout enough ticks
12271 cx.dispatcher.scheduler().set_timeout_ticks(1000..=1000);
12272
12273 let window = cx.add_window(|window, cx| {
12274 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12275 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12276 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12277 editor
12278 });
12279 let cx = &mut VisualTestContext::from_window(*window, cx);
12280 let editor = window.root(cx).unwrap();
12281 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12282
12283 for x in 1..=100 {
12284 let (_, state) = cx.draw(
12285 Default::default(),
12286 size(px(200. + 0.13 * x as f32), px(500.)),
12287 |_, _| EditorElement::new(&editor, style.clone()),
12288 );
12289
12290 assert!(
12291 state.position_map.scroll_max.x == 0.,
12292 "Soft wrapped editor should have no horizontal scrolling!"
12293 );
12294 }
12295 }
12296
12297 #[gpui::test]
12298 fn test_layout_line_numbers(cx: &mut TestAppContext) {
12299 init_test(cx, |_| {});
12300 let window = cx.add_window(|window, cx| {
12301 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12302 Editor::new(EditorMode::full(), buffer, None, window, cx)
12303 });
12304
12305 let editor = window.root(cx).unwrap();
12306 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12307 let line_height = window
12308 .update(cx, |_, window, _| {
12309 style.text.line_height_in_pixels(window.rem_size())
12310 })
12311 .unwrap();
12312 let element = EditorElement::new(&editor, style);
12313 let snapshot = window
12314 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12315 .unwrap();
12316
12317 let layouts = cx
12318 .update_window(*window, |_, window, cx| {
12319 element.layout_line_numbers(
12320 None,
12321 GutterDimensions {
12322 left_padding: Pixels::ZERO,
12323 right_padding: Pixels::ZERO,
12324 width: px(30.0),
12325 margin: Pixels::ZERO,
12326 git_blame_entries_width: None,
12327 },
12328 line_height,
12329 gpui::Point::default(),
12330 DisplayRow(0)..DisplayRow(6),
12331 &(0..6)
12332 .map(|row| RowInfo {
12333 buffer_row: Some(row),
12334 ..Default::default()
12335 })
12336 .collect::<Vec<_>>(),
12337 &BTreeMap::default(),
12338 Some(DisplayRow(0)),
12339 &snapshot,
12340 window,
12341 cx,
12342 )
12343 })
12344 .unwrap();
12345 assert_eq!(layouts.len(), 6);
12346
12347 let relative_rows = window
12348 .update(cx, |editor, window, cx| {
12349 let snapshot = editor.snapshot(window, cx);
12350 snapshot.calculate_relative_line_numbers(
12351 &(DisplayRow(0)..DisplayRow(6)),
12352 DisplayRow(3),
12353 false,
12354 )
12355 })
12356 .unwrap();
12357 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12358 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12359 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12360 // current line has no relative number
12361 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12362 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12363 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12364
12365 // works if cursor is before screen
12366 let relative_rows = window
12367 .update(cx, |editor, window, cx| {
12368 let snapshot = editor.snapshot(window, cx);
12369 snapshot.calculate_relative_line_numbers(
12370 &(DisplayRow(3)..DisplayRow(6)),
12371 DisplayRow(1),
12372 false,
12373 )
12374 })
12375 .unwrap();
12376 assert_eq!(relative_rows.len(), 3);
12377 assert_eq!(relative_rows[&DisplayRow(3)], 2);
12378 assert_eq!(relative_rows[&DisplayRow(4)], 3);
12379 assert_eq!(relative_rows[&DisplayRow(5)], 4);
12380
12381 // works if cursor is after screen
12382 let relative_rows = window
12383 .update(cx, |editor, window, cx| {
12384 let snapshot = editor.snapshot(window, cx);
12385 snapshot.calculate_relative_line_numbers(
12386 &(DisplayRow(0)..DisplayRow(3)),
12387 DisplayRow(6),
12388 false,
12389 )
12390 })
12391 .unwrap();
12392 assert_eq!(relative_rows.len(), 3);
12393 assert_eq!(relative_rows[&DisplayRow(0)], 5);
12394 assert_eq!(relative_rows[&DisplayRow(1)], 4);
12395 assert_eq!(relative_rows[&DisplayRow(2)], 3);
12396
12397 const DELETED_LINE: u32 = 3;
12398 let layouts = cx
12399 .update_window(*window, |_, window, cx| {
12400 element.layout_line_numbers(
12401 None,
12402 GutterDimensions {
12403 left_padding: Pixels::ZERO,
12404 right_padding: Pixels::ZERO,
12405 width: px(30.0),
12406 margin: Pixels::ZERO,
12407 git_blame_entries_width: None,
12408 },
12409 line_height,
12410 gpui::Point::default(),
12411 DisplayRow(0)..DisplayRow(6),
12412 &(0..6)
12413 .map(|row| RowInfo {
12414 buffer_row: Some(row),
12415 diff_status: (row == DELETED_LINE).then(|| {
12416 DiffHunkStatus::deleted(
12417 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12418 )
12419 }),
12420 ..Default::default()
12421 })
12422 .collect::<Vec<_>>(),
12423 &BTreeMap::default(),
12424 Some(DisplayRow(0)),
12425 &snapshot,
12426 window,
12427 cx,
12428 )
12429 })
12430 .unwrap();
12431 assert_eq!(layouts.len(), 5,);
12432 assert!(
12433 layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12434 "Deleted line should not have a line number"
12435 );
12436 }
12437
12438 #[gpui::test]
12439 async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12440 init_test(cx, |_| {});
12441
12442 let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12443
12444 let window = cx.add_window(|window, cx| {
12445 let buffer = cx.new(|cx| {
12446 Buffer::local(
12447 indoc::indoc! {"
12448 fn test() -> int {
12449 return 2;
12450 }
12451
12452 fn another_test() -> int {
12453 # This is a very peculiar method that is hard to grasp.
12454 return 4;
12455 }
12456 "},
12457 cx,
12458 )
12459 .with_language(python_lang, cx)
12460 });
12461
12462 let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12463 Editor::new(EditorMode::full(), buffer, None, window, cx)
12464 });
12465
12466 let editor = window.root(cx).unwrap();
12467 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12468 let line_height = window
12469 .update(cx, |_, window, _| {
12470 style.text.line_height_in_pixels(window.rem_size())
12471 })
12472 .unwrap();
12473 let element = EditorElement::new(&editor, style);
12474 let snapshot = window
12475 .update(cx, |editor, window, cx| {
12476 editor.fold_at(MultiBufferRow(0), window, cx);
12477 editor.snapshot(window, cx)
12478 })
12479 .unwrap();
12480
12481 let layouts = cx
12482 .update_window(*window, |_, window, cx| {
12483 element.layout_line_numbers(
12484 None,
12485 GutterDimensions {
12486 left_padding: Pixels::ZERO,
12487 right_padding: Pixels::ZERO,
12488 width: px(30.0),
12489 margin: Pixels::ZERO,
12490 git_blame_entries_width: None,
12491 },
12492 line_height,
12493 gpui::Point::default(),
12494 DisplayRow(0)..DisplayRow(6),
12495 &(0..6)
12496 .map(|row| RowInfo {
12497 buffer_row: Some(row),
12498 ..Default::default()
12499 })
12500 .collect::<Vec<_>>(),
12501 &BTreeMap::default(),
12502 Some(DisplayRow(3)),
12503 &snapshot,
12504 window,
12505 cx,
12506 )
12507 })
12508 .unwrap();
12509 assert_eq!(layouts.len(), 6);
12510
12511 let relative_rows = window
12512 .update(cx, |editor, window, cx| {
12513 let snapshot = editor.snapshot(window, cx);
12514 snapshot.calculate_relative_line_numbers(
12515 &(DisplayRow(0)..DisplayRow(6)),
12516 DisplayRow(3),
12517 false,
12518 )
12519 })
12520 .unwrap();
12521 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12522 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12523 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12524 // current line has no relative number
12525 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12526 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12527 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12528 }
12529
12530 #[gpui::test]
12531 fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12532 init_test(cx, |_| {});
12533 let window = cx.add_window(|window, cx| {
12534 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12535 Editor::new(EditorMode::full(), buffer, None, window, cx)
12536 });
12537
12538 update_test_language_settings(cx, |s| {
12539 s.defaults.preferred_line_length = Some(5_u32);
12540 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12541 });
12542
12543 let editor = window.root(cx).unwrap();
12544 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12545 let line_height = window
12546 .update(cx, |_, window, _| {
12547 style.text.line_height_in_pixels(window.rem_size())
12548 })
12549 .unwrap();
12550 let element = EditorElement::new(&editor, style);
12551 let snapshot = window
12552 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12553 .unwrap();
12554
12555 let layouts = cx
12556 .update_window(*window, |_, window, cx| {
12557 element.layout_line_numbers(
12558 None,
12559 GutterDimensions {
12560 left_padding: Pixels::ZERO,
12561 right_padding: Pixels::ZERO,
12562 width: px(30.0),
12563 margin: Pixels::ZERO,
12564 git_blame_entries_width: None,
12565 },
12566 line_height,
12567 gpui::Point::default(),
12568 DisplayRow(0)..DisplayRow(6),
12569 &(0..6)
12570 .map(|row| RowInfo {
12571 buffer_row: Some(row),
12572 ..Default::default()
12573 })
12574 .collect::<Vec<_>>(),
12575 &BTreeMap::default(),
12576 Some(DisplayRow(0)),
12577 &snapshot,
12578 window,
12579 cx,
12580 )
12581 })
12582 .unwrap();
12583 assert_eq!(layouts.len(), 3);
12584
12585 let relative_rows = window
12586 .update(cx, |editor, window, cx| {
12587 let snapshot = editor.snapshot(window, cx);
12588 snapshot.calculate_relative_line_numbers(
12589 &(DisplayRow(0)..DisplayRow(6)),
12590 DisplayRow(3),
12591 true,
12592 )
12593 })
12594 .unwrap();
12595
12596 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12597 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12598 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12599 // current line has no relative number
12600 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12601 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12602 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12603
12604 let layouts = cx
12605 .update_window(*window, |_, window, cx| {
12606 element.layout_line_numbers(
12607 None,
12608 GutterDimensions {
12609 left_padding: Pixels::ZERO,
12610 right_padding: Pixels::ZERO,
12611 width: px(30.0),
12612 margin: Pixels::ZERO,
12613 git_blame_entries_width: None,
12614 },
12615 line_height,
12616 gpui::Point::default(),
12617 DisplayRow(0)..DisplayRow(6),
12618 &(0..6)
12619 .map(|row| RowInfo {
12620 buffer_row: Some(row),
12621 diff_status: Some(DiffHunkStatus::deleted(
12622 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12623 )),
12624 ..Default::default()
12625 })
12626 .collect::<Vec<_>>(),
12627 &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12628 Some(DisplayRow(0)),
12629 &snapshot,
12630 window,
12631 cx,
12632 )
12633 })
12634 .unwrap();
12635 assert!(
12636 layouts.is_empty(),
12637 "Deleted lines should have no line number"
12638 );
12639
12640 let relative_rows = window
12641 .update(cx, |editor, window, cx| {
12642 let snapshot = editor.snapshot(window, cx);
12643 snapshot.calculate_relative_line_numbers(
12644 &(DisplayRow(0)..DisplayRow(6)),
12645 DisplayRow(3),
12646 true,
12647 )
12648 })
12649 .unwrap();
12650
12651 // Deleted lines should still have relative numbers
12652 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12653 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12654 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12655 // current line, even if deleted, has no relative number
12656 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12657 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12658 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12659 }
12660
12661 #[gpui::test]
12662 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12663 init_test(cx, |_| {});
12664
12665 let window = cx.add_window(|window, cx| {
12666 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12667 Editor::new(EditorMode::full(), buffer, None, window, cx)
12668 });
12669 let cx = &mut VisualTestContext::from_window(*window, cx);
12670 let editor = window.root(cx).unwrap();
12671 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12672
12673 window
12674 .update(cx, |editor, window, cx| {
12675 editor.cursor_offset_on_selection = true;
12676 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12677 s.select_ranges([
12678 Point::new(0, 0)..Point::new(1, 0),
12679 Point::new(3, 2)..Point::new(3, 3),
12680 Point::new(5, 6)..Point::new(6, 0),
12681 ]);
12682 });
12683 })
12684 .unwrap();
12685
12686 let (_, state) = cx.draw(
12687 point(px(500.), px(500.)),
12688 size(px(500.), px(500.)),
12689 |_, _| EditorElement::new(&editor, style),
12690 );
12691
12692 assert_eq!(state.selections.len(), 1);
12693 let local_selections = &state.selections[0].1;
12694 assert_eq!(local_selections.len(), 3);
12695 // moves cursor back one line
12696 assert_eq!(
12697 local_selections[0].head,
12698 DisplayPoint::new(DisplayRow(0), 6)
12699 );
12700 assert_eq!(
12701 local_selections[0].range,
12702 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12703 );
12704
12705 // moves cursor back one column
12706 assert_eq!(
12707 local_selections[1].range,
12708 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12709 );
12710 assert_eq!(
12711 local_selections[1].head,
12712 DisplayPoint::new(DisplayRow(3), 2)
12713 );
12714
12715 // leaves cursor on the max point
12716 assert_eq!(
12717 local_selections[2].range,
12718 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12719 );
12720 assert_eq!(
12721 local_selections[2].head,
12722 DisplayPoint::new(DisplayRow(6), 0)
12723 );
12724
12725 // active lines does not include 1 (even though the range of the selection does)
12726 assert_eq!(
12727 state.active_rows.keys().cloned().collect::<Vec<_>>(),
12728 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12729 );
12730 }
12731
12732 #[gpui::test]
12733 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12734 init_test(cx, |_| {});
12735
12736 let window = cx.add_window(|window, cx| {
12737 let buffer = MultiBuffer::build_simple("", cx);
12738 Editor::new(EditorMode::full(), buffer, None, window, cx)
12739 });
12740 let cx = &mut VisualTestContext::from_window(*window, cx);
12741 let editor = window.root(cx).unwrap();
12742 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12743 window
12744 .update(cx, |editor, window, cx| {
12745 editor.set_placeholder_text("hello", window, cx);
12746 editor.insert_blocks(
12747 [BlockProperties {
12748 style: BlockStyle::Fixed,
12749 placement: BlockPlacement::Above(Anchor::min()),
12750 height: Some(3),
12751 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12752 priority: 0,
12753 }],
12754 None,
12755 cx,
12756 );
12757
12758 // Blur the editor so that it displays placeholder text.
12759 window.blur();
12760 })
12761 .unwrap();
12762
12763 let (_, state) = cx.draw(
12764 point(px(500.), px(500.)),
12765 size(px(500.), px(500.)),
12766 |_, _| EditorElement::new(&editor, style),
12767 );
12768 assert_eq!(state.position_map.line_layouts.len(), 4);
12769 assert_eq!(state.line_numbers.len(), 1);
12770 assert_eq!(
12771 state
12772 .line_numbers
12773 .get(&MultiBufferRow(0))
12774 .map(|line_number| line_number
12775 .segments
12776 .first()
12777 .unwrap()
12778 .shaped_line
12779 .text
12780 .as_ref()),
12781 Some("1")
12782 );
12783 }
12784
12785 #[gpui::test]
12786 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12787 const TAB_SIZE: u32 = 4;
12788
12789 let input_text = "\t \t|\t| a b";
12790 let expected_invisibles = vec![
12791 Invisible::Tab {
12792 line_start_offset: 0,
12793 line_end_offset: TAB_SIZE as usize,
12794 },
12795 Invisible::Whitespace {
12796 line_offset: TAB_SIZE as usize,
12797 },
12798 Invisible::Tab {
12799 line_start_offset: TAB_SIZE as usize + 1,
12800 line_end_offset: TAB_SIZE as usize * 2,
12801 },
12802 Invisible::Tab {
12803 line_start_offset: TAB_SIZE as usize * 2 + 1,
12804 line_end_offset: TAB_SIZE as usize * 3,
12805 },
12806 Invisible::Whitespace {
12807 line_offset: TAB_SIZE as usize * 3 + 1,
12808 },
12809 Invisible::Whitespace {
12810 line_offset: TAB_SIZE as usize * 3 + 3,
12811 },
12812 ];
12813 assert_eq!(
12814 expected_invisibles.len(),
12815 input_text
12816 .chars()
12817 .filter(|initial_char| initial_char.is_whitespace())
12818 .count(),
12819 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12820 );
12821
12822 for show_line_numbers in [true, false] {
12823 init_test(cx, |s| {
12824 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12825 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
12826 });
12827
12828 let actual_invisibles = collect_invisibles_from_new_editor(
12829 cx,
12830 EditorMode::full(),
12831 input_text,
12832 px(500.0),
12833 show_line_numbers,
12834 );
12835
12836 assert_eq!(expected_invisibles, actual_invisibles);
12837 }
12838 }
12839
12840 #[gpui::test]
12841 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
12842 init_test(cx, |s| {
12843 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12844 s.defaults.tab_size = NonZeroU32::new(4);
12845 });
12846
12847 for editor_mode_without_invisibles in [
12848 EditorMode::SingleLine,
12849 EditorMode::AutoHeight {
12850 min_lines: 1,
12851 max_lines: Some(100),
12852 },
12853 ] {
12854 for show_line_numbers in [true, false] {
12855 let invisibles = collect_invisibles_from_new_editor(
12856 cx,
12857 editor_mode_without_invisibles.clone(),
12858 "\t\t\t| | a b",
12859 px(500.0),
12860 show_line_numbers,
12861 );
12862 assert!(
12863 invisibles.is_empty(),
12864 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
12865 );
12866 }
12867 }
12868 }
12869
12870 #[gpui::test]
12871 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
12872 let tab_size = 4;
12873 let input_text = "a\tbcd ".repeat(9);
12874 let repeated_invisibles = [
12875 Invisible::Tab {
12876 line_start_offset: 1,
12877 line_end_offset: tab_size as usize,
12878 },
12879 Invisible::Whitespace {
12880 line_offset: tab_size as usize + 3,
12881 },
12882 Invisible::Whitespace {
12883 line_offset: tab_size as usize + 4,
12884 },
12885 Invisible::Whitespace {
12886 line_offset: tab_size as usize + 5,
12887 },
12888 Invisible::Whitespace {
12889 line_offset: tab_size as usize + 6,
12890 },
12891 Invisible::Whitespace {
12892 line_offset: tab_size as usize + 7,
12893 },
12894 ];
12895 let expected_invisibles = std::iter::once(repeated_invisibles)
12896 .cycle()
12897 .take(9)
12898 .flatten()
12899 .collect::<Vec<_>>();
12900 assert_eq!(
12901 expected_invisibles.len(),
12902 input_text
12903 .chars()
12904 .filter(|initial_char| initial_char.is_whitespace())
12905 .count(),
12906 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12907 );
12908 info!("Expected invisibles: {expected_invisibles:?}");
12909
12910 init_test(cx, |_| {});
12911
12912 // Put the same string with repeating whitespace pattern into editors of various size,
12913 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
12914 let resize_step = 10.0;
12915 let mut editor_width = 200.0;
12916 while editor_width <= 1000.0 {
12917 for show_line_numbers in [true, false] {
12918 update_test_language_settings(cx, |s| {
12919 s.defaults.tab_size = NonZeroU32::new(tab_size);
12920 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12921 s.defaults.preferred_line_length = Some(editor_width as u32);
12922 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12923 });
12924
12925 let actual_invisibles = collect_invisibles_from_new_editor(
12926 cx,
12927 EditorMode::full(),
12928 &input_text,
12929 px(editor_width),
12930 show_line_numbers,
12931 );
12932
12933 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
12934 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
12935 let mut i = 0;
12936 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
12937 i = actual_index;
12938 match expected_invisibles.get(i) {
12939 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
12940 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
12941 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
12942 _ => {
12943 panic!(
12944 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
12945 )
12946 }
12947 },
12948 None => {
12949 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
12950 }
12951 }
12952 }
12953 let missing_expected_invisibles = &expected_invisibles[i + 1..];
12954 assert!(
12955 missing_expected_invisibles.is_empty(),
12956 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
12957 );
12958
12959 editor_width += resize_step;
12960 }
12961 }
12962 }
12963
12964 fn collect_invisibles_from_new_editor(
12965 cx: &mut TestAppContext,
12966 editor_mode: EditorMode,
12967 input_text: &str,
12968 editor_width: Pixels,
12969 show_line_numbers: bool,
12970 ) -> Vec<Invisible> {
12971 info!(
12972 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
12973 f32::from(editor_width)
12974 );
12975 let window = cx.add_window(|window, cx| {
12976 let buffer = MultiBuffer::build_simple(input_text, cx);
12977 Editor::new(editor_mode, buffer, None, window, cx)
12978 });
12979 let cx = &mut VisualTestContext::from_window(*window, cx);
12980 let editor = window.root(cx).unwrap();
12981
12982 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12983 window
12984 .update(cx, |editor, _, cx| {
12985 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12986 editor.set_wrap_width(Some(editor_width), cx);
12987 editor.set_show_line_numbers(show_line_numbers, cx);
12988 })
12989 .unwrap();
12990 let (_, state) = cx.draw(
12991 point(px(500.), px(500.)),
12992 size(px(500.), px(500.)),
12993 |_, _| EditorElement::new(&editor, style),
12994 );
12995 state
12996 .position_map
12997 .line_layouts
12998 .iter()
12999 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13000 .cloned()
13001 .collect()
13002 }
13003
13004 #[gpui::test]
13005 fn test_merge_overlapping_ranges() {
13006 let base_bg = Hsla::white();
13007 let color1 = Hsla {
13008 h: 0.0,
13009 s: 0.5,
13010 l: 0.5,
13011 a: 0.5,
13012 };
13013 let color2 = Hsla {
13014 h: 120.0,
13015 s: 0.5,
13016 l: 0.5,
13017 a: 0.5,
13018 };
13019
13020 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13021 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13022 v.iter()
13023 .map(|(r, _)| (r.start.column(), r.end.column()))
13024 .collect()
13025 };
13026
13027 // Test overlapping ranges blend colors
13028 let overlapping = vec![
13029 (display_point(5)..display_point(15), color1),
13030 (display_point(10)..display_point(20), color2),
13031 ];
13032 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13033 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13034
13035 // Test middle segment should have blended color
13036 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13037 assert_eq!(result[1].1, blended);
13038
13039 // Test adjacent same-color ranges merge
13040 let adjacent_same = vec![
13041 (display_point(5)..display_point(10), color1),
13042 (display_point(10)..display_point(15), color1),
13043 ];
13044 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13045 assert_eq!(cols(&result), vec![(5, 15)]);
13046
13047 // Test contained range splits
13048 let contained = vec![
13049 (display_point(5)..display_point(20), color1),
13050 (display_point(10)..display_point(15), color2),
13051 ];
13052 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13053 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13054
13055 // Test multiple overlaps split at every boundary
13056 let color3 = Hsla {
13057 h: 240.0,
13058 s: 0.5,
13059 l: 0.5,
13060 a: 0.5,
13061 };
13062 let complex = vec![
13063 (display_point(5)..display_point(12), color1),
13064 (display_point(8)..display_point(16), color2),
13065 (display_point(10)..display_point(14), color3),
13066 ];
13067 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13068 assert_eq!(
13069 cols(&result),
13070 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13071 );
13072 }
13073
13074 #[gpui::test]
13075 fn test_bg_segments_per_row() {
13076 let base_bg = Hsla::white();
13077
13078 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13079 {
13080 let selection_color = Hsla {
13081 h: 200.0,
13082 s: 0.5,
13083 l: 0.5,
13084 a: 0.5,
13085 };
13086 let player_color = PlayerColor {
13087 cursor: selection_color,
13088 background: selection_color,
13089 selection: selection_color,
13090 };
13091
13092 let spanning_selection = SelectionLayout {
13093 head: DisplayPoint::new(DisplayRow(3), 7),
13094 cursor_shape: CursorShape::Bar,
13095 is_newest: true,
13096 is_local: true,
13097 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13098 active_rows: DisplayRow(1)..DisplayRow(4),
13099 user_name: None,
13100 };
13101
13102 let selections = vec![(player_color, vec![spanning_selection])];
13103 let result = EditorElement::bg_segments_per_row(
13104 DisplayRow(0)..DisplayRow(5),
13105 &selections,
13106 &[],
13107 base_bg,
13108 );
13109
13110 assert_eq!(result.len(), 5);
13111 assert!(result[0].is_empty());
13112 assert_eq!(result[1].len(), 1);
13113 assert_eq!(result[2].len(), 1);
13114 assert_eq!(result[3].len(), 1);
13115 assert!(result[4].is_empty());
13116
13117 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13118 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13119 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13120 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13121 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13122 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13123 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13124 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13125 }
13126
13127 // Case B: selection ends exactly at the start of row 3, excluding row 3
13128 {
13129 let selection_color = Hsla {
13130 h: 120.0,
13131 s: 0.5,
13132 l: 0.5,
13133 a: 0.5,
13134 };
13135 let player_color = PlayerColor {
13136 cursor: selection_color,
13137 background: selection_color,
13138 selection: selection_color,
13139 };
13140
13141 let selection = SelectionLayout {
13142 head: DisplayPoint::new(DisplayRow(2), 0),
13143 cursor_shape: CursorShape::Bar,
13144 is_newest: true,
13145 is_local: true,
13146 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13147 active_rows: DisplayRow(1)..DisplayRow(3),
13148 user_name: None,
13149 };
13150
13151 let selections = vec![(player_color, vec![selection])];
13152 let result = EditorElement::bg_segments_per_row(
13153 DisplayRow(0)..DisplayRow(4),
13154 &selections,
13155 &[],
13156 base_bg,
13157 );
13158
13159 assert_eq!(result.len(), 4);
13160 assert!(result[0].is_empty());
13161 assert_eq!(result[1].len(), 1);
13162 assert_eq!(result[2].len(), 1);
13163 assert!(result[3].is_empty());
13164
13165 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13166 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13167 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13168 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13169 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13170 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13171 }
13172 }
13173
13174 #[cfg(test)]
13175 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13176 TextRun {
13177 len,
13178 color,
13179 ..Default::default()
13180 }
13181 }
13182
13183 #[gpui::test]
13184 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13185 init_test(cx, |_| {});
13186
13187 let dx = |start: u32, end: u32| {
13188 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13189 };
13190
13191 let text_color = Hsla {
13192 h: 210.0,
13193 s: 0.1,
13194 l: 0.4,
13195 a: 1.0,
13196 };
13197 let bg_1 = Hsla {
13198 h: 30.0,
13199 s: 0.6,
13200 l: 0.8,
13201 a: 1.0,
13202 };
13203 let bg_2 = Hsla {
13204 h: 200.0,
13205 s: 0.6,
13206 l: 0.2,
13207 a: 1.0,
13208 };
13209 let min_contrast = 45.0;
13210 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13211 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13212
13213 // Case A: single run; disjoint segments inside the run
13214 {
13215 let runs = vec![generate_test_run(20, text_color)];
13216 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13217 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13218 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13219 assert_eq!(
13220 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13221 vec![5, 5, 2, 4, 4]
13222 );
13223 assert_eq!(out[0].color, text_color);
13224 assert_eq!(out[1].color, adjusted_bg1);
13225 assert_eq!(out[2].color, text_color);
13226 assert_eq!(out[3].color, adjusted_bg2);
13227 assert_eq!(out[4].color, text_color);
13228 }
13229
13230 // Case B: multiple runs; segment extends to end of line (u32::MAX)
13231 {
13232 let runs = vec![
13233 generate_test_run(8, text_color),
13234 generate_test_run(7, text_color),
13235 ];
13236 let segs = vec![(dx(6, u32::MAX), bg_1)];
13237 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13238 // Expected slices across runs: [0,6) [6,8) | [0,7)
13239 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13240 assert_eq!(out[0].color, text_color);
13241 assert_eq!(out[1].color, adjusted_bg1);
13242 assert_eq!(out[2].color, adjusted_bg1);
13243 }
13244
13245 // Case C: multi-byte characters
13246 {
13247 // for text: "Hello π δΈη!"
13248 let runs = vec![
13249 generate_test_run(5, text_color), // "Hello"
13250 generate_test_run(6, text_color), // " π "
13251 generate_test_run(6, text_color), // "δΈη"
13252 generate_test_run(1, text_color), // "!"
13253 ];
13254 // selecting "π δΈ"
13255 let segs = vec![(dx(6, 14), bg_1)];
13256 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13257 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
13258 assert_eq!(
13259 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13260 vec![5, 1, 5, 3, 3, 1]
13261 );
13262 assert_eq!(out[0].color, text_color); // "Hello"
13263 assert_eq!(out[2].color, adjusted_bg1); // "π "
13264 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
13265 assert_eq!(out[4].color, text_color); // "η"
13266 assert_eq!(out[5].color, text_color); // "!"
13267 }
13268
13269 // Case D: split multiple consecutive text runs with segments
13270 {
13271 let segs = vec![
13272 (dx(2, 4), bg_1), // selecting "cd"
13273 (dx(4, 8), bg_2), // selecting "efgh"
13274 (dx(9, 11), bg_1), // selecting "jk"
13275 (dx(12, 16), bg_2), // selecting "mnop"
13276 (dx(18, 19), bg_1), // selecting "s"
13277 ];
13278
13279 // for text: "abcdef"
13280 let runs = vec![
13281 generate_test_run(2, text_color), // ab
13282 generate_test_run(4, text_color), // cdef
13283 ];
13284 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13285 // new splits "ab", "cd", "ef"
13286 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13287 assert_eq!(out[0].color, text_color);
13288 assert_eq!(out[1].color, adjusted_bg1);
13289 assert_eq!(out[2].color, adjusted_bg2);
13290
13291 // for text: "ghijklmn"
13292 let runs = vec![
13293 generate_test_run(3, text_color), // ghi
13294 generate_test_run(2, text_color), // jk
13295 generate_test_run(3, text_color), // lmn
13296 ];
13297 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13298 // new splits "gh", "i", "jk", "l", "mn"
13299 assert_eq!(
13300 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13301 vec![2, 1, 2, 1, 2]
13302 );
13303 assert_eq!(out[0].color, adjusted_bg2);
13304 assert_eq!(out[1].color, text_color);
13305 assert_eq!(out[2].color, adjusted_bg1);
13306 assert_eq!(out[3].color, text_color);
13307 assert_eq!(out[4].color, adjusted_bg2);
13308
13309 // for text: "opqrs"
13310 let runs = vec![
13311 generate_test_run(1, text_color), // o
13312 generate_test_run(4, text_color), // pqrs
13313 ];
13314 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13315 // new splits "o", "p", "qr", "s"
13316 assert_eq!(
13317 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13318 vec![1, 1, 2, 1]
13319 );
13320 assert_eq!(out[0].color, adjusted_bg2);
13321 assert_eq!(out[1].color, adjusted_bg2);
13322 assert_eq!(out[2].color, text_color);
13323 assert_eq!(out[3].color, adjusted_bg1);
13324 }
13325 }
13326
13327 #[test]
13328 fn test_checkerboard_size() {
13329 // line height is smaller than target height, so we just return half the line height
13330 assert_eq!(EditorElement::checkerboard_size(10.0, 20.0), 5.0);
13331
13332 // line height is exactly half the target height, perfect match
13333 assert_eq!(EditorElement::checkerboard_size(20.0, 10.0), 10.0);
13334
13335 // line height is close to half the target height
13336 assert_eq!(EditorElement::checkerboard_size(20.0, 9.0), 10.0);
13337
13338 // line height is close to 1/4 the target height
13339 assert_eq!(EditorElement::checkerboard_size(20.0, 4.8), 5.0);
13340 }
13341
13342 #[gpui::test(iterations = 100)]
13343 fn test_random_checkerboard_size(mut rng: StdRng) {
13344 let line_height = rng.next_u32() as f32;
13345 let target_height = rng.next_u32() as f32;
13346
13347 let result = EditorElement::checkerboard_size(line_height, target_height);
13348
13349 let k = line_height / result;
13350 assert!(k - k.round() < 0.0000001); // approximately integer
13351 assert!((k.round() as u32).is_multiple_of(2));
13352 }
13353
13354 #[test]
13355 fn test_calculate_wrap_width() {
13356 let editor_width = px(800.0);
13357 let em_width = px(8.0);
13358
13359 assert_eq!(
13360 calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13361 None,
13362 );
13363
13364 assert_eq!(
13365 calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13366 Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13367 );
13368
13369 assert_eq!(
13370 calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13371 Some(px(800.0)),
13372 );
13373
13374 assert_eq!(
13375 calculate_wrap_width(SoftWrap::Column(72), editor_width, em_width),
13376 Some(px((72.0 * 8.0_f32).ceil())),
13377 );
13378
13379 assert_eq!(
13380 calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13381 Some(px((72.0 * 8.0_f32).ceil())),
13382 );
13383 assert_eq!(
13384 calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13385 Some(px(400.0)),
13386 );
13387 }
13388}