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(
4230 editor_margins.gutter.width + *scroll_width + editor_margins.extended_right,
4231 )
4232 .into(),
4233 (BlockStyle::FlexClipped, _) => hitbox
4234 .size
4235 .width
4236 .max(fixed_block_max_width)
4237 .max(*scroll_width + editor_margins.extended_right)
4238 .into(),
4239 (BlockStyle::Fixed, _) => unreachable!(),
4240 };
4241 let block_id = block.id();
4242
4243 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4244 focused_block = None;
4245 }
4246
4247 if let Some((element, element_size, row, x_offset)) = self.render_block(
4248 block,
4249 width,
4250 block_id,
4251 row,
4252 snapshot,
4253 text_x,
4254 &rows,
4255 line_layouts,
4256 editor_margins,
4257 line_height,
4258 em_width,
4259 text_hitbox,
4260 editor_width,
4261 scroll_width,
4262 &mut resized_blocks,
4263 &mut row_block_types,
4264 selections,
4265 selected_buffer_ids,
4266 latest_selection_anchors,
4267 is_row_soft_wrapped,
4268 sticky_header_excerpt_id,
4269 &mut block_resize_offset,
4270 window,
4271 cx,
4272 ) {
4273 blocks.push(BlockLayout {
4274 id: block_id,
4275 x_offset,
4276 row: Some(row),
4277 element,
4278 available_space: size(width, element_size.height.into()),
4279 style,
4280 overlaps_gutter: !block.place_near() && style != BlockStyle::FlexClipped,
4281 is_buffer_header: block.is_buffer_header(),
4282 });
4283 }
4284 }
4285
4286 if let Some(focused_block) = focused_block
4287 && let Some(focus_handle) = focused_block.focus_handle.upgrade()
4288 && focus_handle.is_focused(window)
4289 && let Some(block) = snapshot.block_for_id(focused_block.id)
4290 {
4291 let style = block.style();
4292 let width = match style {
4293 BlockStyle::Fixed => AvailableSpace::MinContent,
4294 BlockStyle::Flex => {
4295 AvailableSpace::Definite(hitbox.size.width.max(fixed_block_max_width).max(
4296 editor_margins.gutter.width + *scroll_width + editor_margins.extended_right,
4297 ))
4298 }
4299 BlockStyle::FlexClipped => AvailableSpace::Definite(
4300 hitbox
4301 .size
4302 .width
4303 .max(fixed_block_max_width)
4304 .max(*scroll_width + editor_margins.extended_right),
4305 ),
4306 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
4307 };
4308
4309 if let Some((element, element_size, _, x_offset)) = self.render_block(
4310 &block,
4311 width,
4312 focused_block.id,
4313 rows.end,
4314 snapshot,
4315 text_x,
4316 &rows,
4317 line_layouts,
4318 editor_margins,
4319 line_height,
4320 em_width,
4321 text_hitbox,
4322 editor_width,
4323 scroll_width,
4324 &mut resized_blocks,
4325 &mut row_block_types,
4326 selections,
4327 selected_buffer_ids,
4328 latest_selection_anchors,
4329 is_row_soft_wrapped,
4330 sticky_header_excerpt_id,
4331 &mut block_resize_offset,
4332 window,
4333 cx,
4334 ) {
4335 blocks.push(BlockLayout {
4336 id: block.id(),
4337 x_offset,
4338 row: None,
4339 element,
4340 available_space: size(width, element_size.height.into()),
4341 style,
4342 overlaps_gutter: true,
4343 is_buffer_header: block.is_buffer_header(),
4344 });
4345 }
4346 }
4347
4348 if resized_blocks.is_empty() {
4349 *scroll_width =
4350 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
4351 }
4352
4353 RenderBlocksOutput {
4354 blocks,
4355 row_block_types,
4356 resized_blocks: (!resized_blocks.is_empty()).then_some(resized_blocks),
4357 }
4358 }
4359
4360 fn layout_blocks(
4361 &self,
4362 blocks: &mut Vec<BlockLayout>,
4363 hitbox: &Hitbox,
4364 gutter_hitbox: &Hitbox,
4365 line_height: Pixels,
4366 scroll_position: gpui::Point<ScrollOffset>,
4367 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4368 window: &mut Window,
4369 cx: &mut App,
4370 ) {
4371 for block in blocks {
4372 let mut origin = if let Some(row) = block.row {
4373 hitbox.origin
4374 + point(
4375 block.x_offset,
4376 Pixels::from(
4377 (row.as_f64() - scroll_position.y)
4378 * ScrollPixelOffset::from(line_height),
4379 ),
4380 )
4381 } else {
4382 // Position the block outside the visible area
4383 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
4384 };
4385
4386 if block.style == BlockStyle::FlexClipped {
4387 origin += point(gutter_hitbox.size.width, Pixels::ZERO);
4388 }
4389
4390 if !matches!(block.style, BlockStyle::Sticky) {
4391 origin += point(Pixels::from(-scroll_pixel_position.x), Pixels::ZERO);
4392 }
4393
4394 let focus_handle =
4395 block
4396 .element
4397 .prepaint_as_root(origin, block.available_space, window, cx);
4398
4399 if let Some(focus_handle) = focus_handle {
4400 self.editor.update(cx, |editor, _cx| {
4401 editor.set_focused_block(FocusedBlock {
4402 id: block.id,
4403 focus_handle: focus_handle.downgrade(),
4404 });
4405 });
4406 }
4407 }
4408 }
4409
4410 fn layout_sticky_buffer_header(
4411 &self,
4412 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
4413 scroll_position: gpui::Point<ScrollOffset>,
4414 line_height: Pixels,
4415 right_margin: Pixels,
4416 snapshot: &EditorSnapshot,
4417 hitbox: &Hitbox,
4418 selected_buffer_ids: &Vec<BufferId>,
4419 blocks: &[BlockLayout],
4420 latest_selection_anchors: &HashMap<BufferId, Anchor>,
4421 window: &mut Window,
4422 cx: &mut App,
4423 ) -> AnyElement {
4424 let jump_data = header_jump_data(
4425 snapshot,
4426 DisplayRow(scroll_position.y as u32),
4427 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4428 excerpt,
4429 latest_selection_anchors,
4430 );
4431
4432 let editor_bg_color = cx.theme().colors().editor_background;
4433
4434 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4435
4436 let available_width = hitbox.bounds.size.width - right_margin;
4437
4438 let mut header = v_flex()
4439 .w_full()
4440 .relative()
4441 .child(
4442 div()
4443 .w(available_width)
4444 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4445 .bg(linear_gradient(
4446 0.,
4447 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4448 linear_color_stop(editor_bg_color, 0.6),
4449 ))
4450 .absolute()
4451 .top_0(),
4452 )
4453 .child(
4454 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4455 .into_any_element(),
4456 )
4457 .into_any_element();
4458
4459 let mut origin = hitbox.origin;
4460 // Move floating header up to avoid colliding with the next buffer header.
4461 for block in blocks.iter() {
4462 if !block.is_buffer_header {
4463 continue;
4464 }
4465
4466 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position.y as u32) else {
4467 continue;
4468 };
4469
4470 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4471 let offset = scroll_position.y - max_row as f64;
4472
4473 if offset > 0.0 {
4474 origin.y -= Pixels::from(offset * ScrollPixelOffset::from(line_height));
4475 }
4476 break;
4477 }
4478
4479 let size = size(
4480 AvailableSpace::Definite(available_width),
4481 AvailableSpace::MinContent,
4482 );
4483
4484 header.prepaint_as_root(origin, size, window, cx);
4485
4486 header
4487 }
4488
4489 fn layout_sticky_headers(
4490 &self,
4491 snapshot: &EditorSnapshot,
4492 editor_width: Pixels,
4493 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4494 line_height: Pixels,
4495 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4496 content_origin: gpui::Point<Pixels>,
4497 gutter_dimensions: &GutterDimensions,
4498 gutter_hitbox: &Hitbox,
4499 text_hitbox: &Hitbox,
4500 relative_line_numbers: RelativeLineNumbers,
4501 relative_to: Option<DisplayRow>,
4502 window: &mut Window,
4503 cx: &mut App,
4504 ) -> Option<StickyHeaders> {
4505 let show_line_numbers = snapshot
4506 .show_line_numbers
4507 .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
4508
4509 let rows = Self::sticky_headers(self.editor.read(cx), snapshot);
4510
4511 let mut lines = Vec::<StickyHeaderLine>::new();
4512
4513 for StickyHeader {
4514 item,
4515 sticky_row,
4516 start_point,
4517 offset,
4518 } in rows.into_iter().rev()
4519 {
4520 let line = layout_line(
4521 sticky_row,
4522 snapshot,
4523 &self.style,
4524 editor_width,
4525 is_row_soft_wrapped,
4526 window,
4527 cx,
4528 );
4529
4530 let line_number = show_line_numbers.then(|| {
4531 let start_display_row = start_point.to_display_point(snapshot).row();
4532 let relative_number = relative_to
4533 .filter(|_| relative_line_numbers != RelativeLineNumbers::Disabled)
4534 .map(|base| {
4535 snapshot.relative_line_delta(
4536 base,
4537 start_display_row,
4538 relative_line_numbers == RelativeLineNumbers::Wrapped,
4539 )
4540 });
4541 let number = relative_number
4542 .filter(|&delta| delta != 0)
4543 .map(|delta| delta.unsigned_abs() as u32)
4544 .unwrap_or(start_point.row + 1);
4545 let color = cx.theme().colors().editor_line_number;
4546 self.shape_line_number(SharedString::from(number.to_string()), color, window)
4547 });
4548
4549 lines.push(StickyHeaderLine::new(
4550 sticky_row,
4551 line_height * offset as f32,
4552 line,
4553 line_number,
4554 item.range.start,
4555 line_height,
4556 scroll_pixel_position,
4557 content_origin,
4558 gutter_hitbox,
4559 text_hitbox,
4560 window,
4561 cx,
4562 ));
4563 }
4564
4565 lines.reverse();
4566 if lines.is_empty() {
4567 return None;
4568 }
4569
4570 Some(StickyHeaders {
4571 lines,
4572 gutter_background: cx.theme().colors().editor_gutter_background,
4573 content_background: self.style.background,
4574 gutter_right_padding: gutter_dimensions.right_padding,
4575 })
4576 }
4577
4578 pub(crate) fn sticky_headers(editor: &Editor, snapshot: &EditorSnapshot) -> Vec<StickyHeader> {
4579 let scroll_top = snapshot.scroll_position().y;
4580
4581 let mut end_rows = Vec::<DisplayRow>::new();
4582 let mut rows = Vec::<StickyHeader>::new();
4583
4584 for item in editor.sticky_headers.iter().flatten() {
4585 let start_point = item.range.start.to_point(snapshot.buffer_snapshot());
4586 let end_point = item.range.end.to_point(snapshot.buffer_snapshot());
4587
4588 let sticky_row = snapshot
4589 .display_snapshot
4590 .point_to_display_point(start_point, Bias::Left)
4591 .row();
4592 let end_row = snapshot
4593 .display_snapshot
4594 .point_to_display_point(end_point, Bias::Left)
4595 .row();
4596 let max_sticky_row = end_row.previous_row();
4597 if max_sticky_row <= sticky_row {
4598 continue;
4599 }
4600
4601 while end_rows
4602 .last()
4603 .is_some_and(|&last_end| last_end <= sticky_row)
4604 {
4605 end_rows.pop();
4606 }
4607 let depth = end_rows.len();
4608 let adjusted_scroll_top = scroll_top + depth as f64;
4609
4610 if sticky_row.as_f64() >= adjusted_scroll_top || end_row.as_f64() <= adjusted_scroll_top
4611 {
4612 continue;
4613 }
4614
4615 let max_scroll_offset = max_sticky_row.as_f64() - scroll_top;
4616 let offset = (depth as f64).min(max_scroll_offset);
4617
4618 end_rows.push(end_row);
4619 rows.push(StickyHeader {
4620 item: item.clone(),
4621 sticky_row,
4622 start_point,
4623 offset,
4624 });
4625 }
4626
4627 rows
4628 }
4629
4630 fn layout_cursor_popovers(
4631 &self,
4632 line_height: Pixels,
4633 text_hitbox: &Hitbox,
4634 content_origin: gpui::Point<Pixels>,
4635 right_margin: Pixels,
4636 start_row: DisplayRow,
4637 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4638 line_layouts: &[LineWithInvisibles],
4639 cursor: DisplayPoint,
4640 cursor_point: Point,
4641 style: &EditorStyle,
4642 window: &mut Window,
4643 cx: &mut App,
4644 ) -> Option<ContextMenuLayout> {
4645 let mut min_menu_height = Pixels::ZERO;
4646 let mut max_menu_height = Pixels::ZERO;
4647 let mut height_above_menu = Pixels::ZERO;
4648 let height_below_menu = Pixels::ZERO;
4649 let mut edit_prediction_popover_visible = false;
4650 let mut context_menu_visible = false;
4651 let context_menu_placement;
4652
4653 {
4654 let editor = self.editor.read(cx);
4655 if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
4656 {
4657 height_above_menu +=
4658 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4659 edit_prediction_popover_visible = true;
4660 }
4661
4662 if editor.context_menu_visible()
4663 && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
4664 {
4665 let (min_height_in_lines, max_height_in_lines) = editor
4666 .context_menu_options
4667 .as_ref()
4668 .map_or((3, 12), |options| {
4669 (options.min_entries_visible, options.max_entries_visible)
4670 });
4671
4672 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4673 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4674 context_menu_visible = true;
4675 }
4676 context_menu_placement = editor
4677 .context_menu_options
4678 .as_ref()
4679 .and_then(|options| options.placement.clone());
4680 }
4681
4682 let visible = edit_prediction_popover_visible || context_menu_visible;
4683 if !visible {
4684 return None;
4685 }
4686
4687 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4688 let target_position = content_origin
4689 + gpui::Point {
4690 x: cmp::max(
4691 px(0.),
4692 Pixels::from(
4693 ScrollPixelOffset::from(
4694 cursor_row_layout.x_for_index(cursor.column() as usize),
4695 ) - scroll_pixel_position.x,
4696 ),
4697 ),
4698 y: cmp::max(
4699 px(0.),
4700 Pixels::from(
4701 cursor.row().next_row().as_f64() * ScrollPixelOffset::from(line_height)
4702 - scroll_pixel_position.y,
4703 ),
4704 ),
4705 };
4706
4707 let viewport_bounds =
4708 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4709 right: -right_margin - MENU_GAP,
4710 ..Default::default()
4711 });
4712
4713 let min_height = height_above_menu + min_menu_height + height_below_menu;
4714 let max_height = height_above_menu + max_menu_height + height_below_menu;
4715 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4716 target_position,
4717 line_height,
4718 min_height,
4719 max_height,
4720 context_menu_placement,
4721 text_hitbox,
4722 viewport_bounds,
4723 window,
4724 cx,
4725 |height, max_width_for_stable_x, y_flipped, window, cx| {
4726 // First layout the menu to get its size - others can be at least this wide.
4727 let context_menu = if context_menu_visible {
4728 let menu_height = if y_flipped {
4729 height - height_below_menu
4730 } else {
4731 height - height_above_menu
4732 };
4733 let mut element = self
4734 .render_context_menu(line_height, menu_height, window, cx)
4735 .expect("Visible context menu should always render.");
4736 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4737 Some((CursorPopoverType::CodeContextMenu, element, size))
4738 } else {
4739 None
4740 };
4741 let min_width = context_menu
4742 .as_ref()
4743 .map_or(px(0.), |(_, _, size)| size.width);
4744 let max_width = max_width_for_stable_x.max(
4745 context_menu
4746 .as_ref()
4747 .map_or(px(0.), |(_, _, size)| size.width),
4748 );
4749
4750 let edit_prediction = if edit_prediction_popover_visible {
4751 self.editor.update(cx, move |editor, cx| {
4752 let accept_binding = editor.accept_edit_prediction_keybind(
4753 EditPredictionGranularity::Full,
4754 window,
4755 cx,
4756 );
4757 let mut element = editor.render_edit_prediction_cursor_popover(
4758 min_width,
4759 max_width,
4760 cursor_point,
4761 style,
4762 accept_binding.keystroke(),
4763 window,
4764 cx,
4765 )?;
4766 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4767 Some((CursorPopoverType::EditPrediction, element, size))
4768 })
4769 } else {
4770 None
4771 };
4772 vec![edit_prediction, context_menu]
4773 .into_iter()
4774 .flatten()
4775 .collect::<Vec<_>>()
4776 },
4777 )?;
4778
4779 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4780 .iter()
4781 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4782 let last_ix = laid_out_popovers.len() - 1;
4783 let menu_is_last = menu_ix == last_ix;
4784 let first_popover_bounds = laid_out_popovers[0].1;
4785 let last_popover_bounds = laid_out_popovers[last_ix].1;
4786
4787 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4788 // right, and otherwise it goes below or to the right.
4789 let mut target_bounds = Bounds::from_corners(
4790 first_popover_bounds.origin,
4791 last_popover_bounds.bottom_right(),
4792 );
4793 target_bounds.size.width = menu_bounds.size.width;
4794
4795 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4796 // based on this is preferred for layout stability.
4797 let mut max_target_bounds = target_bounds;
4798 max_target_bounds.size.height = max_height;
4799 if y_flipped {
4800 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4801 }
4802
4803 // Add spacing around `target_bounds` and `max_target_bounds`.
4804 let mut extend_amount = Edges::all(MENU_GAP);
4805 if y_flipped {
4806 extend_amount.bottom = line_height;
4807 } else {
4808 extend_amount.top = line_height;
4809 }
4810 let target_bounds = target_bounds.extend(extend_amount);
4811 let max_target_bounds = max_target_bounds.extend(extend_amount);
4812
4813 let must_place_above_or_below =
4814 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4815 laid_out_popovers[menu_ix + 1..]
4816 .iter()
4817 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4818 } else {
4819 false
4820 };
4821
4822 let aside_bounds = self.layout_context_menu_aside(
4823 y_flipped,
4824 *menu_bounds,
4825 target_bounds,
4826 max_target_bounds,
4827 max_menu_height,
4828 must_place_above_or_below,
4829 text_hitbox,
4830 viewport_bounds,
4831 window,
4832 cx,
4833 );
4834
4835 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4836 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4837 Some(*bounds)
4838 } else {
4839 None
4840 }
4841 }) {
4842 let bounds = if let Some(aside_bounds) = aside_bounds {
4843 menu_bounds.union(&aside_bounds)
4844 } else {
4845 menu_bounds
4846 };
4847 return Some(ContextMenuLayout { y_flipped, bounds });
4848 }
4849
4850 None
4851 }
4852
4853 fn layout_gutter_menu(
4854 &self,
4855 line_height: Pixels,
4856 text_hitbox: &Hitbox,
4857 content_origin: gpui::Point<Pixels>,
4858 right_margin: Pixels,
4859 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4860 gutter_overshoot: Pixels,
4861 window: &mut Window,
4862 cx: &mut App,
4863 ) {
4864 let editor = self.editor.read(cx);
4865 if !editor.context_menu_visible() {
4866 return;
4867 }
4868 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4869 editor.context_menu_origin()
4870 else {
4871 return;
4872 };
4873 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4874 // indicator than just a plain first column of the text field.
4875 let target_position = content_origin
4876 + gpui::Point {
4877 x: -gutter_overshoot,
4878 y: Pixels::from(
4879 gutter_row.next_row().as_f64() * ScrollPixelOffset::from(line_height)
4880 - scroll_pixel_position.y,
4881 ),
4882 };
4883
4884 let (min_height_in_lines, max_height_in_lines) = editor
4885 .context_menu_options
4886 .as_ref()
4887 .map_or((3, 12), |options| {
4888 (options.min_entries_visible, options.max_entries_visible)
4889 });
4890
4891 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4892 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4893 let viewport_bounds =
4894 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4895 right: -right_margin - MENU_GAP,
4896 ..Default::default()
4897 });
4898 self.layout_popovers_above_or_below_line(
4899 target_position,
4900 line_height,
4901 min_height,
4902 max_height,
4903 editor
4904 .context_menu_options
4905 .as_ref()
4906 .and_then(|options| options.placement.clone()),
4907 text_hitbox,
4908 viewport_bounds,
4909 window,
4910 cx,
4911 move |height, _max_width_for_stable_x, _, window, cx| {
4912 let mut element = self
4913 .render_context_menu(line_height, height, window, cx)
4914 .expect("Visible context menu should always render.");
4915 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4916 vec![(CursorPopoverType::CodeContextMenu, element, size)]
4917 },
4918 );
4919 }
4920
4921 fn layout_popovers_above_or_below_line(
4922 &self,
4923 target_position: gpui::Point<Pixels>,
4924 line_height: Pixels,
4925 min_height: Pixels,
4926 max_height: Pixels,
4927 placement: Option<ContextMenuPlacement>,
4928 text_hitbox: &Hitbox,
4929 viewport_bounds: Bounds<Pixels>,
4930 window: &mut Window,
4931 cx: &mut App,
4932 make_sized_popovers: impl FnOnce(
4933 Pixels,
4934 Pixels,
4935 bool,
4936 &mut Window,
4937 &mut App,
4938 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
4939 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
4940 let text_style = TextStyleRefinement {
4941 line_height: Some(DefiniteLength::Fraction(
4942 BufferLineHeight::Comfortable.value(),
4943 )),
4944 ..Default::default()
4945 };
4946 window.with_text_style(Some(text_style), |window| {
4947 // If the max height won't fit below and there is more space above, put it above the line.
4948 let bottom_y_when_flipped = target_position.y - line_height;
4949 let available_above = bottom_y_when_flipped - text_hitbox.top();
4950 let available_below = text_hitbox.bottom() - target_position.y;
4951 let y_overflows_below = max_height > available_below;
4952 let mut y_flipped = match placement {
4953 Some(ContextMenuPlacement::Above) => true,
4954 Some(ContextMenuPlacement::Below) => false,
4955 None => y_overflows_below && available_above > available_below,
4956 };
4957 let mut height = cmp::min(
4958 max_height,
4959 if y_flipped {
4960 available_above
4961 } else {
4962 available_below
4963 },
4964 );
4965
4966 // If the min height doesn't fit within text bounds, instead fit within the window.
4967 if height < min_height {
4968 let available_above = bottom_y_when_flipped;
4969 let available_below = viewport_bounds.bottom() - target_position.y;
4970 let (y_flipped_override, height_override) = match placement {
4971 Some(ContextMenuPlacement::Above) => {
4972 (true, cmp::min(available_above, min_height))
4973 }
4974 Some(ContextMenuPlacement::Below) => {
4975 (false, cmp::min(available_below, min_height))
4976 }
4977 None => {
4978 if available_below > min_height {
4979 (false, min_height)
4980 } else if available_above > min_height {
4981 (true, min_height)
4982 } else if available_above > available_below {
4983 (true, available_above)
4984 } else {
4985 (false, available_below)
4986 }
4987 }
4988 };
4989 y_flipped = y_flipped_override;
4990 height = height_override;
4991 }
4992
4993 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
4994
4995 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
4996 // for very narrow windows.
4997 let popovers =
4998 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
4999 if popovers.is_empty() {
5000 return None;
5001 }
5002
5003 let max_width = popovers
5004 .iter()
5005 .map(|(_, _, size)| size.width)
5006 .max()
5007 .unwrap_or_default();
5008
5009 let mut current_position = gpui::Point {
5010 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
5011 // overflow. Include space for the scrollbar.
5012 x: target_position
5013 .x
5014 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
5015 y: if y_flipped {
5016 bottom_y_when_flipped
5017 } else {
5018 target_position.y
5019 },
5020 };
5021
5022 let mut laid_out_popovers = popovers
5023 .into_iter()
5024 .map(|(popover_type, element, size)| {
5025 if y_flipped {
5026 current_position.y -= size.height;
5027 }
5028 let position = current_position;
5029 window.defer_draw(element, current_position, 1);
5030 if !y_flipped {
5031 current_position.y += size.height + MENU_GAP;
5032 } else {
5033 current_position.y -= MENU_GAP;
5034 }
5035 (popover_type, Bounds::new(position, size))
5036 })
5037 .collect::<Vec<_>>();
5038
5039 if y_flipped {
5040 laid_out_popovers.reverse();
5041 }
5042
5043 Some((laid_out_popovers, y_flipped))
5044 })
5045 }
5046
5047 fn layout_context_menu_aside(
5048 &self,
5049 y_flipped: bool,
5050 menu_bounds: Bounds<Pixels>,
5051 target_bounds: Bounds<Pixels>,
5052 max_target_bounds: Bounds<Pixels>,
5053 max_height: Pixels,
5054 must_place_above_or_below: bool,
5055 text_hitbox: &Hitbox,
5056 viewport_bounds: Bounds<Pixels>,
5057 window: &mut Window,
5058 cx: &mut App,
5059 ) -> Option<Bounds<Pixels>> {
5060 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
5061 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
5062 && !must_place_above_or_below
5063 {
5064 let max_width = cmp::min(
5065 available_within_viewport.right - px(1.),
5066 MENU_ASIDE_MAX_WIDTH,
5067 );
5068 let mut aside = self.render_context_menu_aside(
5069 size(max_width, max_height - POPOVER_Y_PADDING),
5070 window,
5071 cx,
5072 )?;
5073 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5074 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
5075 Some((aside, right_position, size))
5076 } else {
5077 let max_size = size(
5078 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
5079 // won't be needed here.
5080 cmp::min(
5081 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
5082 viewport_bounds.right(),
5083 ),
5084 cmp::min(
5085 max_height,
5086 cmp::max(
5087 available_within_viewport.top,
5088 available_within_viewport.bottom,
5089 ),
5090 ) - POPOVER_Y_PADDING,
5091 );
5092 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
5093 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5094
5095 let top_position = point(
5096 menu_bounds.origin.x,
5097 target_bounds.top() - actual_size.height,
5098 );
5099 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
5100
5101 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
5102 // Prefer to fit on the same side of the line as the menu, then on the other side of
5103 // the line.
5104 if !y_flipped && wanted.height < available.bottom {
5105 Some(bottom_position)
5106 } else if !y_flipped && wanted.height < available.top {
5107 Some(top_position)
5108 } else if y_flipped && wanted.height < available.top {
5109 Some(top_position)
5110 } else if y_flipped && wanted.height < available.bottom {
5111 Some(bottom_position)
5112 } else {
5113 None
5114 }
5115 };
5116
5117 // Prefer choosing a direction using max sizes rather than actual size for stability.
5118 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
5119 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
5120 let aside_position = fit_within(available_within_text, wanted)
5121 // Fallback: fit max size in window.
5122 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
5123 // Fallback: fit actual size in window.
5124 .or_else(|| fit_within(available_within_viewport, actual_size));
5125
5126 aside_position.map(|position| (aside, position, actual_size))
5127 };
5128
5129 // Skip drawing if it doesn't fit anywhere.
5130 if let Some((aside, position, size)) = positioned_aside {
5131 let aside_bounds = Bounds::new(position, size);
5132 window.defer_draw(aside, position, 2);
5133 return Some(aside_bounds);
5134 }
5135
5136 None
5137 }
5138
5139 fn render_context_menu(
5140 &self,
5141 line_height: Pixels,
5142 height: Pixels,
5143 window: &mut Window,
5144 cx: &mut App,
5145 ) -> Option<AnyElement> {
5146 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
5147 self.editor.update(cx, |editor, cx| {
5148 editor.render_context_menu(max_height_in_lines, window, cx)
5149 })
5150 }
5151
5152 fn render_context_menu_aside(
5153 &self,
5154 max_size: Size<Pixels>,
5155 window: &mut Window,
5156 cx: &mut App,
5157 ) -> Option<AnyElement> {
5158 if max_size.width < px(100.) || max_size.height < px(12.) {
5159 None
5160 } else {
5161 self.editor.update(cx, |editor, cx| {
5162 editor.render_context_menu_aside(max_size, window, cx)
5163 })
5164 }
5165 }
5166
5167 fn layout_mouse_context_menu(
5168 &self,
5169 editor_snapshot: &EditorSnapshot,
5170 visible_range: Range<DisplayRow>,
5171 content_origin: gpui::Point<Pixels>,
5172 window: &mut Window,
5173 cx: &mut App,
5174 ) -> Option<AnyElement> {
5175 let position = self.editor.update(cx, |editor, cx| {
5176 let visible_start_point = editor.display_to_pixel_point(
5177 DisplayPoint::new(visible_range.start, 0),
5178 editor_snapshot,
5179 window,
5180 cx,
5181 )?;
5182 let visible_end_point = editor.display_to_pixel_point(
5183 DisplayPoint::new(visible_range.end, 0),
5184 editor_snapshot,
5185 window,
5186 cx,
5187 )?;
5188
5189 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5190 let (source_display_point, position) = match mouse_context_menu.position {
5191 MenuPosition::PinnedToScreen(point) => (None, point),
5192 MenuPosition::PinnedToEditor { source, offset } => {
5193 let source_display_point = source.to_display_point(editor_snapshot);
5194 let source_point =
5195 editor.to_pixel_point(source, editor_snapshot, window, cx)?;
5196 let position = content_origin + source_point + offset;
5197 (Some(source_display_point), position)
5198 }
5199 };
5200
5201 let source_included = source_display_point.is_none_or(|source_display_point| {
5202 visible_range
5203 .to_inclusive()
5204 .contains(&source_display_point.row())
5205 });
5206 let position_included =
5207 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
5208 if !source_included && !position_included {
5209 None
5210 } else {
5211 Some(position)
5212 }
5213 })?;
5214
5215 let text_style = TextStyleRefinement {
5216 line_height: Some(DefiniteLength::Fraction(
5217 BufferLineHeight::Comfortable.value(),
5218 )),
5219 ..Default::default()
5220 };
5221 window.with_text_style(Some(text_style), |window| {
5222 let mut element = self.editor.read_with(cx, |editor, _| {
5223 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5224 let context_menu = mouse_context_menu.context_menu.clone();
5225
5226 Some(
5227 deferred(
5228 anchored()
5229 .position(position)
5230 .child(context_menu)
5231 .anchor(Corner::TopLeft)
5232 .snap_to_window_with_margin(px(8.)),
5233 )
5234 .with_priority(1)
5235 .into_any(),
5236 )
5237 })?;
5238
5239 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
5240 Some(element)
5241 })
5242 }
5243
5244 fn layout_hover_popovers(
5245 &self,
5246 snapshot: &EditorSnapshot,
5247 hitbox: &Hitbox,
5248 visible_display_row_range: Range<DisplayRow>,
5249 content_origin: gpui::Point<Pixels>,
5250 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5251 line_layouts: &[LineWithInvisibles],
5252 line_height: Pixels,
5253 em_width: Pixels,
5254 context_menu_layout: Option<ContextMenuLayout>,
5255 window: &mut Window,
5256 cx: &mut App,
5257 ) {
5258 struct MeasuredHoverPopover {
5259 element: AnyElement,
5260 size: Size<Pixels>,
5261 horizontal_offset: Pixels,
5262 }
5263
5264 let max_size = size(
5265 (120. * em_width) // Default size
5266 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5267 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5268 (16. * line_height) // Default size
5269 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5270 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5271 );
5272
5273 // Don't show hover popovers when context menu is open to avoid overlap
5274 let has_context_menu = self.editor.read(cx).mouse_context_menu.is_some();
5275 if has_context_menu {
5276 return;
5277 }
5278
5279 let hover_popovers = self.editor.update(cx, |editor, cx| {
5280 editor.hover_state.render(
5281 snapshot,
5282 visible_display_row_range.clone(),
5283 max_size,
5284 &editor.text_layout_details(window, cx),
5285 window,
5286 cx,
5287 )
5288 });
5289 let Some((popover_position, hover_popovers)) = hover_popovers else {
5290 return;
5291 };
5292
5293 // This is safe because we check on layout whether the required row is available
5294 let hovered_row_layout = &line_layouts[popover_position
5295 .row()
5296 .minus(visible_display_row_range.start)
5297 as usize];
5298
5299 // Compute Hovered Point
5300 let x = hovered_row_layout.x_for_index(popover_position.column() as usize)
5301 - Pixels::from(scroll_pixel_position.x);
5302 let y = Pixels::from(
5303 popover_position.row().as_f64() * ScrollPixelOffset::from(line_height)
5304 - scroll_pixel_position.y,
5305 );
5306 let hovered_point = content_origin + point(x, y);
5307
5308 let mut overall_height = Pixels::ZERO;
5309 let mut measured_hover_popovers = Vec::new();
5310 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
5311 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
5312 let horizontal_offset =
5313 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
5314 .min(Pixels::ZERO);
5315 match position {
5316 itertools::Position::Middle | itertools::Position::Last => {
5317 overall_height += HOVER_POPOVER_GAP
5318 }
5319 _ => {}
5320 }
5321 overall_height += size.height;
5322 measured_hover_popovers.push(MeasuredHoverPopover {
5323 element: hover_popover,
5324 size,
5325 horizontal_offset,
5326 });
5327 }
5328
5329 fn draw_occluder(
5330 width: Pixels,
5331 origin: gpui::Point<Pixels>,
5332 window: &mut Window,
5333 cx: &mut App,
5334 ) {
5335 let mut occlusion = div()
5336 .size_full()
5337 .occlude()
5338 .on_mouse_move(|_, _, cx| cx.stop_propagation())
5339 .into_any_element();
5340 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
5341 window.defer_draw(occlusion, origin, 2);
5342 }
5343
5344 fn place_popovers_above(
5345 hovered_point: gpui::Point<Pixels>,
5346 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5347 window: &mut Window,
5348 cx: &mut App,
5349 ) {
5350 let mut current_y = hovered_point.y;
5351 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5352 let size = popover.size;
5353 let popover_origin = point(
5354 hovered_point.x + popover.horizontal_offset,
5355 current_y - size.height,
5356 );
5357
5358 window.defer_draw(popover.element, popover_origin, 2);
5359 if position != itertools::Position::Last {
5360 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
5361 draw_occluder(size.width, origin, window, cx);
5362 }
5363
5364 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5365 }
5366 }
5367
5368 fn place_popovers_below(
5369 hovered_point: gpui::Point<Pixels>,
5370 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5371 line_height: Pixels,
5372 window: &mut Window,
5373 cx: &mut App,
5374 ) {
5375 let mut current_y = hovered_point.y + line_height;
5376 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5377 let size = popover.size;
5378 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5379
5380 window.defer_draw(popover.element, popover_origin, 2);
5381 if position != itertools::Position::Last {
5382 let origin = point(popover_origin.x, popover_origin.y + size.height);
5383 draw_occluder(size.width, origin, window, cx);
5384 }
5385
5386 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5387 }
5388 }
5389
5390 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5391 context_menu_layout
5392 .as_ref()
5393 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5394 };
5395
5396 let can_place_above = {
5397 let mut bounds_above = Vec::new();
5398 let mut current_y = hovered_point.y;
5399 for popover in &measured_hover_popovers {
5400 let size = popover.size;
5401 let popover_origin = point(
5402 hovered_point.x + popover.horizontal_offset,
5403 current_y - size.height,
5404 );
5405 bounds_above.push(Bounds::new(popover_origin, size));
5406 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5407 }
5408 bounds_above
5409 .iter()
5410 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5411 };
5412
5413 let can_place_below = || {
5414 let mut bounds_below = Vec::new();
5415 let mut current_y = hovered_point.y + line_height;
5416 for popover in &measured_hover_popovers {
5417 let size = popover.size;
5418 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5419 bounds_below.push(Bounds::new(popover_origin, size));
5420 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5421 }
5422 bounds_below
5423 .iter()
5424 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5425 };
5426
5427 if can_place_above {
5428 // try placing above hovered point
5429 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5430 } else if can_place_below() {
5431 // try placing below hovered point
5432 place_popovers_below(
5433 hovered_point,
5434 measured_hover_popovers,
5435 line_height,
5436 window,
5437 cx,
5438 );
5439 } else {
5440 // try to place popovers around the context menu
5441 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5442 let total_width = measured_hover_popovers
5443 .iter()
5444 .map(|p| p.size.width)
5445 .max()
5446 .unwrap_or(Pixels::ZERO);
5447 let y_for_horizontal_positioning = if menu.y_flipped {
5448 menu.bounds.bottom() - overall_height
5449 } else {
5450 menu.bounds.top()
5451 };
5452 let possible_origins = vec![
5453 // left of context menu
5454 point(
5455 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
5456 y_for_horizontal_positioning,
5457 ),
5458 // right of context menu
5459 point(
5460 menu.bounds.right() + HOVER_POPOVER_GAP,
5461 y_for_horizontal_positioning,
5462 ),
5463 // top of context menu
5464 point(
5465 menu.bounds.left(),
5466 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
5467 ),
5468 // bottom of context menu
5469 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5470 ];
5471 possible_origins.into_iter().find(|&origin| {
5472 Bounds::new(origin, size(total_width, overall_height))
5473 .is_contained_within(hitbox)
5474 })
5475 });
5476 if let Some(origin) = origin_surrounding_menu {
5477 let mut current_y = origin.y;
5478 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5479 let size = popover.size;
5480 let popover_origin = point(origin.x, current_y);
5481
5482 window.defer_draw(popover.element, popover_origin, 2);
5483 if position != itertools::Position::Last {
5484 let origin = point(popover_origin.x, popover_origin.y + size.height);
5485 draw_occluder(size.width, origin, window, cx);
5486 }
5487
5488 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5489 }
5490 } else {
5491 // fallback to existing above/below cursor logic
5492 // this might overlap menu or overflow in rare case
5493 if can_place_above {
5494 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5495 } else {
5496 place_popovers_below(
5497 hovered_point,
5498 measured_hover_popovers,
5499 line_height,
5500 window,
5501 cx,
5502 );
5503 }
5504 }
5505 }
5506 }
5507
5508 fn layout_word_diff_highlights(
5509 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5510 row_infos: &[RowInfo],
5511 start_row: DisplayRow,
5512 snapshot: &EditorSnapshot,
5513 highlighted_ranges: &mut Vec<(Range<DisplayPoint>, Hsla)>,
5514 cx: &mut App,
5515 ) {
5516 let colors = cx.theme().colors();
5517
5518 let word_highlights = display_hunks
5519 .into_iter()
5520 .filter_map(|(hunk, _)| match hunk {
5521 DisplayDiffHunk::Unfolded {
5522 word_diffs, status, ..
5523 } => Some((word_diffs, status)),
5524 _ => None,
5525 })
5526 .filter(|(_, status)| status.is_modified())
5527 .flat_map(|(word_diffs, _)| word_diffs)
5528 .flat_map(|word_diff| {
5529 let display_ranges = snapshot
5530 .display_snapshot
5531 .isomorphic_display_point_ranges_for_buffer_range(
5532 word_diff.start..word_diff.end,
5533 );
5534
5535 display_ranges.into_iter().filter_map(|range| {
5536 let start_row_offset = range.start.row().0.saturating_sub(start_row.0) as usize;
5537
5538 let diff_status = row_infos
5539 .get(start_row_offset)
5540 .and_then(|row_info| row_info.diff_status)?;
5541
5542 let background_color = match diff_status.kind {
5543 DiffHunkStatusKind::Added => colors.version_control_word_added,
5544 DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,
5545 DiffHunkStatusKind::Modified => {
5546 debug_panic!("modified diff status for row info");
5547 return None;
5548 }
5549 };
5550
5551 Some((range, background_color))
5552 })
5553 });
5554
5555 highlighted_ranges.extend(word_highlights);
5556 }
5557
5558 fn layout_diff_hunk_controls(
5559 &self,
5560 row_range: Range<DisplayRow>,
5561 row_infos: &[RowInfo],
5562 text_hitbox: &Hitbox,
5563 newest_cursor_row: Option<DisplayRow>,
5564 line_height: Pixels,
5565 right_margin: Pixels,
5566 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5567 sticky_header_height: Pixels,
5568 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5569 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
5570 editor: Entity<Editor>,
5571 window: &mut Window,
5572 cx: &mut App,
5573 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
5574 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
5575 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
5576 let sticky_top = text_hitbox.bounds.top() + sticky_header_height;
5577
5578 let mut controls = vec![];
5579 let mut control_bounds = vec![];
5580
5581 let active_rows = [hovered_diff_hunk_row, newest_cursor_row];
5582
5583 for (hunk, _) in display_hunks {
5584 if let DisplayDiffHunk::Unfolded {
5585 display_row_range,
5586 multi_buffer_range,
5587 status,
5588 is_created_file,
5589 ..
5590 } = &hunk
5591 {
5592 if display_row_range.start >= row_range.end {
5593 // hunk is fully below the viewport
5594 continue;
5595 }
5596 if display_row_range.end <= row_range.start {
5597 // hunk is fully above the viewport
5598 continue;
5599 }
5600 let row_ix = display_row_range.start.0.saturating_sub(row_range.start.0);
5601 if row_infos[row_ix as usize].diff_status.is_none() {
5602 continue;
5603 }
5604 if highlighted_rows
5605 .get(&display_row_range.start)
5606 .and_then(|highlight| highlight.type_id)
5607 .is_some_and(|type_id| {
5608 [
5609 TypeId::of::<ConflictsOuter>(),
5610 TypeId::of::<ConflictsOursMarker>(),
5611 TypeId::of::<ConflictsOurs>(),
5612 TypeId::of::<ConflictsTheirs>(),
5613 TypeId::of::<ConflictsTheirsMarker>(),
5614 ]
5615 .contains(&type_id)
5616 })
5617 {
5618 continue;
5619 }
5620
5621 if active_rows
5622 .iter()
5623 .any(|row| row.is_some_and(|row| display_row_range.contains(&row)))
5624 {
5625 let hunk_start_y: Pixels = (display_row_range.start.as_f64()
5626 * ScrollPixelOffset::from(line_height)
5627 + ScrollPixelOffset::from(text_hitbox.bounds.top())
5628 - scroll_pixel_position.y)
5629 .into();
5630
5631 let y: Pixels = if hunk_start_y >= sticky_top {
5632 hunk_start_y
5633 } else {
5634 let hunk_end_y: Pixels = hunk_start_y
5635 + (display_row_range.len() as f64
5636 * ScrollPixelOffset::from(line_height))
5637 .into();
5638 let max_y = hunk_end_y - line_height;
5639 sticky_top.min(max_y)
5640 };
5641
5642 let mut element = render_diff_hunk_controls(
5643 display_row_range.start.0,
5644 status,
5645 multi_buffer_range.clone(),
5646 *is_created_file,
5647 line_height,
5648 &editor,
5649 window,
5650 cx,
5651 );
5652 let size =
5653 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5654
5655 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5656
5657 if x < text_hitbox.bounds.left() {
5658 continue;
5659 }
5660
5661 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5662 control_bounds.push((display_row_range.start, bounds));
5663
5664 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5665 element.prepaint(window, cx)
5666 });
5667 controls.push(element);
5668 }
5669 }
5670 }
5671
5672 (controls, control_bounds)
5673 }
5674
5675 fn layout_signature_help(
5676 &self,
5677 hitbox: &Hitbox,
5678 content_origin: gpui::Point<Pixels>,
5679 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5680 newest_selection_head: Option<DisplayPoint>,
5681 start_row: DisplayRow,
5682 line_layouts: &[LineWithInvisibles],
5683 line_height: Pixels,
5684 em_width: Pixels,
5685 context_menu_layout: Option<ContextMenuLayout>,
5686 window: &mut Window,
5687 cx: &mut App,
5688 ) {
5689 if !self.editor.focus_handle(cx).is_focused(window) {
5690 return;
5691 }
5692 let Some(newest_selection_head) = newest_selection_head else {
5693 return;
5694 };
5695
5696 let max_size = size(
5697 (120. * em_width) // Default size
5698 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5699 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5700 (16. * line_height) // Default size
5701 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5702 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5703 );
5704
5705 let maybe_element = self.editor.update(cx, |editor, cx| {
5706 if let Some(popover) = editor.signature_help_state.popover_mut() {
5707 let element = popover.render(max_size, window, cx);
5708 Some(element)
5709 } else {
5710 None
5711 }
5712 });
5713 let Some(mut element) = maybe_element else {
5714 return;
5715 };
5716
5717 let selection_row = newest_selection_head.row();
5718 let Some(cursor_row_layout) = (selection_row >= start_row)
5719 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5720 .flatten()
5721 else {
5722 return;
5723 };
5724
5725 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5726 - Pixels::from(scroll_pixel_position.x);
5727 let target_y = Pixels::from(
5728 selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
5729 );
5730 let target_point = content_origin + point(target_x, target_y);
5731
5732 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5733
5734 let (popover_bounds_above, popover_bounds_below) = {
5735 let horizontal_offset = (hitbox.top_right().x
5736 - POPOVER_RIGHT_OFFSET
5737 - (target_point.x + actual_size.width))
5738 .min(Pixels::ZERO);
5739 let initial_x = target_point.x + horizontal_offset;
5740 (
5741 Bounds::new(
5742 point(initial_x, target_point.y - actual_size.height),
5743 actual_size,
5744 ),
5745 Bounds::new(
5746 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5747 actual_size,
5748 ),
5749 )
5750 };
5751
5752 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5753 context_menu_layout
5754 .as_ref()
5755 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5756 };
5757
5758 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5759 && !intersects_menu(popover_bounds_above)
5760 {
5761 // try placing above cursor
5762 popover_bounds_above.origin
5763 } else if popover_bounds_below.is_contained_within(hitbox)
5764 && !intersects_menu(popover_bounds_below)
5765 {
5766 // try placing below cursor
5767 popover_bounds_below.origin
5768 } else {
5769 // try surrounding context menu if exists
5770 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5771 let y_for_horizontal_positioning = if menu.y_flipped {
5772 menu.bounds.bottom() - actual_size.height
5773 } else {
5774 menu.bounds.top()
5775 };
5776 let possible_origins = vec![
5777 // left of context menu
5778 point(
5779 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5780 y_for_horizontal_positioning,
5781 ),
5782 // right of context menu
5783 point(
5784 menu.bounds.right() + HOVER_POPOVER_GAP,
5785 y_for_horizontal_positioning,
5786 ),
5787 // top of context menu
5788 point(
5789 menu.bounds.left(),
5790 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5791 ),
5792 // bottom of context menu
5793 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5794 ];
5795 possible_origins
5796 .into_iter()
5797 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5798 });
5799 origin_surrounding_menu.unwrap_or_else(|| {
5800 // fallback to existing above/below cursor logic
5801 // this might overlap menu or overflow in rare case
5802 if popover_bounds_above.is_contained_within(hitbox) {
5803 popover_bounds_above.origin
5804 } else {
5805 popover_bounds_below.origin
5806 }
5807 })
5808 };
5809
5810 window.defer_draw(element, final_origin, 2);
5811 }
5812
5813 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5814 window.paint_layer(layout.hitbox.bounds, |window| {
5815 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5816 let gutter_bg = cx.theme().colors().editor_gutter_background;
5817 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5818 window.paint_quad(fill(
5819 layout.position_map.text_hitbox.bounds,
5820 self.style.background,
5821 ));
5822
5823 if matches!(
5824 layout.mode,
5825 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5826 ) {
5827 let show_active_line_background = match layout.mode {
5828 EditorMode::Full {
5829 show_active_line_background,
5830 ..
5831 } => show_active_line_background,
5832 EditorMode::Minimap { .. } => true,
5833 _ => false,
5834 };
5835 let mut active_rows = layout.active_rows.iter().peekable();
5836 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5837 let mut end_row = start_row.0;
5838 while active_rows
5839 .peek()
5840 .is_some_and(|(active_row, has_selection)| {
5841 active_row.0 == end_row + 1
5842 && has_selection.selection == contains_non_empty_selection.selection
5843 })
5844 {
5845 active_rows.next().unwrap();
5846 end_row += 1;
5847 }
5848
5849 if show_active_line_background && !contains_non_empty_selection.selection {
5850 let highlight_h_range =
5851 match layout.position_map.snapshot.current_line_highlight {
5852 CurrentLineHighlight::Gutter => Some(Range {
5853 start: layout.hitbox.left(),
5854 end: layout.gutter_hitbox.right(),
5855 }),
5856 CurrentLineHighlight::Line => Some(Range {
5857 start: layout.position_map.text_hitbox.bounds.left(),
5858 end: layout.position_map.text_hitbox.bounds.right(),
5859 }),
5860 CurrentLineHighlight::All => Some(Range {
5861 start: layout.hitbox.left(),
5862 end: layout.hitbox.right(),
5863 }),
5864 CurrentLineHighlight::None => None,
5865 };
5866 if let Some(range) = highlight_h_range {
5867 let active_line_bg = cx.theme().colors().editor_active_line_background;
5868 let bounds = Bounds {
5869 origin: point(
5870 range.start,
5871 layout.hitbox.origin.y
5872 + Pixels::from(
5873 (start_row.as_f64() - scroll_top)
5874 * ScrollPixelOffset::from(
5875 layout.position_map.line_height,
5876 ),
5877 ),
5878 ),
5879 size: size(
5880 range.end - range.start,
5881 layout.position_map.line_height
5882 * (end_row - start_row.0 + 1) as f32,
5883 ),
5884 };
5885 window.paint_quad(fill(bounds, active_line_bg));
5886 }
5887 }
5888 }
5889
5890 let mut paint_highlight = |highlight_row_start: DisplayRow,
5891 highlight_row_end: DisplayRow,
5892 highlight: crate::LineHighlight,
5893 edges| {
5894 let mut origin_x = layout.hitbox.left();
5895 let mut width = layout.hitbox.size.width;
5896 if !highlight.include_gutter {
5897 origin_x += layout.gutter_hitbox.size.width;
5898 width -= layout.gutter_hitbox.size.width;
5899 }
5900
5901 let origin = point(
5902 origin_x,
5903 layout.hitbox.origin.y
5904 + Pixels::from(
5905 (highlight_row_start.as_f64() - scroll_top)
5906 * ScrollPixelOffset::from(layout.position_map.line_height),
5907 ),
5908 );
5909 let size = size(
5910 width,
5911 layout.position_map.line_height
5912 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5913 );
5914 let mut quad = fill(Bounds { origin, size }, highlight.background);
5915 if let Some(border_color) = highlight.border {
5916 quad.border_color = border_color;
5917 quad.border_widths = edges
5918 }
5919 window.paint_quad(quad);
5920 };
5921
5922 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5923 None;
5924 for (&new_row, &new_background) in &layout.highlighted_rows {
5925 match &mut current_paint {
5926 &mut Some((current_background, ref mut current_range, mut edges)) => {
5927 let new_range_started = current_background != new_background
5928 || current_range.end.next_row() != new_row;
5929 if new_range_started {
5930 if current_range.end.next_row() == new_row {
5931 edges.bottom = px(0.);
5932 };
5933 paint_highlight(
5934 current_range.start,
5935 current_range.end,
5936 current_background,
5937 edges,
5938 );
5939 let edges = Edges {
5940 top: if current_range.end.next_row() != new_row {
5941 px(1.)
5942 } else {
5943 px(0.)
5944 },
5945 bottom: px(1.),
5946 ..Default::default()
5947 };
5948 current_paint = Some((new_background, new_row..new_row, edges));
5949 continue;
5950 } else {
5951 current_range.end = current_range.end.next_row();
5952 }
5953 }
5954 None => {
5955 let edges = Edges {
5956 top: px(1.),
5957 bottom: px(1.),
5958 ..Default::default()
5959 };
5960 current_paint = Some((new_background, new_row..new_row, edges))
5961 }
5962 };
5963 }
5964 if let Some((color, range, edges)) = current_paint {
5965 paint_highlight(range.start, range.end, color, edges);
5966 }
5967
5968 for (guide_x, active) in layout.wrap_guides.iter() {
5969 let color = if *active {
5970 cx.theme().colors().editor_active_wrap_guide
5971 } else {
5972 cx.theme().colors().editor_wrap_guide
5973 };
5974 window.paint_quad(fill(
5975 Bounds {
5976 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5977 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5978 },
5979 color,
5980 ));
5981 }
5982 }
5983 })
5984 }
5985
5986 fn paint_indent_guides(
5987 &mut self,
5988 layout: &mut EditorLayout,
5989 window: &mut Window,
5990 cx: &mut App,
5991 ) {
5992 let Some(indent_guides) = &layout.indent_guides else {
5993 return;
5994 };
5995
5996 let faded_color = |color: Hsla, alpha: f32| {
5997 let mut faded = color;
5998 faded.a = alpha;
5999 faded
6000 };
6001
6002 for indent_guide in indent_guides {
6003 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
6004 let settings = &indent_guide.settings;
6005
6006 // TODO fixed for now, expose them through themes later
6007 const INDENT_AWARE_ALPHA: f32 = 0.2;
6008 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
6009 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
6010 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
6011
6012 let line_color = match (settings.coloring, indent_guide.active) {
6013 (IndentGuideColoring::Disabled, _) => None,
6014 (IndentGuideColoring::Fixed, false) => {
6015 Some(cx.theme().colors().editor_indent_guide)
6016 }
6017 (IndentGuideColoring::Fixed, true) => {
6018 Some(cx.theme().colors().editor_indent_guide_active)
6019 }
6020 (IndentGuideColoring::IndentAware, false) => {
6021 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
6022 }
6023 (IndentGuideColoring::IndentAware, true) => {
6024 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
6025 }
6026 };
6027
6028 let background_color = match (settings.background_coloring, indent_guide.active) {
6029 (IndentGuideBackgroundColoring::Disabled, _) => None,
6030 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
6031 indent_accent_colors,
6032 INDENT_AWARE_BACKGROUND_ALPHA,
6033 )),
6034 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
6035 indent_accent_colors,
6036 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
6037 )),
6038 };
6039
6040 let requested_line_width = if indent_guide.active {
6041 settings.active_line_width
6042 } else {
6043 settings.line_width
6044 }
6045 .clamp(1, 10);
6046 let mut line_indicator_width = 0.;
6047 if let Some(color) = line_color {
6048 window.paint_quad(fill(
6049 Bounds {
6050 origin: indent_guide.origin,
6051 size: size(px(requested_line_width as f32), indent_guide.length),
6052 },
6053 color,
6054 ));
6055 line_indicator_width = requested_line_width as f32;
6056 }
6057
6058 if let Some(color) = background_color {
6059 let width = indent_guide.single_indent_width - px(line_indicator_width);
6060 window.paint_quad(fill(
6061 Bounds {
6062 origin: point(
6063 indent_guide.origin.x + px(line_indicator_width),
6064 indent_guide.origin.y,
6065 ),
6066 size: size(width, indent_guide.length),
6067 },
6068 color,
6069 ));
6070 }
6071 }
6072 }
6073
6074 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6075 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
6076
6077 let line_height = layout.position_map.line_height;
6078 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
6079
6080 for line_layout in layout.line_numbers.values() {
6081 for LineNumberSegment {
6082 shaped_line,
6083 hitbox,
6084 } in &line_layout.segments
6085 {
6086 let Some(hitbox) = hitbox else {
6087 continue;
6088 };
6089
6090 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
6091 let color = cx.theme().colors().editor_hover_line_number;
6092
6093 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
6094 line.paint(
6095 hitbox.origin,
6096 line_height,
6097 TextAlign::Left,
6098 None,
6099 window,
6100 cx,
6101 )
6102 .log_err()
6103 } else {
6104 shaped_line
6105 .paint(
6106 hitbox.origin,
6107 line_height,
6108 TextAlign::Left,
6109 None,
6110 window,
6111 cx,
6112 )
6113 .log_err()
6114 }) else {
6115 continue;
6116 };
6117
6118 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
6119 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
6120 if is_singleton {
6121 window.set_cursor_style(CursorStyle::IBeam, hitbox);
6122 } else {
6123 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
6124 }
6125 }
6126 }
6127 }
6128
6129 fn paint_gutter_diff_hunks(
6130 layout: &mut EditorLayout,
6131 split_side: Option<SplitSide>,
6132 window: &mut Window,
6133 cx: &mut App,
6134 ) {
6135 if layout.display_hunks.is_empty() {
6136 return;
6137 }
6138
6139 let line_height = layout.position_map.line_height;
6140 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6141 for (hunk, hitbox) in &layout.display_hunks {
6142 let hunk_to_paint = match hunk {
6143 DisplayDiffHunk::Folded { .. } => {
6144 let hunk_bounds = Self::diff_hunk_bounds(
6145 &layout.position_map.snapshot,
6146 line_height,
6147 layout.gutter_hitbox.bounds,
6148 hunk,
6149 );
6150 Some((
6151 hunk_bounds,
6152 cx.theme().colors().version_control_modified,
6153 Corners::all(px(0.)),
6154 DiffHunkStatus::modified_none(),
6155 ))
6156 }
6157 DisplayDiffHunk::Unfolded {
6158 status,
6159 display_row_range,
6160 ..
6161 } => hitbox.as_ref().map(|hunk_hitbox| {
6162 let color = match split_side {
6163 Some(SplitSide::Left) => cx.theme().colors().version_control_deleted,
6164 Some(SplitSide::Right) => cx.theme().colors().version_control_added,
6165 None => match status.kind {
6166 DiffHunkStatusKind::Added => {
6167 cx.theme().colors().version_control_added
6168 }
6169 DiffHunkStatusKind::Modified => {
6170 cx.theme().colors().version_control_modified
6171 }
6172 DiffHunkStatusKind::Deleted => {
6173 cx.theme().colors().version_control_deleted
6174 }
6175 },
6176 };
6177 match status.kind {
6178 DiffHunkStatusKind::Deleted if display_row_range.is_empty() => (
6179 Bounds::new(
6180 point(
6181 hunk_hitbox.origin.x - hunk_hitbox.size.width,
6182 hunk_hitbox.origin.y,
6183 ),
6184 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
6185 ),
6186 color,
6187 Corners::all(1. * line_height),
6188 *status,
6189 ),
6190 _ => (hunk_hitbox.bounds, color, Corners::all(px(0.)), *status),
6191 }
6192 }),
6193 };
6194
6195 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
6196 // Flatten the background color with the editor color to prevent
6197 // elements below transparent hunks from showing through
6198 let flattened_background_color = cx
6199 .theme()
6200 .colors()
6201 .editor_background
6202 .blend(background_color);
6203
6204 if !Self::diff_hunk_hollow(status, cx) {
6205 window.paint_quad(quad(
6206 hunk_bounds,
6207 corner_radii,
6208 flattened_background_color,
6209 Edges::default(),
6210 transparent_black(),
6211 BorderStyle::default(),
6212 ));
6213 } else {
6214 let flattened_unstaged_background_color = cx
6215 .theme()
6216 .colors()
6217 .editor_background
6218 .blend(background_color.opacity(0.3));
6219
6220 window.paint_quad(quad(
6221 hunk_bounds,
6222 corner_radii,
6223 flattened_unstaged_background_color,
6224 Edges::all(px(1.0)),
6225 flattened_background_color,
6226 BorderStyle::Solid,
6227 ));
6228 }
6229 }
6230 }
6231 });
6232 }
6233
6234 fn gutter_strip_width(line_height: Pixels) -> Pixels {
6235 (0.275 * line_height).floor()
6236 }
6237
6238 fn diff_hunk_bounds(
6239 snapshot: &EditorSnapshot,
6240 line_height: Pixels,
6241 gutter_bounds: Bounds<Pixels>,
6242 hunk: &DisplayDiffHunk,
6243 ) -> Bounds<Pixels> {
6244 let scroll_position = snapshot.scroll_position();
6245 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
6246 let gutter_strip_width = Self::gutter_strip_width(line_height);
6247
6248 match hunk {
6249 DisplayDiffHunk::Folded { display_row, .. } => {
6250 let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
6251 - scroll_top)
6252 .into();
6253 let end_y = start_y + line_height;
6254 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6255 let highlight_size = size(gutter_strip_width, end_y - start_y);
6256 Bounds::new(highlight_origin, highlight_size)
6257 }
6258 DisplayDiffHunk::Unfolded {
6259 display_row_range,
6260 status,
6261 ..
6262 } => {
6263 if status.is_deleted() && display_row_range.is_empty() {
6264 let row = display_row_range.start;
6265
6266 let offset = ScrollPixelOffset::from(line_height / 2.);
6267 let start_y =
6268 (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
6269 .into();
6270 let end_y = start_y + line_height;
6271
6272 let width = (0.35 * line_height).floor();
6273 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6274 let highlight_size = size(width, end_y - start_y);
6275 Bounds::new(highlight_origin, highlight_size)
6276 } else {
6277 let start_row = display_row_range.start;
6278 let end_row = display_row_range.end;
6279 // If we're in a multibuffer, row range span might include an
6280 // excerpt header, so if we were to draw the marker straight away,
6281 // the hunk might include the rows of that header.
6282 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
6283 // Instead, we simply check whether the range we're dealing with includes
6284 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
6285 let end_row_in_current_excerpt = snapshot
6286 .blocks_in_range(start_row..end_row)
6287 .find_map(|(start_row, block)| {
6288 if matches!(
6289 block,
6290 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
6291 ) {
6292 Some(start_row)
6293 } else {
6294 None
6295 }
6296 })
6297 .unwrap_or(end_row);
6298
6299 let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
6300 - scroll_top)
6301 .into();
6302 let end_y = Pixels::from(
6303 end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
6304 - scroll_top,
6305 );
6306
6307 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6308 let highlight_size = size(gutter_strip_width, end_y - start_y);
6309 Bounds::new(highlight_origin, highlight_size)
6310 }
6311 }
6312 }
6313 }
6314
6315 fn paint_gutter_indicators(
6316 &self,
6317 layout: &mut EditorLayout,
6318 window: &mut Window,
6319 cx: &mut App,
6320 ) {
6321 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6322 window.with_element_namespace("crease_toggles", |window| {
6323 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
6324 crease_toggle.paint(window, cx);
6325 }
6326 });
6327
6328 window.with_element_namespace("expand_toggles", |window| {
6329 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
6330 expand_toggle.paint(window, cx);
6331 }
6332 });
6333
6334 for breakpoint in layout.breakpoints.iter_mut() {
6335 breakpoint.paint(window, cx);
6336 }
6337
6338 for test_indicator in layout.test_indicators.iter_mut() {
6339 test_indicator.paint(window, cx);
6340 }
6341
6342 if let Some(diff_review_button) = layout.diff_review_button.as_mut() {
6343 diff_review_button.paint(window, cx);
6344 }
6345 });
6346 }
6347
6348 fn paint_gutter_highlights(
6349 &self,
6350 layout: &mut EditorLayout,
6351 window: &mut Window,
6352 cx: &mut App,
6353 ) {
6354 for (_, hunk_hitbox) in &layout.display_hunks {
6355 if let Some(hunk_hitbox) = hunk_hitbox
6356 && !self
6357 .editor
6358 .read(cx)
6359 .buffer()
6360 .read(cx)
6361 .all_diff_hunks_expanded()
6362 {
6363 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
6364 }
6365 }
6366
6367 let show_git_gutter = layout
6368 .position_map
6369 .snapshot
6370 .show_git_diff_gutter
6371 .unwrap_or_else(|| {
6372 matches!(
6373 ProjectSettings::get_global(cx).git.git_gutter,
6374 GitGutterSetting::TrackedFiles
6375 )
6376 });
6377 if show_git_gutter {
6378 Self::paint_gutter_diff_hunks(layout, self.split_side, window, cx)
6379 }
6380
6381 let highlight_width = 0.275 * layout.position_map.line_height;
6382 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
6383 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6384 for (range, color) in &layout.highlighted_gutter_ranges {
6385 let start_row = if range.start.row() < layout.visible_display_row_range.start {
6386 layout.visible_display_row_range.start - DisplayRow(1)
6387 } else {
6388 range.start.row()
6389 };
6390 let end_row = if range.end.row() > layout.visible_display_row_range.end {
6391 layout.visible_display_row_range.end + DisplayRow(1)
6392 } else {
6393 range.end.row()
6394 };
6395
6396 let start_y = layout.gutter_hitbox.top()
6397 + Pixels::from(
6398 start_row.0 as f64
6399 * ScrollPixelOffset::from(layout.position_map.line_height)
6400 - layout.position_map.scroll_pixel_position.y,
6401 );
6402 let end_y = layout.gutter_hitbox.top()
6403 + Pixels::from(
6404 (end_row.0 + 1) as f64
6405 * ScrollPixelOffset::from(layout.position_map.line_height)
6406 - layout.position_map.scroll_pixel_position.y,
6407 );
6408 let bounds = Bounds::from_corners(
6409 point(layout.gutter_hitbox.left(), start_y),
6410 point(layout.gutter_hitbox.left() + highlight_width, end_y),
6411 );
6412 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
6413 }
6414 });
6415 }
6416
6417 fn paint_blamed_display_rows(
6418 &self,
6419 layout: &mut EditorLayout,
6420 window: &mut Window,
6421 cx: &mut App,
6422 ) {
6423 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
6424 return;
6425 };
6426
6427 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6428 for mut blame_element in blamed_display_rows.into_iter() {
6429 blame_element.paint(window, cx);
6430 }
6431 })
6432 }
6433
6434 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6435 window.with_content_mask(
6436 Some(ContentMask {
6437 bounds: layout.position_map.text_hitbox.bounds,
6438 }),
6439 |window| {
6440 let editor = self.editor.read(cx);
6441 if editor.mouse_cursor_hidden {
6442 window.set_window_cursor_style(CursorStyle::None);
6443 } else if let SelectionDragState::ReadyToDrag {
6444 mouse_down_time, ..
6445 } = &editor.selection_drag_state
6446 {
6447 let drag_and_drop_delay = Duration::from_millis(
6448 EditorSettings::get_global(cx)
6449 .drag_and_drop_selection
6450 .delay
6451 .0,
6452 );
6453 if mouse_down_time.elapsed() >= drag_and_drop_delay {
6454 window.set_cursor_style(
6455 CursorStyle::DragCopy,
6456 &layout.position_map.text_hitbox,
6457 );
6458 }
6459 } else if matches!(
6460 editor.selection_drag_state,
6461 SelectionDragState::Dragging { .. }
6462 ) {
6463 window
6464 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
6465 } else if editor
6466 .hovered_link_state
6467 .as_ref()
6468 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
6469 {
6470 window.set_cursor_style(
6471 CursorStyle::PointingHand,
6472 &layout.position_map.text_hitbox,
6473 );
6474 } else {
6475 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
6476 };
6477
6478 self.paint_lines_background(layout, window, cx);
6479 let invisible_display_ranges = self.paint_highlights(layout, window, cx);
6480 self.paint_document_colors(layout, window);
6481 self.paint_lines(&invisible_display_ranges, layout, window, cx);
6482 self.paint_redactions(layout, window);
6483 self.paint_cursors(layout, window, cx);
6484 self.paint_inline_diagnostics(layout, window, cx);
6485 self.paint_inline_blame(layout, window, cx);
6486 self.paint_inline_code_actions(layout, window, cx);
6487 self.paint_diff_hunk_controls(layout, window, cx);
6488 window.with_element_namespace("crease_trailers", |window| {
6489 for trailer in layout.crease_trailers.iter_mut().flatten() {
6490 trailer.element.paint(window, cx);
6491 }
6492 });
6493 },
6494 )
6495 }
6496
6497 fn paint_highlights(
6498 &mut self,
6499 layout: &mut EditorLayout,
6500 window: &mut Window,
6501 cx: &mut App,
6502 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6503 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6504 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6505 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6506 for (range, color) in &layout.highlighted_ranges {
6507 self.paint_highlighted_range(
6508 range.clone(),
6509 true,
6510 *color,
6511 Pixels::ZERO,
6512 line_end_overshoot,
6513 layout,
6514 window,
6515 );
6516 }
6517
6518 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
6519 0.15 * layout.position_map.line_height
6520 } else {
6521 Pixels::ZERO
6522 };
6523
6524 for (player_color, selections) in &layout.selections {
6525 for selection in selections.iter() {
6526 self.paint_highlighted_range(
6527 selection.range.clone(),
6528 true,
6529 player_color.selection,
6530 corner_radius,
6531 corner_radius * 2.,
6532 layout,
6533 window,
6534 );
6535
6536 if selection.is_local && !selection.range.is_empty() {
6537 invisible_display_ranges.push(selection.range.clone());
6538 }
6539 }
6540 }
6541 invisible_display_ranges
6542 })
6543 }
6544
6545 fn paint_lines(
6546 &mut self,
6547 invisible_display_ranges: &[Range<DisplayPoint>],
6548 layout: &mut EditorLayout,
6549 window: &mut Window,
6550 cx: &mut App,
6551 ) {
6552 let whitespace_setting = self
6553 .editor
6554 .read(cx)
6555 .buffer
6556 .read(cx)
6557 .language_settings(cx)
6558 .show_whitespaces;
6559
6560 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6561 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6562 line_with_invisibles.draw(
6563 layout,
6564 row,
6565 layout.content_origin,
6566 whitespace_setting,
6567 invisible_display_ranges,
6568 window,
6569 cx,
6570 )
6571 }
6572
6573 for line_element in &mut layout.line_elements {
6574 line_element.paint(window, cx);
6575 }
6576 }
6577
6578 fn paint_sticky_headers(
6579 &mut self,
6580 layout: &mut EditorLayout,
6581 window: &mut Window,
6582 cx: &mut App,
6583 ) {
6584 let Some(mut sticky_headers) = layout.sticky_headers.take() else {
6585 return;
6586 };
6587
6588 if sticky_headers.lines.is_empty() {
6589 layout.sticky_headers = Some(sticky_headers);
6590 return;
6591 }
6592
6593 let whitespace_setting = self
6594 .editor
6595 .read(cx)
6596 .buffer
6597 .read(cx)
6598 .language_settings(cx)
6599 .show_whitespaces;
6600 sticky_headers.paint(layout, whitespace_setting, window, cx);
6601
6602 let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
6603 .lines
6604 .iter()
6605 .map(|line| line.hitbox.clone())
6606 .collect();
6607 let hovered_hitbox = sticky_header_hitboxes
6608 .iter()
6609 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6610
6611 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
6612 if !phase.bubble() {
6613 return;
6614 }
6615
6616 let current_hover = sticky_header_hitboxes
6617 .iter()
6618 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6619 if hovered_hitbox != current_hover {
6620 window.refresh();
6621 }
6622 });
6623
6624 for (line_index, line) in sticky_headers.lines.iter().enumerate() {
6625 let editor = self.editor.clone();
6626 let hitbox = line.hitbox.clone();
6627 let target_anchor = line.target_anchor;
6628 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
6629 if !phase.bubble() {
6630 return;
6631 }
6632
6633 if event.button == MouseButton::Left && hitbox.is_hovered(window) {
6634 editor.update(cx, |editor, cx| {
6635 editor.change_selections(
6636 SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
6637 window,
6638 cx,
6639 |selections| selections.select_ranges([target_anchor..target_anchor]),
6640 );
6641 cx.stop_propagation();
6642 });
6643 }
6644 });
6645 }
6646
6647 let text_bounds = layout.position_map.text_hitbox.bounds;
6648 let border_top = text_bounds.top()
6649 + sticky_headers.lines.last().unwrap().offset
6650 + layout.position_map.line_height;
6651 let separator_height = px(1.);
6652 let border_bounds = Bounds::from_corners(
6653 point(layout.gutter_hitbox.bounds.left(), border_top),
6654 point(text_bounds.right(), border_top + separator_height),
6655 );
6656 window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
6657
6658 layout.sticky_headers = Some(sticky_headers);
6659 }
6660
6661 fn paint_lines_background(
6662 &mut self,
6663 layout: &mut EditorLayout,
6664 window: &mut Window,
6665 cx: &mut App,
6666 ) {
6667 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6668 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6669 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6670 }
6671 }
6672
6673 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6674 if layout.redacted_ranges.is_empty() {
6675 return;
6676 }
6677
6678 let line_end_overshoot = layout.line_end_overshoot();
6679
6680 // A softer than perfect black
6681 let redaction_color = gpui::rgb(0x0e1111);
6682
6683 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6684 for range in layout.redacted_ranges.iter() {
6685 self.paint_highlighted_range(
6686 range.clone(),
6687 true,
6688 redaction_color.into(),
6689 Pixels::ZERO,
6690 line_end_overshoot,
6691 layout,
6692 window,
6693 );
6694 }
6695 });
6696 }
6697
6698 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6699 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6700 return;
6701 };
6702 if image_colors.is_empty()
6703 || colors_render_mode == &DocumentColorsRenderMode::None
6704 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6705 {
6706 return;
6707 }
6708
6709 let line_end_overshoot = layout.line_end_overshoot();
6710
6711 for (range, color) in image_colors {
6712 match colors_render_mode {
6713 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6714 DocumentColorsRenderMode::Background => {
6715 self.paint_highlighted_range(
6716 range.clone(),
6717 true,
6718 *color,
6719 Pixels::ZERO,
6720 line_end_overshoot,
6721 layout,
6722 window,
6723 );
6724 }
6725 DocumentColorsRenderMode::Border => {
6726 self.paint_highlighted_range(
6727 range.clone(),
6728 false,
6729 *color,
6730 Pixels::ZERO,
6731 line_end_overshoot,
6732 layout,
6733 window,
6734 );
6735 }
6736 }
6737 }
6738 }
6739
6740 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6741 for cursor in &mut layout.visible_cursors {
6742 cursor.paint(layout.content_origin, window, cx);
6743 }
6744 }
6745
6746 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6747 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6748 return;
6749 };
6750 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6751
6752 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6753 let hitbox = &scrollbar_layout.hitbox;
6754 if scrollbars_layout.visible {
6755 let scrollbar_edges = match axis {
6756 ScrollbarAxis::Horizontal => Edges {
6757 top: Pixels::ZERO,
6758 right: Pixels::ZERO,
6759 bottom: Pixels::ZERO,
6760 left: Pixels::ZERO,
6761 },
6762 ScrollbarAxis::Vertical => Edges {
6763 top: Pixels::ZERO,
6764 right: Pixels::ZERO,
6765 bottom: Pixels::ZERO,
6766 left: ScrollbarLayout::BORDER_WIDTH,
6767 },
6768 };
6769
6770 window.paint_layer(hitbox.bounds, |window| {
6771 window.paint_quad(quad(
6772 hitbox.bounds,
6773 Corners::default(),
6774 cx.theme().colors().scrollbar_track_background,
6775 scrollbar_edges,
6776 cx.theme().colors().scrollbar_track_border,
6777 BorderStyle::Solid,
6778 ));
6779
6780 if axis == ScrollbarAxis::Vertical {
6781 let fast_markers =
6782 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6783 // Refresh slow scrollbar markers in the background. Below, we
6784 // paint whatever markers have already been computed.
6785 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6786
6787 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6788 for marker in markers.iter().chain(&fast_markers) {
6789 let mut marker = marker.clone();
6790 marker.bounds.origin += hitbox.origin;
6791 window.paint_quad(marker);
6792 }
6793 }
6794
6795 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6796 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6797 ScrollbarThumbState::Dragging => {
6798 cx.theme().colors().scrollbar_thumb_active_background
6799 }
6800 ScrollbarThumbState::Hovered => {
6801 cx.theme().colors().scrollbar_thumb_hover_background
6802 }
6803 ScrollbarThumbState::Idle => {
6804 cx.theme().colors().scrollbar_thumb_background
6805 }
6806 };
6807 window.paint_quad(quad(
6808 thumb_bounds,
6809 Corners::default(),
6810 scrollbar_thumb_color,
6811 scrollbar_edges,
6812 cx.theme().colors().scrollbar_thumb_border,
6813 BorderStyle::Solid,
6814 ));
6815
6816 if any_scrollbar_dragged {
6817 window.set_window_cursor_style(CursorStyle::Arrow);
6818 } else {
6819 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6820 }
6821 }
6822 })
6823 }
6824 }
6825
6826 window.on_mouse_event({
6827 let editor = self.editor.clone();
6828 let scrollbars_layout = scrollbars_layout.clone();
6829
6830 let mut mouse_position = window.mouse_position();
6831 move |event: &MouseMoveEvent, phase, window, cx| {
6832 if phase == DispatchPhase::Capture {
6833 return;
6834 }
6835
6836 editor.update(cx, |editor, cx| {
6837 if let Some((scrollbar_layout, axis)) = event
6838 .pressed_button
6839 .filter(|button| *button == MouseButton::Left)
6840 .and(editor.scroll_manager.dragging_scrollbar_axis())
6841 .and_then(|axis| {
6842 scrollbars_layout
6843 .iter_scrollbars()
6844 .find(|(_, a)| *a == axis)
6845 })
6846 {
6847 let ScrollbarLayout {
6848 hitbox,
6849 text_unit_size,
6850 ..
6851 } = scrollbar_layout;
6852
6853 let old_position = mouse_position.along(axis);
6854 let new_position = event.position.along(axis);
6855 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6856 .contains(&old_position)
6857 {
6858 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6859 (p + ScrollOffset::from(
6860 (new_position - old_position) / *text_unit_size,
6861 ))
6862 .max(0.)
6863 });
6864 editor.set_scroll_position(position, window, cx);
6865 }
6866
6867 editor.scroll_manager.show_scrollbars(window, cx);
6868 cx.stop_propagation();
6869 } else if let Some((layout, axis)) = scrollbars_layout
6870 .get_hovered_axis(window)
6871 .filter(|_| !event.dragging())
6872 {
6873 if layout.thumb_hovered(&event.position) {
6874 editor
6875 .scroll_manager
6876 .set_hovered_scroll_thumb_axis(axis, cx);
6877 } else {
6878 editor.scroll_manager.reset_scrollbar_state(cx);
6879 }
6880
6881 editor.scroll_manager.show_scrollbars(window, cx);
6882 } else {
6883 editor.scroll_manager.reset_scrollbar_state(cx);
6884 }
6885
6886 mouse_position = event.position;
6887 })
6888 }
6889 });
6890
6891 if any_scrollbar_dragged {
6892 window.on_mouse_event({
6893 let editor = self.editor.clone();
6894 move |_: &MouseUpEvent, phase, window, cx| {
6895 if phase == DispatchPhase::Capture {
6896 return;
6897 }
6898
6899 editor.update(cx, |editor, cx| {
6900 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6901 editor
6902 .scroll_manager
6903 .set_hovered_scroll_thumb_axis(axis, cx);
6904 } else {
6905 editor.scroll_manager.reset_scrollbar_state(cx);
6906 }
6907 cx.stop_propagation();
6908 });
6909 }
6910 });
6911 } else {
6912 window.on_mouse_event({
6913 let editor = self.editor.clone();
6914
6915 move |event: &MouseDownEvent, phase, window, cx| {
6916 if phase == DispatchPhase::Capture {
6917 return;
6918 }
6919 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6920 else {
6921 return;
6922 };
6923
6924 let ScrollbarLayout {
6925 hitbox,
6926 visible_range,
6927 text_unit_size,
6928 thumb_bounds,
6929 ..
6930 } = scrollbar_layout;
6931
6932 let Some(thumb_bounds) = thumb_bounds else {
6933 return;
6934 };
6935
6936 editor.update(cx, |editor, cx| {
6937 editor
6938 .scroll_manager
6939 .set_dragged_scroll_thumb_axis(axis, cx);
6940
6941 let event_position = event.position.along(axis);
6942
6943 if event_position < thumb_bounds.origin.along(axis)
6944 || thumb_bounds.bottom_right().along(axis) < event_position
6945 {
6946 let center_position = ((event_position - hitbox.origin.along(axis))
6947 / *text_unit_size)
6948 .round() as u32;
6949 let start_position = center_position.saturating_sub(
6950 (visible_range.end - visible_range.start) as u32 / 2,
6951 );
6952
6953 let position = editor
6954 .scroll_position(cx)
6955 .apply_along(axis, |_| start_position as ScrollOffset);
6956
6957 editor.set_scroll_position(position, window, cx);
6958 } else {
6959 editor.scroll_manager.show_scrollbars(window, cx);
6960 }
6961
6962 cx.stop_propagation();
6963 });
6964 }
6965 });
6966 }
6967 }
6968
6969 fn collect_fast_scrollbar_markers(
6970 &self,
6971 layout: &EditorLayout,
6972 scrollbar_layout: &ScrollbarLayout,
6973 cx: &mut App,
6974 ) -> Vec<PaintQuad> {
6975 const LIMIT: usize = 100;
6976 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6977 return vec![];
6978 }
6979 let cursor_ranges = layout
6980 .cursors
6981 .iter()
6982 .map(|(point, color)| ColoredRange {
6983 start: point.row(),
6984 end: point.row(),
6985 color: *color,
6986 })
6987 .collect_vec();
6988 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6989 }
6990
6991 fn refresh_slow_scrollbar_markers(
6992 &self,
6993 layout: &EditorLayout,
6994 scrollbar_layout: &ScrollbarLayout,
6995 window: &mut Window,
6996 cx: &mut App,
6997 ) {
6998 self.editor.update(cx, |editor, cx| {
6999 if editor.buffer_kind(cx) != ItemBufferKind::Singleton
7000 || !editor
7001 .scrollbar_marker_state
7002 .should_refresh(scrollbar_layout.hitbox.size)
7003 {
7004 return;
7005 }
7006
7007 let scrollbar_layout = scrollbar_layout.clone();
7008 let background_highlights = editor.background_highlights.clone();
7009 let snapshot = layout.position_map.snapshot.clone();
7010 let theme = cx.theme().clone();
7011 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
7012
7013 editor.scrollbar_marker_state.dirty = false;
7014 editor.scrollbar_marker_state.pending_refresh =
7015 Some(cx.spawn_in(window, async move |editor, cx| {
7016 let scrollbar_size = scrollbar_layout.hitbox.size;
7017 let scrollbar_markers = cx
7018 .background_spawn(async move {
7019 let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
7020 let mut marker_quads = Vec::new();
7021 if scrollbar_settings.git_diff {
7022 let marker_row_ranges =
7023 snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
7024 let start_display_row =
7025 MultiBufferPoint::new(hunk.row_range.start.0, 0)
7026 .to_display_point(&snapshot.display_snapshot)
7027 .row();
7028 let mut end_display_row =
7029 MultiBufferPoint::new(hunk.row_range.end.0, 0)
7030 .to_display_point(&snapshot.display_snapshot)
7031 .row();
7032 if end_display_row != start_display_row {
7033 end_display_row.0 -= 1;
7034 }
7035 let color = match &hunk.status().kind {
7036 DiffHunkStatusKind::Added => {
7037 theme.colors().version_control_added
7038 }
7039 DiffHunkStatusKind::Modified => {
7040 theme.colors().version_control_modified
7041 }
7042 DiffHunkStatusKind::Deleted => {
7043 theme.colors().version_control_deleted
7044 }
7045 };
7046 ColoredRange {
7047 start: start_display_row,
7048 end: end_display_row,
7049 color,
7050 }
7051 });
7052
7053 marker_quads.extend(
7054 scrollbar_layout
7055 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
7056 );
7057 }
7058
7059 for (background_highlight_id, (_, background_ranges)) in
7060 background_highlights.iter()
7061 {
7062 let is_search_highlights = *background_highlight_id
7063 == HighlightKey::BufferSearchHighlights;
7064 let is_text_highlights =
7065 *background_highlight_id == HighlightKey::SelectedTextHighlight;
7066 let is_symbol_occurrences = *background_highlight_id
7067 == HighlightKey::DocumentHighlightRead
7068 || *background_highlight_id
7069 == HighlightKey::DocumentHighlightWrite;
7070 if (is_search_highlights && scrollbar_settings.search_results)
7071 || (is_text_highlights && scrollbar_settings.selected_text)
7072 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
7073 {
7074 let mut color = theme.status().info;
7075 if is_symbol_occurrences {
7076 color.fade_out(0.5);
7077 }
7078 let marker_row_ranges = background_ranges.iter().map(|range| {
7079 let display_start = range
7080 .start
7081 .to_display_point(&snapshot.display_snapshot);
7082 let display_end =
7083 range.end.to_display_point(&snapshot.display_snapshot);
7084 ColoredRange {
7085 start: display_start.row(),
7086 end: display_end.row(),
7087 color,
7088 }
7089 });
7090 marker_quads.extend(
7091 scrollbar_layout
7092 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
7093 );
7094 }
7095 }
7096
7097 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
7098 let diagnostics = snapshot
7099 .buffer_snapshot()
7100 .diagnostics_in_range::<Point>(Point::zero()..max_point)
7101 // Don't show diagnostics the user doesn't care about
7102 .filter(|diagnostic| {
7103 match (
7104 scrollbar_settings.diagnostics,
7105 diagnostic.diagnostic.severity,
7106 ) {
7107 (ScrollbarDiagnostics::All, _) => true,
7108 (
7109 ScrollbarDiagnostics::Error,
7110 lsp::DiagnosticSeverity::ERROR,
7111 ) => true,
7112 (
7113 ScrollbarDiagnostics::Warning,
7114 lsp::DiagnosticSeverity::ERROR
7115 | lsp::DiagnosticSeverity::WARNING,
7116 ) => true,
7117 (
7118 ScrollbarDiagnostics::Information,
7119 lsp::DiagnosticSeverity::ERROR
7120 | lsp::DiagnosticSeverity::WARNING
7121 | lsp::DiagnosticSeverity::INFORMATION,
7122 ) => true,
7123 (_, _) => false,
7124 }
7125 })
7126 // We want to sort by severity, in order to paint the most severe diagnostics last.
7127 .sorted_by_key(|diagnostic| {
7128 std::cmp::Reverse(diagnostic.diagnostic.severity)
7129 });
7130
7131 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
7132 let start_display = diagnostic
7133 .range
7134 .start
7135 .to_display_point(&snapshot.display_snapshot);
7136 let end_display = diagnostic
7137 .range
7138 .end
7139 .to_display_point(&snapshot.display_snapshot);
7140 let color = match diagnostic.diagnostic.severity {
7141 lsp::DiagnosticSeverity::ERROR => theme.status().error,
7142 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
7143 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
7144 _ => theme.status().hint,
7145 };
7146 ColoredRange {
7147 start: start_display.row(),
7148 end: end_display.row(),
7149 color,
7150 }
7151 });
7152 marker_quads.extend(
7153 scrollbar_layout
7154 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
7155 );
7156 }
7157
7158 Arc::from(marker_quads)
7159 })
7160 .await;
7161
7162 editor.update(cx, |editor, cx| {
7163 editor.scrollbar_marker_state.markers = scrollbar_markers;
7164 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
7165 editor.scrollbar_marker_state.pending_refresh = None;
7166 cx.notify();
7167 })?;
7168
7169 Ok(())
7170 }));
7171 });
7172 }
7173
7174 fn paint_highlighted_range(
7175 &self,
7176 range: Range<DisplayPoint>,
7177 fill: bool,
7178 color: Hsla,
7179 corner_radius: Pixels,
7180 line_end_overshoot: Pixels,
7181 layout: &EditorLayout,
7182 window: &mut Window,
7183 ) {
7184 let start_row = layout.visible_display_row_range.start;
7185 let end_row = layout.visible_display_row_range.end;
7186 if range.start != range.end {
7187 let row_range = if range.end.column() == 0 {
7188 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
7189 } else {
7190 cmp::max(range.start.row(), start_row)
7191 ..cmp::min(range.end.row().next_row(), end_row)
7192 };
7193
7194 let highlighted_range = HighlightedRange {
7195 color,
7196 line_height: layout.position_map.line_height,
7197 corner_radius,
7198 start_y: layout.content_origin.y
7199 + Pixels::from(
7200 (row_range.start.as_f64() - layout.position_map.scroll_position.y)
7201 * ScrollOffset::from(layout.position_map.line_height),
7202 ),
7203 lines: row_range
7204 .iter_rows()
7205 .map(|row| {
7206 let line_layout =
7207 &layout.position_map.line_layouts[row.minus(start_row) as usize];
7208 let alignment_offset =
7209 line_layout.alignment_offset(layout.text_align, layout.content_width);
7210 HighlightedRangeLine {
7211 start_x: if row == range.start.row() {
7212 layout.content_origin.x
7213 + Pixels::from(
7214 ScrollPixelOffset::from(
7215 line_layout.x_for_index(range.start.column() as usize)
7216 + alignment_offset,
7217 ) - layout.position_map.scroll_pixel_position.x,
7218 )
7219 } else {
7220 layout.content_origin.x + alignment_offset
7221 - Pixels::from(layout.position_map.scroll_pixel_position.x)
7222 },
7223 end_x: if row == range.end.row() {
7224 layout.content_origin.x
7225 + Pixels::from(
7226 ScrollPixelOffset::from(
7227 line_layout.x_for_index(range.end.column() as usize)
7228 + alignment_offset,
7229 ) - layout.position_map.scroll_pixel_position.x,
7230 )
7231 } else {
7232 Pixels::from(
7233 ScrollPixelOffset::from(
7234 layout.content_origin.x
7235 + line_layout.width
7236 + alignment_offset
7237 + line_end_overshoot,
7238 ) - layout.position_map.scroll_pixel_position.x,
7239 )
7240 },
7241 }
7242 })
7243 .collect(),
7244 };
7245
7246 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
7247 }
7248 }
7249
7250 fn paint_inline_diagnostics(
7251 &mut self,
7252 layout: &mut EditorLayout,
7253 window: &mut Window,
7254 cx: &mut App,
7255 ) {
7256 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
7257 inline_diagnostic.1.paint(window, cx);
7258 }
7259 }
7260
7261 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7262 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
7263 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
7264 blame_layout.element.paint(window, cx);
7265 })
7266 }
7267 }
7268
7269 fn paint_inline_code_actions(
7270 &mut self,
7271 layout: &mut EditorLayout,
7272 window: &mut Window,
7273 cx: &mut App,
7274 ) {
7275 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
7276 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
7277 inline_code_actions.paint(window, cx);
7278 })
7279 }
7280 }
7281
7282 fn paint_diff_hunk_controls(
7283 &mut self,
7284 layout: &mut EditorLayout,
7285 window: &mut Window,
7286 cx: &mut App,
7287 ) {
7288 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
7289 diff_hunk_control.paint(window, cx);
7290 }
7291 }
7292
7293 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7294 if let Some(mut layout) = layout.minimap.take() {
7295 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
7296 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
7297
7298 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
7299 window.with_element_namespace("minimap", |window| {
7300 layout.minimap.paint(window, cx);
7301 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
7302 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
7303 ScrollbarThumbState::Idle => {
7304 cx.theme().colors().minimap_thumb_background
7305 }
7306 ScrollbarThumbState::Hovered => {
7307 cx.theme().colors().minimap_thumb_hover_background
7308 }
7309 ScrollbarThumbState::Dragging => {
7310 cx.theme().colors().minimap_thumb_active_background
7311 }
7312 };
7313 let minimap_thumb_border = match layout.thumb_border_style {
7314 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
7315 MinimapThumbBorder::LeftOnly => Edges {
7316 left: ScrollbarLayout::BORDER_WIDTH,
7317 ..Default::default()
7318 },
7319 MinimapThumbBorder::LeftOpen => Edges {
7320 right: ScrollbarLayout::BORDER_WIDTH,
7321 top: ScrollbarLayout::BORDER_WIDTH,
7322 bottom: ScrollbarLayout::BORDER_WIDTH,
7323 ..Default::default()
7324 },
7325 MinimapThumbBorder::RightOpen => Edges {
7326 left: ScrollbarLayout::BORDER_WIDTH,
7327 top: ScrollbarLayout::BORDER_WIDTH,
7328 bottom: ScrollbarLayout::BORDER_WIDTH,
7329 ..Default::default()
7330 },
7331 MinimapThumbBorder::None => Default::default(),
7332 };
7333
7334 window.paint_layer(minimap_hitbox.bounds, |window| {
7335 window.paint_quad(quad(
7336 thumb_bounds,
7337 Corners::default(),
7338 minimap_thumb_color,
7339 minimap_thumb_border,
7340 cx.theme().colors().minimap_thumb_border,
7341 BorderStyle::Solid,
7342 ));
7343 });
7344 }
7345 });
7346 });
7347
7348 if dragging_minimap {
7349 window.set_window_cursor_style(CursorStyle::Arrow);
7350 } else {
7351 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
7352 }
7353
7354 let minimap_axis = ScrollbarAxis::Vertical;
7355 let pixels_per_line = Pixels::from(
7356 ScrollPixelOffset::from(minimap_hitbox.size.height) / layout.max_scroll_top,
7357 )
7358 .min(layout.minimap_line_height);
7359
7360 let mut mouse_position = window.mouse_position();
7361
7362 window.on_mouse_event({
7363 let editor = self.editor.clone();
7364
7365 let minimap_hitbox = minimap_hitbox.clone();
7366
7367 move |event: &MouseMoveEvent, phase, window, cx| {
7368 if phase == DispatchPhase::Capture {
7369 return;
7370 }
7371
7372 editor.update(cx, |editor, cx| {
7373 if event.pressed_button == Some(MouseButton::Left)
7374 && editor.scroll_manager.is_dragging_minimap()
7375 {
7376 let old_position = mouse_position.along(minimap_axis);
7377 let new_position = event.position.along(minimap_axis);
7378 if (minimap_hitbox.origin.along(minimap_axis)
7379 ..minimap_hitbox.bottom_right().along(minimap_axis))
7380 .contains(&old_position)
7381 {
7382 let position =
7383 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
7384 (p + ScrollPixelOffset::from(
7385 (new_position - old_position) / pixels_per_line,
7386 ))
7387 .max(0.)
7388 });
7389
7390 editor.set_scroll_position(position, window, cx);
7391 }
7392 cx.stop_propagation();
7393 } else if minimap_hitbox.is_hovered(window) {
7394 editor.scroll_manager.set_is_hovering_minimap_thumb(
7395 !event.dragging()
7396 && layout
7397 .thumb_layout
7398 .thumb_bounds
7399 .is_some_and(|bounds| bounds.contains(&event.position)),
7400 cx,
7401 );
7402
7403 // Stop hover events from propagating to the
7404 // underlying editor if the minimap hitbox is hovered
7405 if !event.dragging() {
7406 cx.stop_propagation();
7407 }
7408 } else {
7409 editor.scroll_manager.hide_minimap_thumb(cx);
7410 }
7411 mouse_position = event.position;
7412 });
7413 }
7414 });
7415
7416 if dragging_minimap {
7417 window.on_mouse_event({
7418 let editor = self.editor.clone();
7419 move |event: &MouseUpEvent, phase, window, cx| {
7420 if phase == DispatchPhase::Capture {
7421 return;
7422 }
7423
7424 editor.update(cx, |editor, cx| {
7425 if minimap_hitbox.is_hovered(window) {
7426 editor.scroll_manager.set_is_hovering_minimap_thumb(
7427 layout
7428 .thumb_layout
7429 .thumb_bounds
7430 .is_some_and(|bounds| bounds.contains(&event.position)),
7431 cx,
7432 );
7433 } else {
7434 editor.scroll_manager.hide_minimap_thumb(cx);
7435 }
7436 cx.stop_propagation();
7437 });
7438 }
7439 });
7440 } else {
7441 window.on_mouse_event({
7442 let editor = self.editor.clone();
7443
7444 move |event: &MouseDownEvent, phase, window, cx| {
7445 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
7446 return;
7447 }
7448
7449 let event_position = event.position;
7450
7451 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
7452 return;
7453 };
7454
7455 editor.update(cx, |editor, cx| {
7456 if !thumb_bounds.contains(&event_position) {
7457 let click_position =
7458 event_position.relative_to(&minimap_hitbox.origin).y;
7459
7460 let top_position = (click_position
7461 - thumb_bounds.size.along(minimap_axis) / 2.0)
7462 .max(Pixels::ZERO);
7463
7464 let scroll_offset = (layout.minimap_scroll_top
7465 + ScrollPixelOffset::from(
7466 top_position / layout.minimap_line_height,
7467 ))
7468 .min(layout.max_scroll_top);
7469
7470 let scroll_position = editor
7471 .scroll_position(cx)
7472 .apply_along(minimap_axis, |_| scroll_offset);
7473 editor.set_scroll_position(scroll_position, window, cx);
7474 }
7475
7476 editor.scroll_manager.set_is_dragging_minimap(cx);
7477 cx.stop_propagation();
7478 });
7479 }
7480 });
7481 }
7482 }
7483 }
7484
7485 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7486 for mut block in layout.blocks.drain(..) {
7487 if block.overlaps_gutter {
7488 block.element.paint(window, cx);
7489 } else {
7490 let mut bounds = layout.hitbox.bounds;
7491 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
7492 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7493 block.element.paint(window, cx);
7494 })
7495 }
7496 }
7497 }
7498
7499 fn paint_edit_prediction_popover(
7500 &mut self,
7501 layout: &mut EditorLayout,
7502 window: &mut Window,
7503 cx: &mut App,
7504 ) {
7505 if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
7506 edit_prediction_popover.paint(window, cx);
7507 }
7508 }
7509
7510 fn paint_mouse_context_menu(
7511 &mut self,
7512 layout: &mut EditorLayout,
7513 window: &mut Window,
7514 cx: &mut App,
7515 ) {
7516 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
7517 mouse_context_menu.paint(window, cx);
7518 }
7519 }
7520
7521 fn paint_scroll_wheel_listener(
7522 &mut self,
7523 layout: &EditorLayout,
7524 window: &mut Window,
7525 cx: &mut App,
7526 ) {
7527 window.on_mouse_event({
7528 let position_map = layout.position_map.clone();
7529 let editor = self.editor.clone();
7530 let hitbox = layout.hitbox.clone();
7531 let mut delta = ScrollDelta::default();
7532
7533 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
7534 // accidentally turn off their scrolling.
7535 let base_scroll_sensitivity =
7536 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
7537
7538 // Use a minimum fast_scroll_sensitivity for same reason above
7539 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
7540 .fast_scroll_sensitivity
7541 .max(0.01);
7542
7543 move |event: &ScrollWheelEvent, phase, window, cx| {
7544 let scroll_sensitivity = {
7545 if event.modifiers.alt {
7546 fast_scroll_sensitivity
7547 } else {
7548 base_scroll_sensitivity
7549 }
7550 };
7551
7552 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
7553 delta = delta.coalesce(event.delta);
7554 editor.update(cx, |editor, cx| {
7555 let position_map: &PositionMap = &position_map;
7556
7557 let line_height = position_map.line_height;
7558 let glyph_width = position_map.em_layout_width;
7559 let (delta, axis) = match delta {
7560 gpui::ScrollDelta::Pixels(mut pixels) => {
7561 //Trackpad
7562 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7563 (pixels, axis)
7564 }
7565
7566 gpui::ScrollDelta::Lines(lines) => {
7567 //Not trackpad
7568 let pixels = point(lines.x * glyph_width, lines.y * line_height);
7569 (pixels, None)
7570 }
7571 };
7572
7573 let current_scroll_position = position_map.snapshot.scroll_position();
7574 let x = (current_scroll_position.x * ScrollPixelOffset::from(glyph_width)
7575 - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
7576 / ScrollPixelOffset::from(glyph_width);
7577 let y = (current_scroll_position.y * ScrollPixelOffset::from(line_height)
7578 - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
7579 / ScrollPixelOffset::from(line_height);
7580 let mut scroll_position =
7581 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7582 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
7583 if forbid_vertical_scroll {
7584 scroll_position.y = current_scroll_position.y;
7585 }
7586
7587 if scroll_position != current_scroll_position {
7588 editor.scroll(scroll_position, axis, window, cx);
7589 cx.stop_propagation();
7590 } else if y < 0. {
7591 // Due to clamping, we may fail to detect cases of overscroll to the top;
7592 // We want the scroll manager to get an update in such cases and detect the change of direction
7593 // on the next frame.
7594 cx.notify();
7595 }
7596 });
7597 }
7598 }
7599 });
7600 }
7601
7602 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7603 if layout.mode.is_minimap() {
7604 return;
7605 }
7606
7607 self.paint_scroll_wheel_listener(layout, window, cx);
7608
7609 window.on_mouse_event({
7610 let position_map = layout.position_map.clone();
7611 let editor = self.editor.clone();
7612 let line_numbers = layout.line_numbers.clone();
7613
7614 move |event: &MouseDownEvent, phase, window, cx| {
7615 if phase == DispatchPhase::Bubble {
7616 match event.button {
7617 MouseButton::Left => editor.update(cx, |editor, cx| {
7618 let pending_mouse_down = editor
7619 .pending_mouse_down
7620 .get_or_insert_with(Default::default)
7621 .clone();
7622
7623 *pending_mouse_down.borrow_mut() = Some(event.clone());
7624
7625 Self::mouse_left_down(
7626 editor,
7627 event,
7628 &position_map,
7629 line_numbers.as_ref(),
7630 window,
7631 cx,
7632 );
7633 }),
7634 MouseButton::Right => editor.update(cx, |editor, cx| {
7635 Self::mouse_right_down(editor, event, &position_map, window, cx);
7636 }),
7637 MouseButton::Middle => editor.update(cx, |editor, cx| {
7638 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7639 }),
7640 _ => {}
7641 };
7642 }
7643 }
7644 });
7645
7646 window.on_mouse_event({
7647 let editor = self.editor.clone();
7648 let position_map = layout.position_map.clone();
7649
7650 move |event: &MouseUpEvent, phase, window, cx| {
7651 if phase == DispatchPhase::Bubble {
7652 editor.update(cx, |editor, cx| {
7653 Self::mouse_up(editor, event, &position_map, window, cx)
7654 });
7655 }
7656 }
7657 });
7658
7659 window.on_mouse_event({
7660 let editor = self.editor.clone();
7661 let position_map = layout.position_map.clone();
7662 let mut captured_mouse_down = None;
7663
7664 move |event: &MouseUpEvent, phase, window, cx| match phase {
7665 // Clear the pending mouse down during the capture phase,
7666 // so that it happens even if another event handler stops
7667 // propagation.
7668 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7669 let pending_mouse_down = editor
7670 .pending_mouse_down
7671 .get_or_insert_with(Default::default)
7672 .clone();
7673
7674 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7675 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7676 captured_mouse_down = pending_mouse_down.take();
7677 window.refresh();
7678 }
7679 }),
7680 // Fire click handlers during the bubble phase.
7681 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7682 if let Some(mouse_down) = captured_mouse_down.take() {
7683 let event = ClickEvent::Mouse(MouseClickEvent {
7684 down: mouse_down,
7685 up: event.clone(),
7686 });
7687 Self::click(editor, &event, &position_map, window, cx);
7688 }
7689 }),
7690 }
7691 });
7692
7693 window.on_mouse_event({
7694 let position_map = layout.position_map.clone();
7695 let editor = self.editor.clone();
7696
7697 move |event: &MousePressureEvent, phase, window, cx| {
7698 if phase == DispatchPhase::Bubble {
7699 editor.update(cx, |editor, cx| {
7700 Self::pressure_click(editor, &event, &position_map, window, cx);
7701 })
7702 }
7703 }
7704 });
7705
7706 window.on_mouse_event({
7707 let position_map = layout.position_map.clone();
7708 let editor = self.editor.clone();
7709 let split_side = self.split_side;
7710
7711 move |event: &MouseMoveEvent, phase, window, cx| {
7712 if phase == DispatchPhase::Bubble {
7713 editor.update(cx, |editor, cx| {
7714 if editor.hover_state.focused(window, cx) {
7715 return;
7716 }
7717 if event.pressed_button == Some(MouseButton::Left)
7718 || event.pressed_button == Some(MouseButton::Middle)
7719 {
7720 Self::mouse_dragged(editor, event, &position_map, window, cx)
7721 }
7722
7723 Self::mouse_moved(editor, event, &position_map, split_side, window, cx)
7724 });
7725 }
7726 }
7727 });
7728 }
7729
7730 fn shape_line_number(
7731 &self,
7732 text: SharedString,
7733 color: Hsla,
7734 window: &mut Window,
7735 ) -> ShapedLine {
7736 let run = TextRun {
7737 len: text.len(),
7738 font: self.style.text.font(),
7739 color,
7740 ..Default::default()
7741 };
7742 window.text_system().shape_line(
7743 text,
7744 self.style.text.font_size.to_pixels(window.rem_size()),
7745 &[run],
7746 None,
7747 )
7748 }
7749
7750 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7751 let unstaged = status.has_secondary_hunk();
7752 let unstaged_hollow = matches!(
7753 ProjectSettings::get_global(cx).git.hunk_style,
7754 GitHunkStyleSetting::UnstagedHollow
7755 );
7756
7757 unstaged == unstaged_hollow
7758 }
7759
7760 #[cfg(debug_assertions)]
7761 fn layout_debug_ranges(
7762 selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
7763 anchor_range: Range<Anchor>,
7764 display_snapshot: &DisplaySnapshot,
7765 cx: &App,
7766 ) {
7767 let theme = cx.theme();
7768 text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
7769 if debug_ranges.ranges.is_empty() {
7770 return;
7771 }
7772 let buffer_snapshot = &display_snapshot.buffer_snapshot();
7773 for (buffer, buffer_range, excerpt_id) in
7774 buffer_snapshot.range_to_buffer_ranges(anchor_range.start..=anchor_range.end)
7775 {
7776 let buffer_range =
7777 buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
7778 selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
7779 let player_color = theme
7780 .players()
7781 .color_for_participant(debug_range.occurrence_index as u32 + 1);
7782 debug_range.ranges.iter().filter_map(move |range| {
7783 if range.start.buffer_id != Some(buffer.remote_id()) {
7784 return None;
7785 }
7786 let clipped_start = range.start.max(&buffer_range.start, buffer);
7787 let clipped_end = range.end.min(&buffer_range.end, buffer);
7788 let range = buffer_snapshot
7789 .anchor_range_in_excerpt(excerpt_id, *clipped_start..*clipped_end)?;
7790 let start = range.start.to_display_point(display_snapshot);
7791 let end = range.end.to_display_point(display_snapshot);
7792 let selection_layout = SelectionLayout {
7793 head: start,
7794 range: start..end,
7795 cursor_shape: CursorShape::Bar,
7796 is_newest: false,
7797 is_local: false,
7798 active_rows: start.row()..end.row(),
7799 user_name: Some(SharedString::new(debug_range.value.clone())),
7800 };
7801 Some((player_color, vec![selection_layout]))
7802 })
7803 }));
7804 }
7805 });
7806 }
7807}
7808
7809pub fn render_breadcrumb_text(
7810 mut segments: Vec<BreadcrumbText>,
7811 prefix: Option<gpui::AnyElement>,
7812 active_item: &dyn ItemHandle,
7813 multibuffer_header: bool,
7814 window: &mut Window,
7815 cx: &App,
7816) -> gpui::AnyElement {
7817 const MAX_SEGMENTS: usize = 12;
7818
7819 let element = h_flex().flex_grow().text_ui(cx);
7820
7821 let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
7822 let suffix_start_ix = cmp::max(
7823 prefix_end_ix,
7824 segments.len().saturating_sub(MAX_SEGMENTS / 2),
7825 );
7826
7827 if suffix_start_ix > prefix_end_ix {
7828 segments.splice(
7829 prefix_end_ix..suffix_start_ix,
7830 Some(BreadcrumbText {
7831 text: "β―".into(),
7832 highlights: None,
7833 font: None,
7834 }),
7835 );
7836 }
7837
7838 let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
7839 let mut text_style = window.text_style();
7840 if let Some(ref font) = segment.font {
7841 text_style.font_family = font.family.clone();
7842 text_style.font_features = font.features.clone();
7843 text_style.font_style = font.style;
7844 text_style.font_weight = font.weight;
7845 }
7846 text_style.color = Color::Muted.color(cx);
7847
7848 if index == 0
7849 && !workspace::TabBarSettings::get_global(cx).show
7850 && active_item.is_dirty(cx)
7851 && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
7852 {
7853 return styled_element;
7854 }
7855
7856 StyledText::new(segment.text.replace('\n', "β"))
7857 .with_default_highlights(&text_style, segment.highlights.unwrap_or_default())
7858 .into_any()
7859 });
7860
7861 let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
7862 Label::new("βΊ").color(Color::Placeholder).into_any_element()
7863 });
7864
7865 let breadcrumbs_stack = h_flex()
7866 .gap_1()
7867 .when(multibuffer_header, |this| {
7868 this.pl_2()
7869 .border_l_1()
7870 .border_color(cx.theme().colors().border.opacity(0.6))
7871 })
7872 .children(breadcrumbs);
7873
7874 let breadcrumbs = if let Some(prefix) = prefix {
7875 h_flex().gap_1p5().child(prefix).child(breadcrumbs_stack)
7876 } else {
7877 breadcrumbs_stack
7878 };
7879
7880 let editor = active_item
7881 .downcast::<Editor>()
7882 .map(|editor| editor.downgrade());
7883
7884 let has_project_path = active_item.project_path(cx).is_some();
7885
7886 match editor {
7887 Some(editor) => element
7888 .id("breadcrumb_container")
7889 .when(!multibuffer_header, |this| this.overflow_x_scroll())
7890 .child(
7891 ButtonLike::new("toggle outline view")
7892 .child(breadcrumbs)
7893 .when(multibuffer_header, |this| {
7894 this.style(ButtonStyle::Transparent)
7895 })
7896 .when(!multibuffer_header, |this| {
7897 let focus_handle = editor.upgrade().unwrap().focus_handle(&cx);
7898
7899 this.tooltip(Tooltip::element(move |_window, cx| {
7900 v_flex()
7901 .gap_1()
7902 .child(
7903 h_flex()
7904 .gap_1()
7905 .justify_between()
7906 .child(Label::new("Show Symbol Outline"))
7907 .child(ui::KeyBinding::for_action_in(
7908 &zed_actions::outline::ToggleOutline,
7909 &focus_handle,
7910 cx,
7911 )),
7912 )
7913 .when(has_project_path, |this| {
7914 this.child(
7915 h_flex()
7916 .gap_1()
7917 .justify_between()
7918 .pt_1()
7919 .border_t_1()
7920 .border_color(cx.theme().colors().border_variant)
7921 .child(Label::new("Right-Click to Copy Path")),
7922 )
7923 })
7924 .into_any_element()
7925 }))
7926 .on_click({
7927 let editor = editor.clone();
7928 move |_, window, cx| {
7929 if let Some((editor, callback)) = editor
7930 .upgrade()
7931 .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
7932 {
7933 callback(editor.to_any_view(), window, cx);
7934 }
7935 }
7936 })
7937 .when(has_project_path, |this| {
7938 this.on_right_click({
7939 let editor = editor.clone();
7940 move |_, _, cx| {
7941 if let Some(abs_path) = editor.upgrade().and_then(|editor| {
7942 editor.update(cx, |editor, cx| {
7943 editor.target_file_abs_path(cx)
7944 })
7945 }) {
7946 if let Some(path_str) = abs_path.to_str() {
7947 cx.write_to_clipboard(ClipboardItem::new_string(
7948 path_str.to_string(),
7949 ));
7950 }
7951 }
7952 }
7953 })
7954 })
7955 }),
7956 )
7957 .into_any_element(),
7958 None => element
7959 .h(rems_from_px(22.)) // Match the height and padding of the `ButtonLike` in the other arm.
7960 .pl_1()
7961 .child(breadcrumbs)
7962 .into_any_element(),
7963 }
7964}
7965
7966fn apply_dirty_filename_style(
7967 segment: &BreadcrumbText,
7968 text_style: &gpui::TextStyle,
7969 cx: &App,
7970) -> Option<gpui::AnyElement> {
7971 let text = segment.text.replace('\n', "β");
7972
7973 let filename_position = std::path::Path::new(&segment.text)
7974 .file_name()
7975 .and_then(|f| {
7976 let filename_str = f.to_string_lossy();
7977 segment.text.rfind(filename_str.as_ref())
7978 })?;
7979
7980 let bold_weight = FontWeight::BOLD;
7981 let default_color = Color::Default.color(cx);
7982
7983 if filename_position == 0 {
7984 let mut filename_style = text_style.clone();
7985 filename_style.font_weight = bold_weight;
7986 filename_style.color = default_color;
7987
7988 return Some(
7989 StyledText::new(text)
7990 .with_default_highlights(&filename_style, [])
7991 .into_any(),
7992 );
7993 }
7994
7995 let highlight_style = gpui::HighlightStyle {
7996 font_weight: Some(bold_weight),
7997 color: Some(default_color),
7998 ..Default::default()
7999 };
8000
8001 let highlight = vec![(filename_position..text.len(), highlight_style)];
8002 Some(
8003 StyledText::new(text)
8004 .with_default_highlights(text_style, highlight)
8005 .into_any(),
8006 )
8007}
8008
8009fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
8010 file_status.map_or(Color::Default, |status| {
8011 if status.is_conflicted() {
8012 Color::Conflict
8013 } else if status.is_modified() {
8014 Color::Modified
8015 } else if status.is_deleted() {
8016 Color::Disabled
8017 } else if status.is_created() {
8018 Color::Created
8019 } else {
8020 Color::Default
8021 }
8022 })
8023}
8024
8025pub(crate) fn header_jump_data(
8026 editor_snapshot: &EditorSnapshot,
8027 block_row_start: DisplayRow,
8028 height: u32,
8029 first_excerpt: &ExcerptInfo,
8030 latest_selection_anchors: &HashMap<BufferId, Anchor>,
8031) -> JumpData {
8032 let jump_target = if let Some(anchor) = latest_selection_anchors.get(&first_excerpt.buffer_id)
8033 && let Some(range) = editor_snapshot.context_range_for_excerpt(anchor.excerpt_id)
8034 && let Some(buffer) = editor_snapshot
8035 .buffer_snapshot()
8036 .buffer_for_excerpt(anchor.excerpt_id)
8037 {
8038 JumpTargetInExcerptInput {
8039 id: anchor.excerpt_id,
8040 buffer,
8041 excerpt_start_anchor: range.start,
8042 jump_anchor: anchor.text_anchor,
8043 }
8044 } else {
8045 JumpTargetInExcerptInput {
8046 id: first_excerpt.id,
8047 buffer: &first_excerpt.buffer,
8048 excerpt_start_anchor: first_excerpt.range.context.start,
8049 jump_anchor: first_excerpt.range.primary.start,
8050 }
8051 };
8052 header_jump_data_inner(editor_snapshot, block_row_start, height, &jump_target)
8053}
8054
8055struct JumpTargetInExcerptInput<'a> {
8056 id: ExcerptId,
8057 buffer: &'a language::BufferSnapshot,
8058 excerpt_start_anchor: text::Anchor,
8059 jump_anchor: text::Anchor,
8060}
8061
8062fn header_jump_data_inner(
8063 snapshot: &EditorSnapshot,
8064 block_row_start: DisplayRow,
8065 height: u32,
8066 for_excerpt: &JumpTargetInExcerptInput,
8067) -> JumpData {
8068 let buffer = &for_excerpt.buffer;
8069 let jump_position = language::ToPoint::to_point(&for_excerpt.jump_anchor, buffer);
8070 let excerpt_start = for_excerpt.excerpt_start_anchor;
8071 let rows_from_excerpt_start = if for_excerpt.jump_anchor == excerpt_start {
8072 0
8073 } else {
8074 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
8075 jump_position.row.saturating_sub(excerpt_start_point.row)
8076 };
8077
8078 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
8079 .saturating_sub(
8080 snapshot
8081 .scroll_anchor
8082 .scroll_position(&snapshot.display_snapshot)
8083 .y as u32,
8084 );
8085
8086 JumpData::MultiBufferPoint {
8087 excerpt_id: for_excerpt.id,
8088 anchor: for_excerpt.jump_anchor,
8089 position: jump_position,
8090 line_offset_from_top,
8091 }
8092}
8093
8094pub(crate) fn render_buffer_header(
8095 editor: &Entity<Editor>,
8096 for_excerpt: &ExcerptInfo,
8097 is_folded: bool,
8098 is_selected: bool,
8099 is_sticky: bool,
8100 jump_data: JumpData,
8101 window: &mut Window,
8102 cx: &mut App,
8103) -> impl IntoElement {
8104 let editor_read = editor.read(cx);
8105 let multi_buffer = editor_read.buffer.read(cx);
8106 let is_read_only = editor_read.read_only(cx);
8107 let editor_handle: &dyn ItemHandle = editor;
8108
8109 let breadcrumbs = if is_selected {
8110 editor_read.breadcrumbs_inner(cx)
8111 } else {
8112 None
8113 };
8114
8115 let file_status = multi_buffer
8116 .all_diff_hunks_expanded()
8117 .then(|| editor_read.status_for_buffer_id(for_excerpt.buffer_id, cx))
8118 .flatten();
8119 let indicator = multi_buffer
8120 .buffer(for_excerpt.buffer_id)
8121 .and_then(|buffer| {
8122 let buffer = buffer.read(cx);
8123 let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
8124 (true, _) => Some(Color::Warning),
8125 (_, true) => Some(Color::Accent),
8126 (false, false) => None,
8127 };
8128 indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
8129 });
8130
8131 let include_root = editor_read
8132 .project
8133 .as_ref()
8134 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
8135 .unwrap_or_default();
8136 let file = for_excerpt.buffer.file();
8137 let can_open_excerpts = file.is_none_or(|file| file.can_open());
8138 let path_style = file.map(|file| file.path_style(cx));
8139 let relative_path = for_excerpt.buffer.resolve_file_path(include_root, cx);
8140 let (parent_path, filename) = if let Some(path) = &relative_path {
8141 if let Some(path_style) = path_style {
8142 let (dir, file_name) = path_style.split(path);
8143 (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
8144 } else {
8145 (None, Some(path.clone()))
8146 }
8147 } else {
8148 (None, None)
8149 };
8150 let focus_handle = editor_read.focus_handle(cx);
8151 let colors = cx.theme().colors();
8152
8153 let header = div()
8154 .id(("buffer-header", for_excerpt.buffer_id.to_proto()))
8155 .p_1()
8156 .w_full()
8157 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
8158 .child(
8159 h_flex()
8160 .size_full()
8161 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
8162 .pl_1()
8163 .pr_2()
8164 .rounded_sm()
8165 .gap_1p5()
8166 .when(is_sticky, |el| el.shadow_md())
8167 .border_1()
8168 .map(|border| {
8169 let border_color =
8170 if is_selected && is_folded && focus_handle.contains_focused(window, cx) {
8171 colors.border_focused
8172 } else {
8173 colors.border
8174 };
8175 border.border_color(border_color)
8176 })
8177 .bg(colors.editor_subheader_background)
8178 .hover(|style| style.bg(colors.element_hover))
8179 .map(|header| {
8180 let editor = editor.clone();
8181 let buffer_id = for_excerpt.buffer_id;
8182 let toggle_chevron_icon =
8183 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
8184 let button_size = rems_from_px(28.);
8185
8186 header.child(
8187 div()
8188 .hover(|style| style.bg(colors.element_selected))
8189 .rounded_xs()
8190 .child(
8191 ButtonLike::new("toggle-buffer-fold")
8192 .style(ButtonStyle::Transparent)
8193 .height(button_size.into())
8194 .width(button_size)
8195 .children(toggle_chevron_icon)
8196 .tooltip({
8197 let focus_handle = focus_handle.clone();
8198 let is_folded_for_tooltip = is_folded;
8199 move |_window, cx| {
8200 Tooltip::with_meta_in(
8201 if is_folded_for_tooltip {
8202 "Unfold Excerpt"
8203 } else {
8204 "Fold Excerpt"
8205 },
8206 Some(&ToggleFold),
8207 format!(
8208 "{} to toggle all",
8209 text_for_keystroke(
8210 &Modifiers::alt(),
8211 "click",
8212 cx
8213 )
8214 ),
8215 &focus_handle,
8216 cx,
8217 )
8218 }
8219 })
8220 .on_click(move |event, window, cx| {
8221 if event.modifiers().alt {
8222 editor.update(cx, |editor, cx| {
8223 editor.toggle_fold_all(&ToggleFoldAll, window, cx);
8224 });
8225 } else {
8226 if is_folded {
8227 editor.update(cx, |editor, cx| {
8228 editor.unfold_buffer(buffer_id, cx);
8229 });
8230 } else {
8231 editor.update(cx, |editor, cx| {
8232 editor.fold_buffer(buffer_id, cx);
8233 });
8234 }
8235 }
8236 }),
8237 ),
8238 )
8239 })
8240 .children(
8241 editor_read
8242 .addons
8243 .values()
8244 .filter_map(|addon| {
8245 addon.render_buffer_header_controls(for_excerpt, window, cx)
8246 })
8247 .take(1),
8248 )
8249 .when(!is_read_only, |this| {
8250 this.child(
8251 h_flex()
8252 .size_3()
8253 .justify_center()
8254 .flex_shrink_0()
8255 .children(indicator),
8256 )
8257 })
8258 .child(
8259 h_flex()
8260 .cursor_pointer()
8261 .id("path_header_block")
8262 .min_w_0()
8263 .size_full()
8264 .gap_1()
8265 .justify_between()
8266 .overflow_hidden()
8267 .child(h_flex().min_w_0().flex_1().gap_0p5().overflow_hidden().map(
8268 |path_header| {
8269 let filename = filename
8270 .map(SharedString::from)
8271 .unwrap_or_else(|| "untitled".into());
8272
8273 let full_path = match parent_path.as_deref() {
8274 Some(parent) if !parent.is_empty() => {
8275 format!("{}{}", parent, filename.as_str())
8276 }
8277 _ => filename.as_str().to_string(),
8278 };
8279
8280 path_header
8281 .child(
8282 ButtonLike::new("filename-button")
8283 .when(ItemSettings::get_global(cx).file_icons, |this| {
8284 let path = path::Path::new(filename.as_str());
8285 let icon = FileIcons::get_icon(path, cx)
8286 .unwrap_or_default();
8287
8288 this.child(
8289 Icon::from_path(icon).color(Color::Muted),
8290 )
8291 })
8292 .child(
8293 Label::new(filename)
8294 .single_line()
8295 .color(file_status_label_color(file_status))
8296 .buffer_font(cx)
8297 .when(
8298 file_status.is_some_and(|s| s.is_deleted()),
8299 |label| label.strikethrough(),
8300 ),
8301 )
8302 .tooltip(move |_, cx| {
8303 Tooltip::with_meta(
8304 "Open File",
8305 None,
8306 full_path.clone(),
8307 cx,
8308 )
8309 })
8310 .on_click(window.listener_for(editor, {
8311 let jump_data = jump_data.clone();
8312 move |editor, e: &ClickEvent, window, cx| {
8313 editor.open_excerpts_common(
8314 Some(jump_data.clone()),
8315 e.modifiers().secondary(),
8316 window,
8317 cx,
8318 );
8319 }
8320 })),
8321 )
8322 .when_some(parent_path, |then, path| {
8323 then.child(
8324 Label::new(path)
8325 .buffer_font(cx)
8326 .truncate_start()
8327 .color(
8328 if file_status
8329 .is_some_and(FileStatus::is_deleted)
8330 {
8331 Color::Custom(colors.text_disabled)
8332 } else {
8333 Color::Custom(colors.text_muted)
8334 },
8335 ),
8336 )
8337 })
8338 .when(!for_excerpt.buffer.capability.editable(), |el| {
8339 el.child(Icon::new(IconName::FileLock).color(Color::Muted))
8340 })
8341 .when_some(breadcrumbs, |then, breadcrumbs| {
8342 then.child(render_breadcrumb_text(
8343 breadcrumbs,
8344 None,
8345 editor_handle,
8346 true,
8347 window,
8348 cx,
8349 ))
8350 })
8351 },
8352 ))
8353 .when(
8354 can_open_excerpts && is_selected && relative_path.is_some(),
8355 |el| {
8356 el.child(
8357 Button::new("open-file-button", "Open File")
8358 .style(ButtonStyle::OutlinedGhost)
8359 .key_binding(KeyBinding::for_action_in(
8360 &OpenExcerpts,
8361 &focus_handle,
8362 cx,
8363 ))
8364 .on_click(window.listener_for(editor, {
8365 let jump_data = jump_data.clone();
8366 move |editor, e: &ClickEvent, window, cx| {
8367 editor.open_excerpts_common(
8368 Some(jump_data.clone()),
8369 e.modifiers().secondary(),
8370 window,
8371 cx,
8372 );
8373 }
8374 })),
8375 )
8376 },
8377 )
8378 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
8379 .on_click(window.listener_for(editor, {
8380 let buffer_id = for_excerpt.buffer_id;
8381 move |editor, e: &ClickEvent, window, cx| {
8382 if e.modifiers().alt {
8383 editor.open_excerpts_common(
8384 Some(jump_data.clone()),
8385 e.modifiers().secondary(),
8386 window,
8387 cx,
8388 );
8389 return;
8390 }
8391
8392 if is_folded {
8393 editor.unfold_buffer(buffer_id, cx);
8394 } else {
8395 editor.fold_buffer(buffer_id, cx);
8396 }
8397 }
8398 })),
8399 ),
8400 );
8401
8402 let file = for_excerpt.buffer.file().cloned();
8403 let editor = editor.clone();
8404
8405 right_click_menu("buffer-header-context-menu")
8406 .trigger(move |_, _, _| header)
8407 .menu(move |window, cx| {
8408 let menu_context = focus_handle.clone();
8409 let editor = editor.clone();
8410 let file = file.clone();
8411 ContextMenu::build(window, cx, move |mut menu, window, cx| {
8412 if let Some(file) = file
8413 && let Some(project) = editor.read(cx).project()
8414 && let Some(worktree) =
8415 project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
8416 {
8417 let path_style = file.path_style(cx);
8418 let worktree = worktree.read(cx);
8419 let relative_path = file.path();
8420 let entry_for_path = worktree.entry_for_path(relative_path);
8421 let abs_path = entry_for_path.map(|e| {
8422 e.canonical_path
8423 .as_deref()
8424 .map_or_else(|| worktree.absolutize(relative_path), Path::to_path_buf)
8425 });
8426 let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
8427
8428 let parent_abs_path = abs_path
8429 .as_ref()
8430 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
8431 let relative_path = has_relative_path
8432 .then_some(relative_path)
8433 .map(ToOwned::to_owned);
8434
8435 let visible_in_project_panel = relative_path.is_some() && worktree.is_visible();
8436 let reveal_in_project_panel = entry_for_path
8437 .filter(|_| visible_in_project_panel)
8438 .map(|entry| entry.id);
8439 menu = menu
8440 .when_some(abs_path, |menu, abs_path| {
8441 menu.entry(
8442 "Copy Path",
8443 Some(Box::new(zed_actions::workspace::CopyPath)),
8444 window.handler_for(&editor, move |_, _, cx| {
8445 cx.write_to_clipboard(ClipboardItem::new_string(
8446 abs_path.to_string_lossy().into_owned(),
8447 ));
8448 }),
8449 )
8450 })
8451 .when_some(relative_path, |menu, relative_path| {
8452 menu.entry(
8453 "Copy Relative Path",
8454 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
8455 window.handler_for(&editor, move |_, _, cx| {
8456 cx.write_to_clipboard(ClipboardItem::new_string(
8457 relative_path.display(path_style).to_string(),
8458 ));
8459 }),
8460 )
8461 })
8462 .when(
8463 reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
8464 |menu| menu.separator(),
8465 )
8466 .when_some(reveal_in_project_panel, |menu, entry_id| {
8467 menu.entry(
8468 "Reveal In Project Panel",
8469 Some(Box::new(RevealInProjectPanel::default())),
8470 window.handler_for(&editor, move |editor, _, cx| {
8471 if let Some(project) = &mut editor.project {
8472 project.update(cx, |_, cx| {
8473 cx.emit(project::Event::RevealInProjectPanel(entry_id))
8474 });
8475 }
8476 }),
8477 )
8478 })
8479 .when_some(parent_abs_path, |menu, parent_abs_path| {
8480 menu.entry(
8481 "Open in Terminal",
8482 Some(Box::new(OpenInTerminal)),
8483 window.handler_for(&editor, move |_, window, cx| {
8484 window.dispatch_action(
8485 OpenTerminal {
8486 working_directory: parent_abs_path.clone(),
8487 local: false,
8488 }
8489 .boxed_clone(),
8490 cx,
8491 );
8492 }),
8493 )
8494 });
8495 }
8496
8497 menu.context(menu_context)
8498 })
8499 })
8500}
8501
8502pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
8503
8504impl AcceptEditPredictionBinding {
8505 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
8506 if let Some(binding) = self.0.as_ref() {
8507 match &binding.keystrokes() {
8508 [keystroke, ..] => Some(keystroke),
8509 _ => None,
8510 }
8511 } else {
8512 None
8513 }
8514 }
8515}
8516
8517fn prepaint_gutter_button(
8518 mut button: AnyElement,
8519 row: DisplayRow,
8520 line_height: Pixels,
8521 gutter_dimensions: &GutterDimensions,
8522 scroll_position: gpui::Point<ScrollOffset>,
8523 gutter_hitbox: &Hitbox,
8524 window: &mut Window,
8525 cx: &mut App,
8526) -> AnyElement {
8527 let available_space = size(
8528 AvailableSpace::MinContent,
8529 AvailableSpace::Definite(line_height),
8530 );
8531 let indicator_size = button.layout_as_root(available_space, window, cx);
8532 let git_gutter_width = EditorElement::gutter_strip_width(line_height)
8533 + gutter_dimensions
8534 .git_blame_entries_width
8535 .unwrap_or_default();
8536
8537 let x = git_gutter_width + px(2.);
8538
8539 let mut y =
8540 Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
8541 y += (line_height - indicator_size.height) / 2.;
8542
8543 button.prepaint_as_root(
8544 gutter_hitbox.origin + point(x, y),
8545 available_space,
8546 window,
8547 cx,
8548 );
8549 button
8550}
8551
8552fn render_inline_blame_entry(
8553 blame_entry: BlameEntry,
8554 style: &EditorStyle,
8555 cx: &mut App,
8556) -> Option<AnyElement> {
8557 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8558 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
8559}
8560
8561fn render_blame_entry_popover(
8562 blame_entry: BlameEntry,
8563 scroll_handle: ScrollHandle,
8564 commit_message: Option<ParsedCommitMessage>,
8565 markdown: Entity<Markdown>,
8566 workspace: WeakEntity<Workspace>,
8567 blame: &Entity<GitBlame>,
8568 buffer: BufferId,
8569 window: &mut Window,
8570 cx: &mut App,
8571) -> Option<AnyElement> {
8572 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8573 let blame = blame.read(cx);
8574 let repository = blame.repository(cx, buffer)?;
8575 renderer.render_blame_entry_popover(
8576 blame_entry,
8577 scroll_handle,
8578 commit_message,
8579 markdown,
8580 repository,
8581 workspace,
8582 window,
8583 cx,
8584 )
8585}
8586
8587fn render_blame_entry(
8588 ix: usize,
8589 blame: &Entity<GitBlame>,
8590 blame_entry: BlameEntry,
8591 style: &EditorStyle,
8592 last_used_color: &mut Option<(Hsla, Oid)>,
8593 editor: Entity<Editor>,
8594 workspace: Entity<Workspace>,
8595 buffer: BufferId,
8596 renderer: &dyn BlameRenderer,
8597 window: &mut Window,
8598 cx: &mut App,
8599) -> Option<AnyElement> {
8600 let index: u32 = blame_entry.sha.into();
8601 let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
8602
8603 // If the last color we used is the same as the one we get for this line, but
8604 // the commit SHAs are different, then we try again to get a different color.
8605 if let Some((color, sha)) = *last_used_color
8606 && sha != blame_entry.sha
8607 && color == sha_color
8608 {
8609 sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
8610 }
8611 last_used_color.replace((sha_color, blame_entry.sha));
8612
8613 let blame = blame.read(cx);
8614 let details = blame.details_for_entry(buffer, &blame_entry);
8615 let repository = blame.repository(cx, buffer)?;
8616 renderer.render_blame_entry(
8617 &style.text,
8618 blame_entry,
8619 details,
8620 repository,
8621 workspace.downgrade(),
8622 editor,
8623 ix,
8624 sha_color,
8625 window,
8626 cx,
8627 )
8628}
8629
8630#[derive(Debug)]
8631pub(crate) struct LineWithInvisibles {
8632 fragments: SmallVec<[LineFragment; 1]>,
8633 invisibles: Vec<Invisible>,
8634 len: usize,
8635 pub(crate) width: Pixels,
8636 font_size: Pixels,
8637}
8638
8639enum LineFragment {
8640 Text(ShapedLine),
8641 Element {
8642 id: ChunkRendererId,
8643 element: Option<AnyElement>,
8644 size: Size<Pixels>,
8645 len: usize,
8646 },
8647}
8648
8649impl fmt::Debug for LineFragment {
8650 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8651 match self {
8652 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
8653 LineFragment::Element { size, len, .. } => f
8654 .debug_struct("Element")
8655 .field("size", size)
8656 .field("len", len)
8657 .finish(),
8658 }
8659 }
8660}
8661
8662impl LineWithInvisibles {
8663 fn from_chunks<'a>(
8664 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
8665 editor_style: &EditorStyle,
8666 max_line_len: usize,
8667 max_line_count: usize,
8668 editor_mode: &EditorMode,
8669 text_width: Pixels,
8670 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8671 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
8672 window: &mut Window,
8673 cx: &mut App,
8674 ) -> Vec<Self> {
8675 let text_style = &editor_style.text;
8676 let mut layouts = Vec::with_capacity(max_line_count);
8677 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
8678 let mut line = String::new();
8679 let mut invisibles = Vec::new();
8680 let mut width = Pixels::ZERO;
8681 let mut len = 0;
8682 let mut styles = Vec::new();
8683 let mut non_whitespace_added = false;
8684 let mut row = 0;
8685 let mut line_exceeded_max_len = false;
8686 let font_size = text_style.font_size.to_pixels(window.rem_size());
8687 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
8688
8689 let ellipsis = SharedString::from("β―");
8690
8691 for highlighted_chunk in chunks.chain([HighlightedChunk {
8692 text: "\n",
8693 style: None,
8694 is_tab: false,
8695 is_inlay: false,
8696 replacement: None,
8697 }]) {
8698 if let Some(replacement) = highlighted_chunk.replacement {
8699 if !line.is_empty() {
8700 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8701 let text_runs: &[TextRun] = if segments.is_empty() {
8702 &styles
8703 } else {
8704 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8705 };
8706 let shaped_line = window.text_system().shape_line(
8707 line.clone().into(),
8708 font_size,
8709 text_runs,
8710 None,
8711 );
8712 width += shaped_line.width;
8713 len += shaped_line.len;
8714 fragments.push(LineFragment::Text(shaped_line));
8715 line.clear();
8716 styles.clear();
8717 }
8718
8719 match replacement {
8720 ChunkReplacement::Renderer(renderer) => {
8721 let available_width = if renderer.constrain_width {
8722 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
8723 ellipsis.clone()
8724 } else {
8725 SharedString::from(Arc::from(highlighted_chunk.text))
8726 };
8727 let shaped_line = window.text_system().shape_line(
8728 chunk,
8729 font_size,
8730 &[text_style.to_run(highlighted_chunk.text.len())],
8731 None,
8732 );
8733 AvailableSpace::Definite(shaped_line.width)
8734 } else {
8735 AvailableSpace::MinContent
8736 };
8737
8738 let mut element = (renderer.render)(&mut ChunkRendererContext {
8739 context: cx,
8740 window,
8741 max_width: text_width,
8742 });
8743 let line_height = text_style.line_height_in_pixels(window.rem_size());
8744 let size = element.layout_as_root(
8745 size(available_width, AvailableSpace::Definite(line_height)),
8746 window,
8747 cx,
8748 );
8749
8750 width += size.width;
8751 len += highlighted_chunk.text.len();
8752 fragments.push(LineFragment::Element {
8753 id: renderer.id,
8754 element: Some(element),
8755 size,
8756 len: highlighted_chunk.text.len(),
8757 });
8758 }
8759 ChunkReplacement::Str(x) => {
8760 let text_style = if let Some(style) = highlighted_chunk.style {
8761 Cow::Owned(text_style.clone().highlight(style))
8762 } else {
8763 Cow::Borrowed(text_style)
8764 };
8765
8766 let run = TextRun {
8767 len: x.len(),
8768 font: text_style.font(),
8769 color: text_style.color,
8770 background_color: text_style.background_color,
8771 underline: text_style.underline,
8772 strikethrough: text_style.strikethrough,
8773 };
8774 let line_layout = window
8775 .text_system()
8776 .shape_line(x, font_size, &[run], None)
8777 .with_len(highlighted_chunk.text.len());
8778
8779 width += line_layout.width;
8780 len += highlighted_chunk.text.len();
8781 fragments.push(LineFragment::Text(line_layout))
8782 }
8783 }
8784 } else {
8785 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
8786 if ix > 0 {
8787 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8788 let text_runs = if segments.is_empty() {
8789 &styles
8790 } else {
8791 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8792 };
8793 let shaped_line = window.text_system().shape_line(
8794 line.clone().into(),
8795 font_size,
8796 text_runs,
8797 None,
8798 );
8799 width += shaped_line.width;
8800 len += shaped_line.len;
8801 fragments.push(LineFragment::Text(shaped_line));
8802 layouts.push(Self {
8803 width: mem::take(&mut width),
8804 len: mem::take(&mut len),
8805 fragments: mem::take(&mut fragments),
8806 invisibles: std::mem::take(&mut invisibles),
8807 font_size,
8808 });
8809
8810 line.clear();
8811 styles.clear();
8812 row += 1;
8813 line_exceeded_max_len = false;
8814 non_whitespace_added = false;
8815 if row == max_line_count {
8816 return layouts;
8817 }
8818 }
8819
8820 if !line_chunk.is_empty() && !line_exceeded_max_len {
8821 let text_style = if let Some(style) = highlighted_chunk.style {
8822 Cow::Owned(text_style.clone().highlight(style))
8823 } else {
8824 Cow::Borrowed(text_style)
8825 };
8826
8827 if line.len() + line_chunk.len() > max_line_len {
8828 let mut chunk_len = max_line_len - line.len();
8829 while !line_chunk.is_char_boundary(chunk_len) {
8830 chunk_len -= 1;
8831 }
8832 line_chunk = &line_chunk[..chunk_len];
8833 line_exceeded_max_len = true;
8834 }
8835
8836 styles.push(TextRun {
8837 len: line_chunk.len(),
8838 font: text_style.font(),
8839 color: text_style.color,
8840 background_color: text_style.background_color,
8841 underline: text_style.underline,
8842 strikethrough: text_style.strikethrough,
8843 });
8844
8845 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
8846 // Line wrap pads its contents with fake whitespaces,
8847 // avoid printing them
8848 let is_soft_wrapped = is_row_soft_wrapped(row);
8849 if highlighted_chunk.is_tab {
8850 if non_whitespace_added || !is_soft_wrapped {
8851 invisibles.push(Invisible::Tab {
8852 line_start_offset: line.len(),
8853 line_end_offset: line.len() + line_chunk.len(),
8854 });
8855 }
8856 } else {
8857 invisibles.extend(line_chunk.char_indices().filter_map(
8858 |(index, c)| {
8859 let is_whitespace = c.is_whitespace();
8860 non_whitespace_added |= !is_whitespace;
8861 if is_whitespace
8862 && (non_whitespace_added || !is_soft_wrapped)
8863 {
8864 Some(Invisible::Whitespace {
8865 line_offset: line.len() + index,
8866 })
8867 } else {
8868 None
8869 }
8870 },
8871 ))
8872 }
8873 }
8874
8875 line.push_str(line_chunk);
8876 }
8877 }
8878 }
8879 }
8880
8881 layouts
8882 }
8883
8884 /// Takes text runs and non-overlapping left-to-right background ranges with color.
8885 /// Returns new text runs with adjusted contrast as per background ranges.
8886 fn split_runs_by_bg_segments(
8887 text_runs: &[TextRun],
8888 bg_segments: &[(Range<DisplayPoint>, Hsla)],
8889 min_contrast: f32,
8890 start_col_offset: usize,
8891 ) -> Vec<TextRun> {
8892 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
8893 let mut line_col = start_col_offset;
8894 let mut segment_ix = 0usize;
8895
8896 for text_run in text_runs.iter() {
8897 let run_start_col = line_col;
8898 let run_end_col = run_start_col + text_run.len;
8899 while segment_ix < bg_segments.len()
8900 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
8901 {
8902 segment_ix += 1;
8903 }
8904 let mut cursor_col = run_start_col;
8905 let mut local_segment_ix = segment_ix;
8906 while local_segment_ix < bg_segments.len() {
8907 let (range, segment_color) = &bg_segments[local_segment_ix];
8908 let segment_start_col = range.start.column() as usize;
8909 let segment_end_col = range.end.column() as usize;
8910 if segment_start_col >= run_end_col {
8911 break;
8912 }
8913 if segment_start_col > cursor_col {
8914 let span_len = segment_start_col - cursor_col;
8915 output_runs.push(TextRun {
8916 len: span_len,
8917 font: text_run.font.clone(),
8918 color: text_run.color,
8919 background_color: text_run.background_color,
8920 underline: text_run.underline,
8921 strikethrough: text_run.strikethrough,
8922 });
8923 cursor_col = segment_start_col;
8924 }
8925 let segment_slice_end_col = segment_end_col.min(run_end_col);
8926 if segment_slice_end_col > cursor_col {
8927 let new_text_color =
8928 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
8929 output_runs.push(TextRun {
8930 len: segment_slice_end_col - cursor_col,
8931 font: text_run.font.clone(),
8932 color: new_text_color,
8933 background_color: text_run.background_color,
8934 underline: text_run.underline,
8935 strikethrough: text_run.strikethrough,
8936 });
8937 cursor_col = segment_slice_end_col;
8938 }
8939 if segment_end_col >= run_end_col {
8940 break;
8941 }
8942 local_segment_ix += 1;
8943 }
8944 if cursor_col < run_end_col {
8945 output_runs.push(TextRun {
8946 len: run_end_col - cursor_col,
8947 font: text_run.font.clone(),
8948 color: text_run.color,
8949 background_color: text_run.background_color,
8950 underline: text_run.underline,
8951 strikethrough: text_run.strikethrough,
8952 });
8953 }
8954 line_col = run_end_col;
8955 segment_ix = local_segment_ix;
8956 }
8957 output_runs
8958 }
8959
8960 fn prepaint(
8961 &mut self,
8962 line_height: Pixels,
8963 scroll_position: gpui::Point<ScrollOffset>,
8964 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8965 row: DisplayRow,
8966 content_origin: gpui::Point<Pixels>,
8967 line_elements: &mut SmallVec<[AnyElement; 1]>,
8968 window: &mut Window,
8969 cx: &mut App,
8970 ) {
8971 let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
8972 self.prepaint_with_custom_offset(
8973 line_height,
8974 scroll_pixel_position,
8975 content_origin,
8976 line_y,
8977 line_elements,
8978 window,
8979 cx,
8980 );
8981 }
8982
8983 fn prepaint_with_custom_offset(
8984 &mut self,
8985 line_height: Pixels,
8986 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8987 content_origin: gpui::Point<Pixels>,
8988 line_y: Pixels,
8989 line_elements: &mut SmallVec<[AnyElement; 1]>,
8990 window: &mut Window,
8991 cx: &mut App,
8992 ) {
8993 let mut fragment_origin =
8994 content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
8995 for fragment in &mut self.fragments {
8996 match fragment {
8997 LineFragment::Text(line) => {
8998 fragment_origin.x += line.width;
8999 }
9000 LineFragment::Element { element, size, .. } => {
9001 let mut element = element
9002 .take()
9003 .expect("you can't prepaint LineWithInvisibles twice");
9004
9005 // Center the element vertically within the line.
9006 let mut element_origin = fragment_origin;
9007 element_origin.y += (line_height - size.height) / 2.;
9008 element.prepaint_at(element_origin, window, cx);
9009 line_elements.push(element);
9010
9011 fragment_origin.x += size.width;
9012 }
9013 }
9014 }
9015 }
9016
9017 fn draw(
9018 &self,
9019 layout: &EditorLayout,
9020 row: DisplayRow,
9021 content_origin: gpui::Point<Pixels>,
9022 whitespace_setting: ShowWhitespaceSetting,
9023 selection_ranges: &[Range<DisplayPoint>],
9024 window: &mut Window,
9025 cx: &mut App,
9026 ) {
9027 self.draw_with_custom_offset(
9028 layout,
9029 row,
9030 content_origin,
9031 layout.position_map.line_height
9032 * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
9033 whitespace_setting,
9034 selection_ranges,
9035 window,
9036 cx,
9037 );
9038 }
9039
9040 fn draw_with_custom_offset(
9041 &self,
9042 layout: &EditorLayout,
9043 row: DisplayRow,
9044 content_origin: gpui::Point<Pixels>,
9045 line_y: Pixels,
9046 whitespace_setting: ShowWhitespaceSetting,
9047 selection_ranges: &[Range<DisplayPoint>],
9048 window: &mut Window,
9049 cx: &mut App,
9050 ) {
9051 let line_height = layout.position_map.line_height;
9052 let mut fragment_origin = content_origin
9053 + gpui::point(
9054 Pixels::from(-layout.position_map.scroll_pixel_position.x),
9055 line_y,
9056 );
9057
9058 for fragment in &self.fragments {
9059 match fragment {
9060 LineFragment::Text(line) => {
9061 line.paint(
9062 fragment_origin,
9063 line_height,
9064 layout.text_align,
9065 Some(layout.content_width),
9066 window,
9067 cx,
9068 )
9069 .log_err();
9070 fragment_origin.x += line.width;
9071 }
9072 LineFragment::Element { size, .. } => {
9073 fragment_origin.x += size.width;
9074 }
9075 }
9076 }
9077
9078 self.draw_invisibles(
9079 selection_ranges,
9080 layout,
9081 content_origin,
9082 line_y,
9083 row,
9084 line_height,
9085 whitespace_setting,
9086 window,
9087 cx,
9088 );
9089 }
9090
9091 fn draw_background(
9092 &self,
9093 layout: &EditorLayout,
9094 row: DisplayRow,
9095 content_origin: gpui::Point<Pixels>,
9096 window: &mut Window,
9097 cx: &mut App,
9098 ) {
9099 let line_height = layout.position_map.line_height;
9100 let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
9101
9102 let mut fragment_origin = content_origin
9103 + gpui::point(
9104 Pixels::from(-layout.position_map.scroll_pixel_position.x),
9105 line_y,
9106 );
9107
9108 for fragment in &self.fragments {
9109 match fragment {
9110 LineFragment::Text(line) => {
9111 line.paint_background(
9112 fragment_origin,
9113 line_height,
9114 layout.text_align,
9115 Some(layout.content_width),
9116 window,
9117 cx,
9118 )
9119 .log_err();
9120 fragment_origin.x += line.width;
9121 }
9122 LineFragment::Element { size, .. } => {
9123 fragment_origin.x += size.width;
9124 }
9125 }
9126 }
9127 }
9128
9129 fn draw_invisibles(
9130 &self,
9131 selection_ranges: &[Range<DisplayPoint>],
9132 layout: &EditorLayout,
9133 content_origin: gpui::Point<Pixels>,
9134 line_y: Pixels,
9135 row: DisplayRow,
9136 line_height: Pixels,
9137 whitespace_setting: ShowWhitespaceSetting,
9138 window: &mut Window,
9139 cx: &mut App,
9140 ) {
9141 let extract_whitespace_info = |invisible: &Invisible| {
9142 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
9143 Invisible::Tab {
9144 line_start_offset,
9145 line_end_offset,
9146 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
9147 Invisible::Whitespace { line_offset } => {
9148 (*line_offset, line_offset + 1, &layout.space_invisible)
9149 }
9150 };
9151
9152 let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
9153 let invisible_offset: ScrollPixelOffset =
9154 ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
9155 .into();
9156 let origin = content_origin
9157 + gpui::point(
9158 Pixels::from(
9159 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
9160 ),
9161 line_y,
9162 );
9163
9164 (
9165 [token_offset, token_end_offset],
9166 Box::new(move |window: &mut Window, cx: &mut App| {
9167 invisible_symbol
9168 .paint(origin, line_height, TextAlign::Left, None, window, cx)
9169 .log_err();
9170 }),
9171 )
9172 };
9173
9174 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
9175 match whitespace_setting {
9176 ShowWhitespaceSetting::None => (),
9177 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
9178 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
9179 let invisible_point = DisplayPoint::new(row, start as u32);
9180 if !selection_ranges
9181 .iter()
9182 .any(|region| region.start <= invisible_point && invisible_point < region.end)
9183 {
9184 return;
9185 }
9186
9187 paint(window, cx);
9188 }),
9189
9190 ShowWhitespaceSetting::Trailing => {
9191 let mut previous_start = self.len;
9192 for ([start, end], paint) in invisible_iter.rev() {
9193 if previous_start != end {
9194 break;
9195 }
9196 previous_start = start;
9197 paint(window, cx);
9198 }
9199 }
9200
9201 // For a whitespace to be on a boundary, any of the following conditions need to be met:
9202 // - It is a tab
9203 // - It is adjacent to an edge (start or end)
9204 // - It is adjacent to a whitespace (left or right)
9205 ShowWhitespaceSetting::Boundary => {
9206 // 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
9207 // the above cases.
9208 // Note: We zip in the original `invisibles` to check for tab equality
9209 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
9210 for (([start, end], paint), invisible) in
9211 invisible_iter.zip_eq(self.invisibles.iter())
9212 {
9213 let should_render = match (&last_seen, invisible) {
9214 (_, Invisible::Tab { .. }) => true,
9215 (Some((_, last_end, _)), _) => *last_end == start,
9216 _ => false,
9217 };
9218
9219 if should_render || start == 0 || end == self.len {
9220 paint(window, cx);
9221
9222 // Since we are scanning from the left, we will skip over the first available whitespace that is part
9223 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
9224 if let Some((should_render_last, last_end, paint_last)) = last_seen {
9225 // Note that we need to make sure that the last one is actually adjacent
9226 if !should_render_last && last_end == start {
9227 paint_last(window, cx);
9228 }
9229 }
9230 }
9231
9232 // Manually render anything within a selection
9233 let invisible_point = DisplayPoint::new(row, start as u32);
9234 if selection_ranges.iter().any(|region| {
9235 region.start <= invisible_point && invisible_point < region.end
9236 }) {
9237 paint(window, cx);
9238 }
9239
9240 last_seen = Some((should_render, end, paint));
9241 }
9242 }
9243 }
9244 }
9245
9246 pub fn x_for_index(&self, index: usize) -> Pixels {
9247 let mut fragment_start_x = Pixels::ZERO;
9248 let mut fragment_start_index = 0;
9249
9250 for fragment in &self.fragments {
9251 match fragment {
9252 LineFragment::Text(shaped_line) => {
9253 let fragment_end_index = fragment_start_index + shaped_line.len;
9254 if index < fragment_end_index {
9255 return fragment_start_x
9256 + shaped_line.x_for_index(index - fragment_start_index);
9257 }
9258 fragment_start_x += shaped_line.width;
9259 fragment_start_index = fragment_end_index;
9260 }
9261 LineFragment::Element { len, size, .. } => {
9262 let fragment_end_index = fragment_start_index + len;
9263 if index < fragment_end_index {
9264 return fragment_start_x;
9265 }
9266 fragment_start_x += size.width;
9267 fragment_start_index = fragment_end_index;
9268 }
9269 }
9270 }
9271
9272 fragment_start_x
9273 }
9274
9275 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
9276 let mut fragment_start_x = Pixels::ZERO;
9277 let mut fragment_start_index = 0;
9278
9279 for fragment in &self.fragments {
9280 match fragment {
9281 LineFragment::Text(shaped_line) => {
9282 let fragment_end_x = fragment_start_x + shaped_line.width;
9283 if x < fragment_end_x {
9284 return Some(
9285 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
9286 );
9287 }
9288 fragment_start_x = fragment_end_x;
9289 fragment_start_index += shaped_line.len;
9290 }
9291 LineFragment::Element { len, size, .. } => {
9292 let fragment_end_x = fragment_start_x + size.width;
9293 if x < fragment_end_x {
9294 return Some(fragment_start_index);
9295 }
9296 fragment_start_index += len;
9297 fragment_start_x = fragment_end_x;
9298 }
9299 }
9300 }
9301
9302 None
9303 }
9304
9305 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
9306 let mut fragment_start_index = 0;
9307
9308 for fragment in &self.fragments {
9309 match fragment {
9310 LineFragment::Text(shaped_line) => {
9311 let fragment_end_index = fragment_start_index + shaped_line.len;
9312 if index < fragment_end_index {
9313 return shaped_line.font_id_for_index(index - fragment_start_index);
9314 }
9315 fragment_start_index = fragment_end_index;
9316 }
9317 LineFragment::Element { len, .. } => {
9318 let fragment_end_index = fragment_start_index + len;
9319 if index < fragment_end_index {
9320 return None;
9321 }
9322 fragment_start_index = fragment_end_index;
9323 }
9324 }
9325 }
9326
9327 None
9328 }
9329
9330 pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
9331 let line_width = self.width;
9332 match text_align {
9333 TextAlign::Left => px(0.0),
9334 TextAlign::Center => (content_width - line_width) / 2.0,
9335 TextAlign::Right => content_width - line_width,
9336 }
9337 }
9338}
9339
9340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9341enum Invisible {
9342 /// A tab character
9343 ///
9344 /// A tab character is internally represented by spaces (configured by the user's tab width)
9345 /// aligned to the nearest column, so it's necessary to store the start and end offset for
9346 /// adjacency checks.
9347 Tab {
9348 line_start_offset: usize,
9349 line_end_offset: usize,
9350 },
9351 Whitespace {
9352 line_offset: usize,
9353 },
9354}
9355
9356impl EditorElement {
9357 /// Returns the rem size to use when rendering the [`EditorElement`].
9358 ///
9359 /// This allows UI elements to scale based on the `buffer_font_size`.
9360 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
9361 match self.editor.read(cx).mode {
9362 EditorMode::Full {
9363 scale_ui_elements_with_buffer_font_size: true,
9364 ..
9365 }
9366 | EditorMode::Minimap { .. } => {
9367 let buffer_font_size = self.style.text.font_size;
9368 match buffer_font_size {
9369 AbsoluteLength::Pixels(pixels) => {
9370 let rem_size_scale = {
9371 // Our default UI font size is 14px on a 16px base scale.
9372 // This means the default UI font size is 0.875rems.
9373 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
9374
9375 // We then determine the delta between a single rem and the default font
9376 // size scale.
9377 let default_font_size_delta = 1. - default_font_size_scale;
9378
9379 // Finally, we add this delta to 1rem to get the scale factor that
9380 // should be used to scale up the UI.
9381 1. + default_font_size_delta
9382 };
9383
9384 Some(pixels * rem_size_scale)
9385 }
9386 AbsoluteLength::Rems(rems) => {
9387 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
9388 }
9389 }
9390 }
9391 // We currently use single-line and auto-height editors in UI contexts,
9392 // so we don't want to scale everything with the buffer font size, as it
9393 // ends up looking off.
9394 _ => None,
9395 }
9396 }
9397
9398 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
9399 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
9400 parent.upgrade()
9401 } else {
9402 Some(self.editor.clone())
9403 }
9404 }
9405}
9406
9407#[derive(Default)]
9408pub struct EditorRequestLayoutState {
9409 // We use prepaint depth to limit the number of times prepaint is
9410 // called recursively. We need this so that we can update stale
9411 // data for e.g. block heights in block map.
9412 prepaint_depth: Rc<Cell<usize>>,
9413}
9414
9415impl EditorRequestLayoutState {
9416 // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
9417 // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
9418 // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
9419 // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
9420 // that subsequent shrinking does not lead to incorrect block placing.
9421 const MAX_PREPAINT_DEPTH: usize = 5;
9422
9423 fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
9424 let depth = self.prepaint_depth.get();
9425 self.prepaint_depth.set(depth + 1);
9426 EditorPrepaintGuard {
9427 prepaint_depth: self.prepaint_depth.clone(),
9428 }
9429 }
9430
9431 fn can_prepaint(&self) -> bool {
9432 self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
9433 }
9434}
9435
9436struct EditorPrepaintGuard {
9437 prepaint_depth: Rc<Cell<usize>>,
9438}
9439
9440impl Drop for EditorPrepaintGuard {
9441 fn drop(&mut self) {
9442 let depth = self.prepaint_depth.get();
9443 self.prepaint_depth.set(depth.saturating_sub(1));
9444 }
9445}
9446
9447impl Element for EditorElement {
9448 type RequestLayoutState = EditorRequestLayoutState;
9449 type PrepaintState = EditorLayout;
9450
9451 fn id(&self) -> Option<ElementId> {
9452 None
9453 }
9454
9455 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
9456 None
9457 }
9458
9459 fn request_layout(
9460 &mut self,
9461 _: Option<&GlobalElementId>,
9462 _inspector_id: Option<&gpui::InspectorElementId>,
9463 window: &mut Window,
9464 cx: &mut App,
9465 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
9466 let rem_size = self.rem_size(cx);
9467 window.with_rem_size(rem_size, |window| {
9468 self.editor.update(cx, |editor, cx| {
9469 editor.set_style(self.style.clone(), window, cx);
9470
9471 let layout_id = match editor.mode {
9472 EditorMode::SingleLine => {
9473 let rem_size = window.rem_size();
9474 let height = self.style.text.line_height_in_pixels(rem_size);
9475 let mut style = Style::default();
9476 style.size.height = height.into();
9477 style.size.width = relative(1.).into();
9478 window.request_layout(style, None, cx)
9479 }
9480 EditorMode::AutoHeight {
9481 min_lines,
9482 max_lines,
9483 } => {
9484 let editor_handle = cx.entity();
9485 window.request_measured_layout(
9486 Style::default(),
9487 move |known_dimensions, available_space, window, cx| {
9488 editor_handle
9489 .update(cx, |editor, cx| {
9490 compute_auto_height_layout(
9491 editor,
9492 min_lines,
9493 max_lines,
9494 known_dimensions,
9495 available_space.width,
9496 window,
9497 cx,
9498 )
9499 })
9500 .unwrap_or_default()
9501 },
9502 )
9503 }
9504 EditorMode::Minimap { .. } => {
9505 let mut style = Style::default();
9506 style.size.width = relative(1.).into();
9507 style.size.height = relative(1.).into();
9508 window.request_layout(style, None, cx)
9509 }
9510 EditorMode::Full {
9511 sizing_behavior, ..
9512 } => {
9513 let mut style = Style::default();
9514 style.size.width = relative(1.).into();
9515 if sizing_behavior == SizingBehavior::SizeByContent {
9516 let snapshot = editor.snapshot(window, cx);
9517 let line_height =
9518 self.style.text.line_height_in_pixels(window.rem_size());
9519 let scroll_height =
9520 (snapshot.max_point().row().next_row().0 as f32) * line_height;
9521 style.size.height = scroll_height.into();
9522 } else {
9523 style.size.height = relative(1.).into();
9524 }
9525 window.request_layout(style, None, cx)
9526 }
9527 };
9528
9529 (layout_id, EditorRequestLayoutState::default())
9530 })
9531 })
9532 }
9533
9534 fn prepaint(
9535 &mut self,
9536 _: Option<&GlobalElementId>,
9537 _inspector_id: Option<&gpui::InspectorElementId>,
9538 bounds: Bounds<Pixels>,
9539 request_layout: &mut Self::RequestLayoutState,
9540 window: &mut Window,
9541 cx: &mut App,
9542 ) -> Self::PrepaintState {
9543 let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
9544 let text_style = TextStyleRefinement {
9545 font_size: Some(self.style.text.font_size),
9546 line_height: Some(self.style.text.line_height),
9547 ..Default::default()
9548 };
9549
9550 let is_minimap = self.editor.read(cx).mode.is_minimap();
9551 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
9552
9553 if !is_minimap {
9554 let focus_handle = self.editor.focus_handle(cx);
9555 window.set_view_id(self.editor.entity_id());
9556 window.set_focus_handle(&focus_handle, cx);
9557 }
9558
9559 let rem_size = self.rem_size(cx);
9560 window.with_rem_size(rem_size, |window| {
9561 window.with_text_style(Some(text_style), |window| {
9562 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9563 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
9564 (editor.snapshot(window, cx), editor.read_only(cx))
9565 });
9566 let style = &self.style;
9567
9568 let rem_size = window.rem_size();
9569 let font_id = window.text_system().resolve_font(&style.text.font());
9570 let font_size = style.text.font_size.to_pixels(rem_size);
9571 let line_height = style.text.line_height_in_pixels(rem_size);
9572 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
9573 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
9574 let em_layout_width = window.text_system().em_layout_width(font_id, font_size);
9575 let glyph_grid_cell = size(em_advance, line_height);
9576
9577 let gutter_dimensions =
9578 snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
9579 let text_width = bounds.size.width - gutter_dimensions.width;
9580
9581 let settings = EditorSettings::get_global(cx);
9582 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
9583 let vertical_scrollbar_width = (scrollbars_shown
9584 && settings.scrollbar.axes.vertical
9585 && self.editor.read(cx).show_scrollbars.vertical)
9586 .then_some(style.scrollbar_width)
9587 .unwrap_or_default();
9588 let minimap_width = self
9589 .get_minimap_width(
9590 &settings.minimap,
9591 scrollbars_shown,
9592 text_width,
9593 em_width,
9594 font_size,
9595 rem_size,
9596 cx,
9597 )
9598 .unwrap_or_default();
9599
9600 let right_margin = minimap_width + vertical_scrollbar_width;
9601
9602 let extended_right = 2 * em_width + right_margin;
9603 let editor_width = text_width - gutter_dimensions.margin - extended_right;
9604 let editor_margins = EditorMargins {
9605 gutter: gutter_dimensions,
9606 right: right_margin,
9607 extended_right,
9608 };
9609
9610 snapshot = self.editor.update(cx, |editor, cx| {
9611 editor.last_bounds = Some(bounds);
9612 editor.gutter_dimensions = gutter_dimensions;
9613 editor.set_visible_line_count(
9614 (bounds.size.height / line_height) as f64,
9615 window,
9616 cx,
9617 );
9618 editor.set_visible_column_count(f64::from(editor_width / em_advance));
9619
9620 if matches!(
9621 editor.mode,
9622 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
9623 ) {
9624 snapshot
9625 } else {
9626 let wrap_width = calculate_wrap_width(
9627 editor.soft_wrap_mode(cx),
9628 editor_width,
9629 em_layout_width,
9630 );
9631
9632 if editor.set_wrap_width(wrap_width, cx) {
9633 editor.snapshot(window, cx)
9634 } else {
9635 snapshot
9636 }
9637 }
9638 });
9639
9640 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
9641 let gutter_hitbox = window.insert_hitbox(
9642 gutter_bounds(bounds, gutter_dimensions),
9643 HitboxBehavior::Normal,
9644 );
9645 let text_hitbox = window.insert_hitbox(
9646 Bounds {
9647 origin: gutter_hitbox.top_right(),
9648 size: size(text_width, bounds.size.height),
9649 },
9650 HitboxBehavior::Normal,
9651 );
9652
9653 // Offset the content_bounds from the text_bounds by the gutter margin (which
9654 // is roughly half a character wide) to make hit testing work more like how we want.
9655 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
9656 let content_origin = text_hitbox.origin + content_offset;
9657
9658 let height_in_lines = f64::from(bounds.size.height / line_height);
9659 let max_row = snapshot.max_point().row().as_f64();
9660
9661 // Calculate how much of the editor is clipped by parent containers (e.g., List).
9662 // This allows us to only render lines that are actually visible, which is
9663 // critical for performance when large AutoHeight editors are inside Lists.
9664 let visible_bounds = window.content_mask().bounds;
9665 let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
9666 let clipped_top_in_lines = f64::from(clipped_top / line_height);
9667 let visible_height_in_lines =
9668 f64::from(visible_bounds.size.height / line_height);
9669
9670 // The max scroll position for the top of the window
9671 let max_scroll_top = if matches!(
9672 snapshot.mode,
9673 EditorMode::SingleLine
9674 | EditorMode::AutoHeight { .. }
9675 | EditorMode::Full {
9676 sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
9677 | SizingBehavior::SizeByContent,
9678 ..
9679 }
9680 ) {
9681 (max_row - height_in_lines + 1.).max(0.)
9682 } else {
9683 let settings = EditorSettings::get_global(cx);
9684 match settings.scroll_beyond_last_line {
9685 ScrollBeyondLastLine::OnePage => max_row,
9686 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
9687 ScrollBeyondLastLine::VerticalScrollMargin => {
9688 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
9689 .max(0.)
9690 }
9691 }
9692 };
9693
9694 let (
9695 autoscroll_request,
9696 autoscroll_containing_element,
9697 needs_horizontal_autoscroll,
9698 ) = self.editor.update(cx, |editor, cx| {
9699 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
9700
9701 let autoscroll_containing_element =
9702 autoscroll_request.is_some() || editor.has_pending_selection();
9703
9704 let (needs_horizontal_autoscroll, was_scrolled) = editor
9705 .autoscroll_vertically(
9706 bounds,
9707 line_height,
9708 max_scroll_top,
9709 autoscroll_request,
9710 window,
9711 cx,
9712 );
9713 if was_scrolled.0 {
9714 snapshot = editor.snapshot(window, cx);
9715 }
9716 (
9717 autoscroll_request,
9718 autoscroll_containing_element,
9719 needs_horizontal_autoscroll,
9720 )
9721 });
9722
9723 let mut scroll_position = snapshot.scroll_position();
9724 // The scroll position is a fractional point, the whole number of which represents
9725 // the top of the window in terms of display rows.
9726 // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
9727 // but we don't modify scroll_position itself since the parent handles positioning.
9728 let max_row = snapshot.max_point().row();
9729 let start_row = cmp::min(
9730 DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
9731 max_row,
9732 );
9733 let end_row = cmp::min(
9734 (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
9735 as u32,
9736 max_row.next_row().0,
9737 );
9738 let end_row = DisplayRow(end_row);
9739
9740 let row_infos = snapshot // note we only get the visual range
9741 .row_infos(start_row)
9742 .take((start_row..end_row).len())
9743 .collect::<Vec<RowInfo>>();
9744 let is_row_soft_wrapped = |row: usize| {
9745 row_infos
9746 .get(row)
9747 .is_none_or(|info| info.buffer_row.is_none())
9748 };
9749
9750 let start_anchor = if start_row == Default::default() {
9751 Anchor::min()
9752 } else {
9753 snapshot.buffer_snapshot().anchor_before(
9754 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
9755 )
9756 };
9757 let end_anchor = if end_row > max_row {
9758 Anchor::max()
9759 } else {
9760 snapshot.buffer_snapshot().anchor_before(
9761 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
9762 )
9763 };
9764
9765 let mut highlighted_rows = self
9766 .editor
9767 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
9768
9769 let is_light = cx.theme().appearance().is_light();
9770
9771 let mut highlighted_ranges = self
9772 .editor_with_selections(cx)
9773 .map(|editor| {
9774 editor.read(cx).background_highlights_in_range(
9775 start_anchor..end_anchor,
9776 &snapshot.display_snapshot,
9777 cx.theme(),
9778 )
9779 })
9780 .unwrap_or_default();
9781
9782 for (ix, row_info) in row_infos.iter().enumerate() {
9783 let Some(diff_status) = row_info.diff_status else {
9784 continue;
9785 };
9786
9787 let background_color = match diff_status.kind {
9788 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
9789 DiffHunkStatusKind::Deleted => {
9790 cx.theme().colors().version_control_deleted
9791 }
9792 DiffHunkStatusKind::Modified => {
9793 debug_panic!("modified diff status for row info");
9794 continue;
9795 }
9796 };
9797
9798 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
9799
9800 let hollow_highlight = LineHighlight {
9801 background: (background_color.opacity(if is_light {
9802 0.08
9803 } else {
9804 0.06
9805 }))
9806 .into(),
9807 border: Some(if is_light {
9808 background_color.opacity(0.48)
9809 } else {
9810 background_color.opacity(0.36)
9811 }),
9812 include_gutter: true,
9813 type_id: None,
9814 };
9815
9816 let filled_highlight = LineHighlight {
9817 background: solid_background(background_color.opacity(hunk_opacity)),
9818 border: None,
9819 include_gutter: true,
9820 type_id: None,
9821 };
9822
9823 let background = if Self::diff_hunk_hollow(diff_status, cx) {
9824 hollow_highlight
9825 } else {
9826 filled_highlight
9827 };
9828
9829 let base_display_point =
9830 DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
9831
9832 highlighted_rows
9833 .entry(base_display_point.row())
9834 .or_insert(background);
9835 }
9836
9837 // Add diff review drag selection highlight to text area
9838 if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
9839 let range = drag_state.row_range(&snapshot.display_snapshot);
9840 let start_row = range.start().0;
9841 let end_row = range.end().0;
9842 let drag_highlight_color =
9843 cx.theme().colors().editor_active_line_background;
9844 let drag_highlight = LineHighlight {
9845 background: solid_background(drag_highlight_color),
9846 border: Some(cx.theme().colors().border_focused),
9847 include_gutter: true,
9848 type_id: None,
9849 };
9850 for row_num in start_row..=end_row {
9851 highlighted_rows
9852 .entry(DisplayRow(row_num))
9853 .or_insert(drag_highlight);
9854 }
9855 }
9856
9857 let highlighted_gutter_ranges =
9858 self.editor.read(cx).gutter_highlights_in_range(
9859 start_anchor..end_anchor,
9860 &snapshot.display_snapshot,
9861 cx,
9862 );
9863
9864 let document_colors = self
9865 .editor
9866 .read(cx)
9867 .colors
9868 .as_ref()
9869 .map(|colors| colors.editor_display_highlights(&snapshot));
9870 let redacted_ranges = self.editor.read(cx).redacted_ranges(
9871 start_anchor..end_anchor,
9872 &snapshot.display_snapshot,
9873 cx,
9874 );
9875
9876 let (local_selections, selected_buffer_ids, latest_selection_anchors): (
9877 Vec<Selection<Point>>,
9878 Vec<BufferId>,
9879 HashMap<BufferId, Anchor>,
9880 ) = self
9881 .editor_with_selections(cx)
9882 .map(|editor| {
9883 editor.update(cx, |editor, cx| {
9884 let all_selections =
9885 editor.selections.all::<Point>(&snapshot.display_snapshot);
9886 let all_anchor_selections =
9887 editor.selections.all_anchors(&snapshot.display_snapshot);
9888 let selected_buffer_ids =
9889 if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
9890 Vec::new()
9891 } else {
9892 let mut selected_buffer_ids =
9893 Vec::with_capacity(all_selections.len());
9894
9895 for selection in all_selections {
9896 for buffer_id in snapshot
9897 .buffer_snapshot()
9898 .buffer_ids_for_range(selection.range())
9899 {
9900 if selected_buffer_ids.last() != Some(&buffer_id) {
9901 selected_buffer_ids.push(buffer_id);
9902 }
9903 }
9904 }
9905
9906 selected_buffer_ids
9907 };
9908
9909 let mut selections = editor.selections.disjoint_in_range(
9910 start_anchor..end_anchor,
9911 &snapshot.display_snapshot,
9912 );
9913 selections
9914 .extend(editor.selections.pending(&snapshot.display_snapshot));
9915
9916 let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
9917 HashMap::default();
9918 for selection in all_anchor_selections.iter() {
9919 let head = selection.head();
9920 if let Some(buffer_id) = head.text_anchor.buffer_id {
9921 anchors_by_buffer
9922 .entry(buffer_id)
9923 .and_modify(|(latest_id, latest_anchor)| {
9924 if selection.id > *latest_id {
9925 *latest_id = selection.id;
9926 *latest_anchor = head;
9927 }
9928 })
9929 .or_insert((selection.id, head));
9930 }
9931 }
9932 let latest_selection_anchors = anchors_by_buffer
9933 .into_iter()
9934 .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
9935 .collect();
9936
9937 (selections, selected_buffer_ids, latest_selection_anchors)
9938 })
9939 })
9940 .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
9941
9942 let (selections, mut active_rows, newest_selection_head) = self
9943 .layout_selections(
9944 start_anchor,
9945 end_anchor,
9946 &local_selections,
9947 &snapshot,
9948 start_row,
9949 end_row,
9950 window,
9951 cx,
9952 );
9953
9954 // relative rows are based on newest selection, even outside the visible area
9955 let current_selection_head = self.editor.update(cx, |editor, cx| {
9956 (editor.selections.count() != 0).then(|| {
9957 let newest = editor
9958 .selections
9959 .newest::<Point>(&editor.display_snapshot(cx));
9960
9961 SelectionLayout::new(
9962 newest,
9963 editor.selections.line_mode(),
9964 editor.cursor_offset_on_selection,
9965 editor.cursor_shape,
9966 &snapshot,
9967 true,
9968 true,
9969 None,
9970 )
9971 .head
9972 .row()
9973 })
9974 });
9975
9976 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
9977 editor.active_breakpoints(start_row..end_row, window, cx)
9978 });
9979 for (display_row, (_, bp, state)) in &breakpoint_rows {
9980 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
9981 active_rows.entry(*display_row).or_default().breakpoint = true;
9982 }
9983 }
9984
9985 let line_numbers = self.layout_line_numbers(
9986 Some(&gutter_hitbox),
9987 gutter_dimensions,
9988 line_height,
9989 scroll_position,
9990 start_row..end_row,
9991 &row_infos,
9992 &active_rows,
9993 current_selection_head,
9994 &snapshot,
9995 window,
9996 cx,
9997 );
9998
9999 // We add the gutter breakpoint indicator to breakpoint_rows after painting
10000 // line numbers so we don't paint a line number debug accent color if a user
10001 // has their mouse over that line when a breakpoint isn't there
10002 self.editor.update(cx, |editor, _| {
10003 if let Some(phantom_breakpoint) = &mut editor
10004 .gutter_breakpoint_indicator
10005 .0
10006 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
10007 {
10008 // Is there a non-phantom breakpoint on this line?
10009 phantom_breakpoint.collides_with_existing_breakpoint = true;
10010 breakpoint_rows
10011 .entry(phantom_breakpoint.display_row)
10012 .or_insert_with(|| {
10013 let position = snapshot.display_point_to_anchor(
10014 DisplayPoint::new(phantom_breakpoint.display_row, 0),
10015 Bias::Right,
10016 );
10017 let breakpoint = Breakpoint::new_standard();
10018 phantom_breakpoint.collides_with_existing_breakpoint = false;
10019 (position, breakpoint, None)
10020 });
10021 }
10022 });
10023
10024 let mut expand_toggles =
10025 window.with_element_namespace("expand_toggles", |window| {
10026 self.layout_expand_toggles(
10027 &gutter_hitbox,
10028 gutter_dimensions,
10029 em_width,
10030 line_height,
10031 scroll_position,
10032 &row_infos,
10033 window,
10034 cx,
10035 )
10036 });
10037
10038 let mut crease_toggles =
10039 window.with_element_namespace("crease_toggles", |window| {
10040 self.layout_crease_toggles(
10041 start_row..end_row,
10042 &row_infos,
10043 &active_rows,
10044 &snapshot,
10045 window,
10046 cx,
10047 )
10048 });
10049 let crease_trailers =
10050 window.with_element_namespace("crease_trailers", |window| {
10051 self.layout_crease_trailers(
10052 row_infos.iter().cloned(),
10053 &snapshot,
10054 window,
10055 cx,
10056 )
10057 });
10058
10059 let display_hunks = self.layout_gutter_diff_hunks(
10060 line_height,
10061 &gutter_hitbox,
10062 start_row..end_row,
10063 &snapshot,
10064 window,
10065 cx,
10066 );
10067
10068 Self::layout_word_diff_highlights(
10069 &display_hunks,
10070 &row_infos,
10071 start_row,
10072 &snapshot,
10073 &mut highlighted_ranges,
10074 cx,
10075 );
10076
10077 let merged_highlighted_ranges =
10078 if let Some((_, colors)) = document_colors.as_ref() {
10079 &highlighted_ranges
10080 .clone()
10081 .into_iter()
10082 .chain(colors.clone())
10083 .collect()
10084 } else {
10085 &highlighted_ranges
10086 };
10087 let bg_segments_per_row = Self::bg_segments_per_row(
10088 start_row..end_row,
10089 &selections,
10090 &merged_highlighted_ranges,
10091 self.style.background,
10092 );
10093
10094 let mut line_layouts = Self::layout_lines(
10095 start_row..end_row,
10096 &snapshot,
10097 &self.style,
10098 editor_width,
10099 is_row_soft_wrapped,
10100 &bg_segments_per_row,
10101 window,
10102 cx,
10103 );
10104 let new_renderer_widths = (!is_minimap).then(|| {
10105 line_layouts
10106 .iter()
10107 .flat_map(|layout| &layout.fragments)
10108 .filter_map(|fragment| {
10109 if let LineFragment::Element { id, size, .. } = fragment {
10110 Some((*id, size.width))
10111 } else {
10112 None
10113 }
10114 })
10115 });
10116 if new_renderer_widths.is_some_and(|new_renderer_widths| {
10117 self.editor.update(cx, |editor, cx| {
10118 editor.update_renderer_widths(new_renderer_widths, cx)
10119 })
10120 }) {
10121 // If the fold widths have changed, we need to prepaint
10122 // the element again to account for any changes in
10123 // wrapping.
10124 if request_layout.can_prepaint() {
10125 return self.prepaint(
10126 None,
10127 _inspector_id,
10128 bounds,
10129 request_layout,
10130 window,
10131 cx,
10132 );
10133 } else {
10134 debug_panic!(concat!(
10135 "skipping recursive prepaint at max depth. ",
10136 "renderer widths may be stale."
10137 ));
10138 }
10139 }
10140
10141 let longest_line_blame_width = self
10142 .editor
10143 .update(cx, |editor, cx| {
10144 if !editor.show_git_blame_inline {
10145 return None;
10146 }
10147 let blame = editor.blame.as_ref()?;
10148 let (_, blame_entry) = blame
10149 .update(cx, |blame, cx| {
10150 let row_infos =
10151 snapshot.row_infos(snapshot.longest_row()).next()?;
10152 blame.blame_for_rows(&[row_infos], cx).next()
10153 })
10154 .flatten()?;
10155 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
10156 let inline_blame_padding =
10157 ProjectSettings::get_global(cx).git.inline_blame.padding as f32
10158 * em_advance;
10159 Some(
10160 element
10161 .layout_as_root(AvailableSpace::min_size(), window, cx)
10162 .width
10163 + inline_blame_padding,
10164 )
10165 })
10166 .unwrap_or(Pixels::ZERO);
10167
10168 let longest_line_width = layout_line(
10169 snapshot.longest_row(),
10170 &snapshot,
10171 style,
10172 editor_width,
10173 is_row_soft_wrapped,
10174 window,
10175 cx,
10176 )
10177 .width;
10178
10179 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
10180 text_hitbox.bounds,
10181 glyph_grid_cell,
10182 size(
10183 longest_line_width,
10184 Pixels::from(max_row.as_f64() * f64::from(line_height)),
10185 ),
10186 longest_line_blame_width,
10187 EditorSettings::get_global(cx),
10188 );
10189
10190 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
10191
10192 let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
10193 snapshot.sticky_header_excerpt(scroll_position.y)
10194 } else {
10195 None
10196 };
10197 let sticky_header_excerpt_id =
10198 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
10199
10200 let blocks = (!is_minimap)
10201 .then(|| {
10202 window.with_element_namespace("blocks", |window| {
10203 self.render_blocks(
10204 start_row..end_row,
10205 &snapshot,
10206 &hitbox,
10207 &text_hitbox,
10208 editor_width,
10209 &mut scroll_width,
10210 &editor_margins,
10211 em_width,
10212 gutter_dimensions.full_width(),
10213 line_height,
10214 &mut line_layouts,
10215 &local_selections,
10216 &selected_buffer_ids,
10217 &latest_selection_anchors,
10218 is_row_soft_wrapped,
10219 sticky_header_excerpt_id,
10220 window,
10221 cx,
10222 )
10223 })
10224 })
10225 .unwrap_or_default();
10226 let RenderBlocksOutput {
10227 mut blocks,
10228 row_block_types,
10229 resized_blocks,
10230 } = blocks;
10231 if let Some(resized_blocks) = resized_blocks {
10232 self.editor.update(cx, |editor, cx| {
10233 editor.resize_blocks(
10234 resized_blocks,
10235 autoscroll_request.map(|(autoscroll, _)| autoscroll),
10236 cx,
10237 )
10238 });
10239 if request_layout.can_prepaint() {
10240 return self.prepaint(
10241 None,
10242 _inspector_id,
10243 bounds,
10244 request_layout,
10245 window,
10246 cx,
10247 );
10248 } else {
10249 debug_panic!(concat!(
10250 "skipping recursive prepaint at max depth. ",
10251 "block layout may be stale."
10252 ));
10253 }
10254 }
10255
10256 let sticky_buffer_header = if self.should_show_buffer_headers() {
10257 sticky_header_excerpt.map(|sticky_header_excerpt| {
10258 window.with_element_namespace("blocks", |window| {
10259 self.layout_sticky_buffer_header(
10260 sticky_header_excerpt,
10261 scroll_position,
10262 line_height,
10263 right_margin,
10264 &snapshot,
10265 &hitbox,
10266 &selected_buffer_ids,
10267 &blocks,
10268 &latest_selection_anchors,
10269 window,
10270 cx,
10271 )
10272 })
10273 })
10274 } else {
10275 None
10276 };
10277
10278 let start_buffer_row =
10279 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot()).row);
10280 let end_buffer_row =
10281 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot()).row);
10282
10283 let scroll_max: gpui::Point<ScrollPixelOffset> = point(
10284 ScrollPixelOffset::from(
10285 ((scroll_width - editor_width) / em_layout_width).max(0.0),
10286 ),
10287 max_scroll_top,
10288 );
10289
10290 self.editor.update(cx, |editor, cx| {
10291 if editor.scroll_manager.clamp_scroll_left(scroll_max.x, cx) {
10292 scroll_position.x = scroll_max.x.min(scroll_position.x);
10293 }
10294
10295 if needs_horizontal_autoscroll.0
10296 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
10297 start_row,
10298 editor_width,
10299 scroll_width,
10300 em_advance,
10301 &line_layouts,
10302 autoscroll_request,
10303 window,
10304 cx,
10305 )
10306 {
10307 scroll_position = new_scroll_position;
10308 }
10309 });
10310
10311 let scroll_pixel_position = point(
10312 scroll_position.x * f64::from(em_layout_width),
10313 scroll_position.y * f64::from(line_height),
10314 );
10315 let sticky_headers = if !is_minimap
10316 && is_singleton
10317 && EditorSettings::get_global(cx).sticky_scroll.enabled
10318 {
10319 let relative = self.editor.read(cx).relative_line_numbers(cx);
10320 self.layout_sticky_headers(
10321 &snapshot,
10322 editor_width,
10323 is_row_soft_wrapped,
10324 line_height,
10325 scroll_pixel_position,
10326 content_origin,
10327 &gutter_dimensions,
10328 &gutter_hitbox,
10329 &text_hitbox,
10330 relative,
10331 current_selection_head,
10332 window,
10333 cx,
10334 )
10335 } else {
10336 None
10337 };
10338 self.editor.update(cx, |editor, _| {
10339 editor.scroll_manager.set_sticky_header_line_count(
10340 sticky_headers.as_ref().map_or(0, |h| h.lines.len()),
10341 );
10342 });
10343 let indent_guides = self.layout_indent_guides(
10344 content_origin,
10345 text_hitbox.origin,
10346 start_buffer_row..end_buffer_row,
10347 scroll_pixel_position,
10348 line_height,
10349 &snapshot,
10350 window,
10351 cx,
10352 );
10353
10354 let crease_trailers =
10355 window.with_element_namespace("crease_trailers", |window| {
10356 self.prepaint_crease_trailers(
10357 crease_trailers,
10358 &line_layouts,
10359 line_height,
10360 content_origin,
10361 scroll_pixel_position,
10362 em_width,
10363 window,
10364 cx,
10365 )
10366 });
10367
10368 let (edit_prediction_popover, edit_prediction_popover_origin) = self
10369 .editor
10370 .update(cx, |editor, cx| {
10371 editor.render_edit_prediction_popover(
10372 &text_hitbox.bounds,
10373 content_origin,
10374 right_margin,
10375 &snapshot,
10376 start_row..end_row,
10377 scroll_position.y,
10378 scroll_position.y + height_in_lines,
10379 &line_layouts,
10380 line_height,
10381 scroll_position,
10382 scroll_pixel_position,
10383 newest_selection_head,
10384 editor_width,
10385 style,
10386 window,
10387 cx,
10388 )
10389 })
10390 .unzip();
10391
10392 let mut inline_diagnostics = self.layout_inline_diagnostics(
10393 &line_layouts,
10394 &crease_trailers,
10395 &row_block_types,
10396 content_origin,
10397 scroll_position,
10398 scroll_pixel_position,
10399 edit_prediction_popover_origin,
10400 start_row,
10401 end_row,
10402 line_height,
10403 em_width,
10404 style,
10405 window,
10406 cx,
10407 );
10408
10409 let mut inline_blame_layout = None;
10410 let mut inline_code_actions = None;
10411 if let Some(newest_selection_head) = newest_selection_head {
10412 let display_row = newest_selection_head.row();
10413 if (start_row..end_row).contains(&display_row)
10414 && !row_block_types.contains_key(&display_row)
10415 {
10416 inline_code_actions = self.layout_inline_code_actions(
10417 newest_selection_head,
10418 content_origin,
10419 scroll_position,
10420 scroll_pixel_position,
10421 line_height,
10422 &snapshot,
10423 window,
10424 cx,
10425 );
10426
10427 let line_ix = display_row.minus(start_row) as usize;
10428 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10429 row_infos.get(line_ix),
10430 line_layouts.get(line_ix),
10431 crease_trailers.get(line_ix),
10432 ) {
10433 let crease_trailer_layout = crease_trailer.as_ref();
10434 if let Some(layout) = self.layout_inline_blame(
10435 display_row,
10436 row_info,
10437 line_layout,
10438 crease_trailer_layout,
10439 em_width,
10440 content_origin,
10441 scroll_position,
10442 scroll_pixel_position,
10443 line_height,
10444 window,
10445 cx,
10446 ) {
10447 inline_blame_layout = Some(layout);
10448 // Blame overrides inline diagnostics
10449 inline_diagnostics.remove(&display_row);
10450 }
10451 } else {
10452 log::error!(
10453 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10454 line_layouts.len(): {}, \
10455 crease_trailers.len(): {}",
10456 line_ix,
10457 row_infos.len(),
10458 line_layouts.len(),
10459 crease_trailers.len(),
10460 );
10461 }
10462 }
10463 }
10464
10465 let blamed_display_rows = self.layout_blame_entries(
10466 &row_infos,
10467 em_width,
10468 scroll_position,
10469 line_height,
10470 &gutter_hitbox,
10471 gutter_dimensions.git_blame_entries_width,
10472 window,
10473 cx,
10474 );
10475
10476 let line_elements = self.prepaint_lines(
10477 start_row,
10478 &mut line_layouts,
10479 line_height,
10480 scroll_position,
10481 scroll_pixel_position,
10482 content_origin,
10483 window,
10484 cx,
10485 );
10486
10487 window.with_element_namespace("blocks", |window| {
10488 self.layout_blocks(
10489 &mut blocks,
10490 &hitbox,
10491 &gutter_hitbox,
10492 line_height,
10493 scroll_position,
10494 scroll_pixel_position,
10495 window,
10496 cx,
10497 );
10498 });
10499
10500 let cursors = self.collect_cursors(&snapshot, cx);
10501 let visible_row_range = start_row..end_row;
10502 let non_visible_cursors = cursors
10503 .iter()
10504 .any(|c| !visible_row_range.contains(&c.0.row()));
10505
10506 let visible_cursors = self.layout_visible_cursors(
10507 &snapshot,
10508 &selections,
10509 &row_block_types,
10510 start_row..end_row,
10511 &line_layouts,
10512 &text_hitbox,
10513 content_origin,
10514 scroll_position,
10515 scroll_pixel_position,
10516 line_height,
10517 em_width,
10518 em_advance,
10519 autoscroll_containing_element,
10520 &redacted_ranges,
10521 window,
10522 cx,
10523 );
10524
10525 let scrollbars_layout = self.layout_scrollbars(
10526 &snapshot,
10527 &scrollbar_layout_information,
10528 content_offset,
10529 scroll_position,
10530 non_visible_cursors,
10531 right_margin,
10532 editor_width,
10533 window,
10534 cx,
10535 );
10536
10537 let gutter_settings = EditorSettings::get_global(cx).gutter;
10538
10539 let context_menu_layout =
10540 if let Some(newest_selection_head) = newest_selection_head {
10541 let newest_selection_point =
10542 newest_selection_head.to_point(&snapshot.display_snapshot);
10543 if (start_row..end_row).contains(&newest_selection_head.row()) {
10544 self.layout_cursor_popovers(
10545 line_height,
10546 &text_hitbox,
10547 content_origin,
10548 right_margin,
10549 start_row,
10550 scroll_pixel_position,
10551 &line_layouts,
10552 newest_selection_head,
10553 newest_selection_point,
10554 style,
10555 window,
10556 cx,
10557 )
10558 } else {
10559 None
10560 }
10561 } else {
10562 None
10563 };
10564
10565 self.layout_gutter_menu(
10566 line_height,
10567 &text_hitbox,
10568 content_origin,
10569 right_margin,
10570 scroll_pixel_position,
10571 gutter_dimensions.width - gutter_dimensions.left_padding,
10572 window,
10573 cx,
10574 );
10575
10576 let test_indicators = if gutter_settings.runnables {
10577 self.layout_run_indicators(
10578 line_height,
10579 start_row..end_row,
10580 &row_infos,
10581 scroll_position,
10582 &gutter_dimensions,
10583 &gutter_hitbox,
10584 &snapshot,
10585 &mut breakpoint_rows,
10586 window,
10587 cx,
10588 )
10589 } else {
10590 Vec::new()
10591 };
10592
10593 let show_breakpoints = snapshot
10594 .show_breakpoints
10595 .unwrap_or(gutter_settings.breakpoints);
10596 let breakpoints = if show_breakpoints {
10597 self.layout_breakpoints(
10598 line_height,
10599 start_row..end_row,
10600 scroll_position,
10601 &gutter_dimensions,
10602 &gutter_hitbox,
10603 &snapshot,
10604 breakpoint_rows,
10605 &row_infos,
10606 window,
10607 cx,
10608 )
10609 } else {
10610 Vec::new()
10611 };
10612
10613 let git_gutter_width = Self::gutter_strip_width(line_height)
10614 + gutter_dimensions
10615 .git_blame_entries_width
10616 .unwrap_or_default();
10617 let available_width = gutter_dimensions.left_padding - git_gutter_width;
10618
10619 let max_line_number_length = self
10620 .editor
10621 .read(cx)
10622 .buffer()
10623 .read(cx)
10624 .snapshot(cx)
10625 .widest_line_number()
10626 .ilog10()
10627 + 1;
10628
10629 let diff_review_button = self
10630 .should_render_diff_review_button(
10631 start_row..end_row,
10632 &row_infos,
10633 &snapshot,
10634 cx,
10635 )
10636 .map(|(display_row, buffer_row)| {
10637 let is_wide = max_line_number_length
10638 >= EditorSettings::get_global(cx).gutter.min_line_number_digits
10639 as u32
10640 && buffer_row.is_some_and(|row| {
10641 (row + 1).ilog10() + 1 == max_line_number_length
10642 })
10643 || gutter_dimensions.right_padding == px(0.);
10644
10645 let button_width = if is_wide {
10646 available_width - px(6.)
10647 } else {
10648 available_width + em_width - px(6.)
10649 };
10650
10651 let button = self.editor.update(cx, |editor, cx| {
10652 editor
10653 .render_diff_review_button(display_row, button_width, cx)
10654 .into_any_element()
10655 });
10656 prepaint_gutter_button(
10657 button,
10658 display_row,
10659 line_height,
10660 &gutter_dimensions,
10661 scroll_position,
10662 &gutter_hitbox,
10663 window,
10664 cx,
10665 )
10666 });
10667
10668 self.layout_signature_help(
10669 &hitbox,
10670 content_origin,
10671 scroll_pixel_position,
10672 newest_selection_head,
10673 start_row,
10674 &line_layouts,
10675 line_height,
10676 em_width,
10677 context_menu_layout,
10678 window,
10679 cx,
10680 );
10681
10682 if !cx.has_active_drag() {
10683 self.layout_hover_popovers(
10684 &snapshot,
10685 &hitbox,
10686 start_row..end_row,
10687 content_origin,
10688 scroll_pixel_position,
10689 &line_layouts,
10690 line_height,
10691 em_width,
10692 context_menu_layout,
10693 window,
10694 cx,
10695 );
10696
10697 self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10698 }
10699
10700 let mouse_context_menu = self.layout_mouse_context_menu(
10701 &snapshot,
10702 start_row..end_row,
10703 content_origin,
10704 window,
10705 cx,
10706 );
10707
10708 window.with_element_namespace("crease_toggles", |window| {
10709 self.prepaint_crease_toggles(
10710 &mut crease_toggles,
10711 line_height,
10712 &gutter_dimensions,
10713 gutter_settings,
10714 scroll_pixel_position,
10715 &gutter_hitbox,
10716 window,
10717 cx,
10718 )
10719 });
10720
10721 window.with_element_namespace("expand_toggles", |window| {
10722 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10723 });
10724
10725 let wrap_guides = self.layout_wrap_guides(
10726 em_advance,
10727 scroll_position,
10728 content_origin,
10729 scrollbars_layout.as_ref(),
10730 vertical_scrollbar_width,
10731 &hitbox,
10732 window,
10733 cx,
10734 );
10735
10736 let minimap = window.with_element_namespace("minimap", |window| {
10737 self.layout_minimap(
10738 &snapshot,
10739 minimap_width,
10740 scroll_position,
10741 &scrollbar_layout_information,
10742 scrollbars_layout.as_ref(),
10743 window,
10744 cx,
10745 )
10746 });
10747
10748 let invisible_symbol_font_size = font_size / 2.;
10749 let whitespace_map = &self
10750 .editor
10751 .read(cx)
10752 .buffer
10753 .read(cx)
10754 .language_settings(cx)
10755 .whitespace_map;
10756
10757 let tab_char = whitespace_map.tab.clone();
10758 let tab_len = tab_char.len();
10759 let tab_invisible = window.text_system().shape_line(
10760 tab_char,
10761 invisible_symbol_font_size,
10762 &[TextRun {
10763 len: tab_len,
10764 font: self.style.text.font(),
10765 color: cx.theme().colors().editor_invisible,
10766 ..Default::default()
10767 }],
10768 None,
10769 );
10770
10771 let space_char = whitespace_map.space.clone();
10772 let space_len = space_char.len();
10773 let space_invisible = window.text_system().shape_line(
10774 space_char,
10775 invisible_symbol_font_size,
10776 &[TextRun {
10777 len: space_len,
10778 font: self.style.text.font(),
10779 color: cx.theme().colors().editor_invisible,
10780 ..Default::default()
10781 }],
10782 None,
10783 );
10784
10785 let mode = snapshot.mode.clone();
10786
10787 let sticky_scroll_header_height = sticky_headers
10788 .as_ref()
10789 .and_then(|headers| headers.lines.last())
10790 .map_or(Pixels::ZERO, |last| last.offset + line_height);
10791
10792 let sticky_header_height = if sticky_buffer_header.is_some() {
10793 let full_height = FILE_HEADER_HEIGHT as f32 * line_height;
10794 let display_row = blocks
10795 .iter()
10796 .filter(|block| block.is_buffer_header)
10797 .find_map(|block| {
10798 block.row.filter(|row| row.0 > scroll_position.y as u32)
10799 });
10800 let offset = match display_row {
10801 Some(display_row) => {
10802 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
10803 let offset = (scroll_position.y - max_row as f64).max(0.0);
10804 let slide_up =
10805 Pixels::from(offset * ScrollPixelOffset::from(line_height));
10806
10807 (full_height - slide_up).max(Pixels::ZERO)
10808 }
10809 None => full_height,
10810 };
10811 sticky_scroll_header_height + offset
10812 } else {
10813 sticky_scroll_header_height
10814 };
10815
10816 let (diff_hunk_controls, diff_hunk_control_bounds) =
10817 if is_read_only && !self.editor.read(cx).delegate_stage_and_restore {
10818 (vec![], vec![])
10819 } else {
10820 self.layout_diff_hunk_controls(
10821 start_row..end_row,
10822 &row_infos,
10823 &text_hitbox,
10824 current_selection_head,
10825 line_height,
10826 right_margin,
10827 scroll_pixel_position,
10828 sticky_header_height,
10829 &display_hunks,
10830 &highlighted_rows,
10831 self.editor.clone(),
10832 window,
10833 cx,
10834 )
10835 };
10836
10837 let position_map = Rc::new(PositionMap {
10838 size: bounds.size,
10839 visible_row_range,
10840 scroll_position,
10841 scroll_pixel_position,
10842 scroll_max,
10843 line_layouts,
10844 line_height,
10845 em_width,
10846 em_advance,
10847 em_layout_width,
10848 snapshot,
10849 text_align: self.style.text.text_align,
10850 content_width: text_hitbox.size.width,
10851 gutter_hitbox: gutter_hitbox.clone(),
10852 text_hitbox: text_hitbox.clone(),
10853 inline_blame_bounds: inline_blame_layout
10854 .as_ref()
10855 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
10856 display_hunks: display_hunks.clone(),
10857 diff_hunk_control_bounds,
10858 });
10859
10860 self.editor.update(cx, |editor, _| {
10861 editor.last_position_map = Some(position_map.clone())
10862 });
10863
10864 EditorLayout {
10865 mode,
10866 position_map,
10867 visible_display_row_range: start_row..end_row,
10868 wrap_guides,
10869 indent_guides,
10870 hitbox,
10871 gutter_hitbox,
10872 display_hunks,
10873 content_origin,
10874 scrollbars_layout,
10875 minimap,
10876 active_rows,
10877 highlighted_rows,
10878 highlighted_ranges,
10879 highlighted_gutter_ranges,
10880 redacted_ranges,
10881 document_colors,
10882 line_elements,
10883 line_numbers,
10884 blamed_display_rows,
10885 inline_diagnostics,
10886 inline_blame_layout,
10887 inline_code_actions,
10888 blocks,
10889 cursors,
10890 visible_cursors,
10891 selections,
10892 edit_prediction_popover,
10893 diff_hunk_controls,
10894 mouse_context_menu,
10895 test_indicators,
10896 breakpoints,
10897 diff_review_button,
10898 crease_toggles,
10899 crease_trailers,
10900 tab_invisible,
10901 space_invisible,
10902 sticky_buffer_header,
10903 sticky_headers,
10904 expand_toggles,
10905 text_align: self.style.text.text_align,
10906 content_width: text_hitbox.size.width,
10907 }
10908 })
10909 })
10910 })
10911 }
10912
10913 fn paint(
10914 &mut self,
10915 _: Option<&GlobalElementId>,
10916 _inspector_id: Option<&gpui::InspectorElementId>,
10917 bounds: Bounds<gpui::Pixels>,
10918 _: &mut Self::RequestLayoutState,
10919 layout: &mut Self::PrepaintState,
10920 window: &mut Window,
10921 cx: &mut App,
10922 ) {
10923 if !layout.mode.is_minimap() {
10924 let focus_handle = self.editor.focus_handle(cx);
10925 let key_context = self
10926 .editor
10927 .update(cx, |editor, cx| editor.key_context(window, cx));
10928
10929 window.set_key_context(key_context);
10930 window.handle_input(
10931 &focus_handle,
10932 ElementInputHandler::new(bounds, self.editor.clone()),
10933 cx,
10934 );
10935 self.register_actions(window, cx);
10936 self.register_key_listeners(window, cx, layout);
10937 }
10938
10939 let text_style = TextStyleRefinement {
10940 font_size: Some(self.style.text.font_size),
10941 line_height: Some(self.style.text.line_height),
10942 ..Default::default()
10943 };
10944 let rem_size = self.rem_size(cx);
10945 window.with_rem_size(rem_size, |window| {
10946 window.with_text_style(Some(text_style), |window| {
10947 window.with_content_mask(Some(ContentMask { bounds }), |window| {
10948 self.paint_mouse_listeners(layout, window, cx);
10949 self.paint_background(layout, window, cx);
10950 self.paint_indent_guides(layout, window, cx);
10951
10952 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10953 self.paint_blamed_display_rows(layout, window, cx);
10954 self.paint_line_numbers(layout, window, cx);
10955 }
10956
10957 self.paint_text(layout, window, cx);
10958
10959 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10960 self.paint_gutter_highlights(layout, window, cx);
10961 self.paint_gutter_indicators(layout, window, cx);
10962 }
10963
10964 if !layout.blocks.is_empty() {
10965 window.with_element_namespace("blocks", |window| {
10966 self.paint_blocks(layout, window, cx);
10967 });
10968 }
10969
10970 window.with_element_namespace("blocks", |window| {
10971 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
10972 sticky_header.paint(window, cx)
10973 }
10974 });
10975
10976 self.paint_sticky_headers(layout, window, cx);
10977 self.paint_minimap(layout, window, cx);
10978 self.paint_scrollbars(layout, window, cx);
10979 self.paint_edit_prediction_popover(layout, window, cx);
10980 self.paint_mouse_context_menu(layout, window, cx);
10981 });
10982 })
10983 })
10984 }
10985}
10986
10987pub(super) fn gutter_bounds(
10988 editor_bounds: Bounds<Pixels>,
10989 gutter_dimensions: GutterDimensions,
10990) -> Bounds<Pixels> {
10991 Bounds {
10992 origin: editor_bounds.origin,
10993 size: size(gutter_dimensions.width, editor_bounds.size.height),
10994 }
10995}
10996
10997#[derive(Clone, Copy)]
10998struct ContextMenuLayout {
10999 y_flipped: bool,
11000 bounds: Bounds<Pixels>,
11001}
11002
11003/// Holds information required for layouting the editor scrollbars.
11004struct ScrollbarLayoutInformation {
11005 /// The bounds of the editor area (excluding the content offset).
11006 editor_bounds: Bounds<Pixels>,
11007 /// The available range to scroll within the document.
11008 scroll_range: Size<Pixels>,
11009 /// The space available for one glyph in the editor.
11010 glyph_grid_cell: Size<Pixels>,
11011}
11012
11013impl ScrollbarLayoutInformation {
11014 pub fn new(
11015 editor_bounds: Bounds<Pixels>,
11016 glyph_grid_cell: Size<Pixels>,
11017 document_size: Size<Pixels>,
11018 longest_line_blame_width: Pixels,
11019 settings: &EditorSettings,
11020 ) -> Self {
11021 let vertical_overscroll = match settings.scroll_beyond_last_line {
11022 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
11023 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
11024 ScrollBeyondLastLine::VerticalScrollMargin => {
11025 (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
11026 }
11027 };
11028
11029 let overscroll = size(longest_line_blame_width, vertical_overscroll);
11030
11031 ScrollbarLayoutInformation {
11032 editor_bounds,
11033 scroll_range: document_size + overscroll,
11034 glyph_grid_cell,
11035 }
11036 }
11037}
11038
11039impl IntoElement for EditorElement {
11040 type Element = Self;
11041
11042 fn into_element(self) -> Self::Element {
11043 self
11044 }
11045}
11046
11047pub struct EditorLayout {
11048 position_map: Rc<PositionMap>,
11049 hitbox: Hitbox,
11050 gutter_hitbox: Hitbox,
11051 content_origin: gpui::Point<Pixels>,
11052 scrollbars_layout: Option<EditorScrollbars>,
11053 minimap: Option<MinimapLayout>,
11054 mode: EditorMode,
11055 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
11056 indent_guides: Option<Vec<IndentGuideLayout>>,
11057 visible_display_row_range: Range<DisplayRow>,
11058 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
11059 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
11060 line_elements: SmallVec<[AnyElement; 1]>,
11061 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
11062 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11063 blamed_display_rows: Option<Vec<AnyElement>>,
11064 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
11065 inline_blame_layout: Option<InlineBlameLayout>,
11066 inline_code_actions: Option<AnyElement>,
11067 blocks: Vec<BlockLayout>,
11068 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11069 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11070 redacted_ranges: Vec<Range<DisplayPoint>>,
11071 cursors: Vec<(DisplayPoint, Hsla)>,
11072 visible_cursors: Vec<CursorLayout>,
11073 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
11074 test_indicators: Vec<AnyElement>,
11075 breakpoints: Vec<AnyElement>,
11076 diff_review_button: Option<AnyElement>,
11077 crease_toggles: Vec<Option<AnyElement>>,
11078 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
11079 diff_hunk_controls: Vec<AnyElement>,
11080 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
11081 edit_prediction_popover: Option<AnyElement>,
11082 mouse_context_menu: Option<AnyElement>,
11083 tab_invisible: ShapedLine,
11084 space_invisible: ShapedLine,
11085 sticky_buffer_header: Option<AnyElement>,
11086 sticky_headers: Option<StickyHeaders>,
11087 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
11088 text_align: TextAlign,
11089 content_width: Pixels,
11090}
11091
11092struct StickyHeaders {
11093 lines: Vec<StickyHeaderLine>,
11094 gutter_background: Hsla,
11095 content_background: Hsla,
11096 gutter_right_padding: Pixels,
11097}
11098
11099struct StickyHeaderLine {
11100 row: DisplayRow,
11101 offset: Pixels,
11102 line: LineWithInvisibles,
11103 line_number: Option<ShapedLine>,
11104 elements: SmallVec<[AnyElement; 1]>,
11105 available_text_width: Pixels,
11106 target_anchor: Anchor,
11107 hitbox: Hitbox,
11108}
11109
11110impl EditorLayout {
11111 fn line_end_overshoot(&self) -> Pixels {
11112 0.15 * self.position_map.line_height
11113 }
11114}
11115
11116impl StickyHeaders {
11117 fn paint(
11118 &mut self,
11119 layout: &mut EditorLayout,
11120 whitespace_setting: ShowWhitespaceSetting,
11121 window: &mut Window,
11122 cx: &mut App,
11123 ) {
11124 let line_height = layout.position_map.line_height;
11125
11126 for line in self.lines.iter_mut().rev() {
11127 window.paint_layer(
11128 Bounds::new(
11129 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11130 size(line.hitbox.size.width, line_height),
11131 ),
11132 |window| {
11133 let gutter_bounds = Bounds::new(
11134 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11135 size(layout.gutter_hitbox.size.width, line_height),
11136 );
11137 window.paint_quad(fill(gutter_bounds, self.gutter_background));
11138
11139 let text_bounds = Bounds::new(
11140 layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11141 size(line.available_text_width, line_height),
11142 );
11143 window.paint_quad(fill(text_bounds, self.content_background));
11144
11145 if line.hitbox.is_hovered(window) {
11146 let hover_overlay = cx.theme().colors().panel_overlay_hover;
11147 window.paint_quad(fill(gutter_bounds, hover_overlay));
11148 window.paint_quad(fill(text_bounds, hover_overlay));
11149 }
11150
11151 line.paint(
11152 layout,
11153 self.gutter_right_padding,
11154 line.available_text_width,
11155 layout.content_origin,
11156 line_height,
11157 whitespace_setting,
11158 window,
11159 cx,
11160 );
11161 },
11162 );
11163
11164 window.set_cursor_style(CursorStyle::PointingHand, &line.hitbox);
11165 }
11166 }
11167}
11168
11169impl StickyHeaderLine {
11170 fn new(
11171 row: DisplayRow,
11172 offset: Pixels,
11173 mut line: LineWithInvisibles,
11174 line_number: Option<ShapedLine>,
11175 target_anchor: Anchor,
11176 line_height: Pixels,
11177 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11178 content_origin: gpui::Point<Pixels>,
11179 gutter_hitbox: &Hitbox,
11180 text_hitbox: &Hitbox,
11181 window: &mut Window,
11182 cx: &mut App,
11183 ) -> Self {
11184 let mut elements = SmallVec::<[AnyElement; 1]>::new();
11185 line.prepaint_with_custom_offset(
11186 line_height,
11187 scroll_pixel_position,
11188 content_origin,
11189 offset,
11190 &mut elements,
11191 window,
11192 cx,
11193 );
11194
11195 let hitbox_bounds = Bounds::new(
11196 gutter_hitbox.origin + point(Pixels::ZERO, offset),
11197 size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11198 );
11199 let available_text_width =
11200 (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11201
11202 Self {
11203 row,
11204 offset,
11205 line,
11206 line_number,
11207 elements,
11208 available_text_width,
11209 target_anchor,
11210 hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11211 }
11212 }
11213
11214 fn paint(
11215 &mut self,
11216 layout: &EditorLayout,
11217 gutter_right_padding: Pixels,
11218 available_text_width: Pixels,
11219 content_origin: gpui::Point<Pixels>,
11220 line_height: Pixels,
11221 whitespace_setting: ShowWhitespaceSetting,
11222 window: &mut Window,
11223 cx: &mut App,
11224 ) {
11225 window.with_content_mask(
11226 Some(ContentMask {
11227 bounds: Bounds::new(
11228 layout.position_map.text_hitbox.bounds.origin
11229 + point(Pixels::ZERO, self.offset),
11230 size(available_text_width, line_height),
11231 ),
11232 }),
11233 |window| {
11234 self.line.draw_with_custom_offset(
11235 layout,
11236 self.row,
11237 content_origin,
11238 self.offset,
11239 whitespace_setting,
11240 &[],
11241 window,
11242 cx,
11243 );
11244 for element in &mut self.elements {
11245 element.paint(window, cx);
11246 }
11247 },
11248 );
11249
11250 if let Some(line_number) = &self.line_number {
11251 let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11252 let gutter_width = layout.gutter_hitbox.size.width;
11253 let origin = point(
11254 gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11255 gutter_origin.y,
11256 );
11257 line_number
11258 .paint(origin, line_height, TextAlign::Left, None, window, cx)
11259 .log_err();
11260 }
11261 }
11262}
11263
11264#[derive(Debug)]
11265struct LineNumberSegment {
11266 shaped_line: ShapedLine,
11267 hitbox: Option<Hitbox>,
11268}
11269
11270#[derive(Debug)]
11271struct LineNumberLayout {
11272 segments: SmallVec<[LineNumberSegment; 1]>,
11273}
11274
11275struct ColoredRange<T> {
11276 start: T,
11277 end: T,
11278 color: Hsla,
11279}
11280
11281impl Along for ScrollbarAxes {
11282 type Unit = bool;
11283
11284 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11285 match axis {
11286 ScrollbarAxis::Horizontal => self.horizontal,
11287 ScrollbarAxis::Vertical => self.vertical,
11288 }
11289 }
11290
11291 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11292 match axis {
11293 ScrollbarAxis::Horizontal => ScrollbarAxes {
11294 horizontal: f(self.horizontal),
11295 vertical: self.vertical,
11296 },
11297 ScrollbarAxis::Vertical => ScrollbarAxes {
11298 horizontal: self.horizontal,
11299 vertical: f(self.vertical),
11300 },
11301 }
11302 }
11303}
11304
11305#[derive(Clone)]
11306struct EditorScrollbars {
11307 pub vertical: Option<ScrollbarLayout>,
11308 pub horizontal: Option<ScrollbarLayout>,
11309 pub visible: bool,
11310}
11311
11312impl EditorScrollbars {
11313 pub fn from_scrollbar_axes(
11314 show_scrollbar: ScrollbarAxes,
11315 layout_information: &ScrollbarLayoutInformation,
11316 content_offset: gpui::Point<Pixels>,
11317 scroll_position: gpui::Point<f64>,
11318 scrollbar_width: Pixels,
11319 right_margin: Pixels,
11320 editor_width: Pixels,
11321 show_scrollbars: bool,
11322 scrollbar_state: Option<&ActiveScrollbarState>,
11323 window: &mut Window,
11324 ) -> Self {
11325 let ScrollbarLayoutInformation {
11326 editor_bounds,
11327 scroll_range,
11328 glyph_grid_cell,
11329 } = layout_information;
11330
11331 let viewport_size = size(editor_width, editor_bounds.size.height);
11332
11333 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11334 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
11335 Corner::BottomLeft,
11336 editor_bounds.bottom_left(),
11337 size(
11338 // The horizontal viewport size differs from the space available for the
11339 // horizontal scrollbar, so we have to manually stitch it together here.
11340 editor_bounds.size.width - right_margin,
11341 scrollbar_width,
11342 ),
11343 ),
11344 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
11345 Corner::TopRight,
11346 editor_bounds.top_right(),
11347 size(scrollbar_width, viewport_size.height),
11348 ),
11349 };
11350
11351 let mut create_scrollbar_layout = |axis| {
11352 let viewport_size = viewport_size.along(axis);
11353 let scroll_range = scroll_range.along(axis);
11354
11355 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11356 (show_scrollbar.along(axis)
11357 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11358 .then(|| {
11359 ScrollbarLayout::new(
11360 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11361 viewport_size,
11362 scroll_range,
11363 glyph_grid_cell.along(axis),
11364 content_offset.along(axis),
11365 scroll_position.along(axis),
11366 show_scrollbars,
11367 axis,
11368 )
11369 .with_thumb_state(
11370 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11371 )
11372 })
11373 };
11374
11375 Self {
11376 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11377 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11378 visible: show_scrollbars,
11379 }
11380 }
11381
11382 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11383 [
11384 (&self.vertical, ScrollbarAxis::Vertical),
11385 (&self.horizontal, ScrollbarAxis::Horizontal),
11386 ]
11387 .into_iter()
11388 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11389 }
11390
11391 /// Returns the currently hovered scrollbar axis, if any.
11392 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11393 self.iter_scrollbars()
11394 .find(|s| s.0.hitbox.is_hovered(window))
11395 }
11396}
11397
11398#[derive(Clone)]
11399struct ScrollbarLayout {
11400 hitbox: Hitbox,
11401 visible_range: Range<ScrollOffset>,
11402 text_unit_size: Pixels,
11403 thumb_bounds: Option<Bounds<Pixels>>,
11404 thumb_state: ScrollbarThumbState,
11405}
11406
11407impl ScrollbarLayout {
11408 const BORDER_WIDTH: Pixels = px(1.0);
11409 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11410 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11411 const MIN_THUMB_SIZE: Pixels = px(25.0);
11412
11413 fn new(
11414 scrollbar_track_hitbox: Hitbox,
11415 viewport_size: Pixels,
11416 scroll_range: Pixels,
11417 glyph_space: Pixels,
11418 content_offset: Pixels,
11419 scroll_position: ScrollOffset,
11420 show_thumb: bool,
11421 axis: ScrollbarAxis,
11422 ) -> Self {
11423 let track_bounds = scrollbar_track_hitbox.bounds;
11424 // The length of the track available to the scrollbar thumb. We deliberately
11425 // exclude the content size here so that the thumb aligns with the content.
11426 let track_length = track_bounds.size.along(axis) - content_offset;
11427
11428 Self::new_with_hitbox_and_track_length(
11429 scrollbar_track_hitbox,
11430 track_length,
11431 viewport_size,
11432 scroll_range.into(),
11433 glyph_space,
11434 content_offset.into(),
11435 scroll_position,
11436 show_thumb,
11437 axis,
11438 )
11439 }
11440
11441 fn for_minimap(
11442 minimap_track_hitbox: Hitbox,
11443 visible_lines: f64,
11444 total_editor_lines: f64,
11445 minimap_line_height: Pixels,
11446 scroll_position: ScrollOffset,
11447 minimap_scroll_top: ScrollOffset,
11448 show_thumb: bool,
11449 ) -> Self {
11450 // The scrollbar thumb size is calculated as
11451 // (visible_content/total_content) Γ scrollbar_track_length.
11452 //
11453 // For the minimap's thumb layout, we leverage this by setting the
11454 // scrollbar track length to the entire document size (using minimap line
11455 // height). This creates a thumb that exactly represents the editor
11456 // viewport scaled to minimap proportions.
11457 //
11458 // We adjust the thumb position relative to `minimap_scroll_top` to
11459 // accommodate for the deliberately oversized track.
11460 //
11461 // This approach ensures that the minimap thumb accurately reflects the
11462 // editor's current scroll position whilst nicely synchronizing the minimap
11463 // thumb and scrollbar thumb.
11464 let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11465 let viewport_size = visible_lines * f64::from(minimap_line_height);
11466
11467 let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11468
11469 Self::new_with_hitbox_and_track_length(
11470 minimap_track_hitbox,
11471 Pixels::from(scroll_range),
11472 Pixels::from(viewport_size),
11473 scroll_range,
11474 minimap_line_height,
11475 track_top_offset,
11476 scroll_position,
11477 show_thumb,
11478 ScrollbarAxis::Vertical,
11479 )
11480 }
11481
11482 fn new_with_hitbox_and_track_length(
11483 scrollbar_track_hitbox: Hitbox,
11484 track_length: Pixels,
11485 viewport_size: Pixels,
11486 scroll_range: f64,
11487 glyph_space: Pixels,
11488 content_offset: ScrollOffset,
11489 scroll_position: ScrollOffset,
11490 show_thumb: bool,
11491 axis: ScrollbarAxis,
11492 ) -> Self {
11493 let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11494 let visible_range = scroll_position..scroll_position + text_units_per_page;
11495 let total_text_units = scroll_range / glyph_space.to_f64();
11496
11497 let thumb_percentage = text_units_per_page / total_text_units;
11498 let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11499 .max(ScrollbarLayout::MIN_THUMB_SIZE)
11500 .min(track_length);
11501
11502 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11503
11504 let content_larger_than_viewport = text_unit_divisor > 0.;
11505
11506 let text_unit_size = if content_larger_than_viewport {
11507 Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11508 } else {
11509 glyph_space
11510 };
11511
11512 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11513 Self::thumb_bounds(
11514 &scrollbar_track_hitbox,
11515 content_offset,
11516 visible_range.start,
11517 text_unit_size,
11518 thumb_size,
11519 axis,
11520 )
11521 });
11522
11523 ScrollbarLayout {
11524 hitbox: scrollbar_track_hitbox,
11525 visible_range,
11526 text_unit_size,
11527 thumb_bounds,
11528 thumb_state: Default::default(),
11529 }
11530 }
11531
11532 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11533 if let Some(thumb_state) = thumb_state {
11534 Self {
11535 thumb_state,
11536 ..self
11537 }
11538 } else {
11539 self
11540 }
11541 }
11542
11543 fn thumb_bounds(
11544 scrollbar_track: &Hitbox,
11545 content_offset: f64,
11546 visible_range_start: f64,
11547 text_unit_size: Pixels,
11548 thumb_size: Pixels,
11549 axis: ScrollbarAxis,
11550 ) -> Bounds<Pixels> {
11551 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11552 origin
11553 + Pixels::from(
11554 content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11555 )
11556 });
11557 Bounds::new(
11558 thumb_origin,
11559 scrollbar_track.size.apply_along(axis, |_| thumb_size),
11560 )
11561 }
11562
11563 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11564 self.thumb_bounds
11565 .is_some_and(|bounds| bounds.contains(position))
11566 }
11567
11568 fn marker_quads_for_ranges(
11569 &self,
11570 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11571 column: Option<usize>,
11572 ) -> Vec<PaintQuad> {
11573 struct MinMax {
11574 min: Pixels,
11575 max: Pixels,
11576 }
11577 let (x_range, height_limit) = if let Some(column) = column {
11578 let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11579 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11580 let end = start + column_width;
11581 (
11582 Range { start, end },
11583 MinMax {
11584 min: Self::MIN_MARKER_HEIGHT,
11585 max: px(f32::MAX),
11586 },
11587 )
11588 } else {
11589 (
11590 Range {
11591 start: Self::BORDER_WIDTH,
11592 end: self.hitbox.size.width,
11593 },
11594 MinMax {
11595 min: Self::LINE_MARKER_HEIGHT,
11596 max: Self::LINE_MARKER_HEIGHT,
11597 },
11598 )
11599 };
11600
11601 let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11602 let mut pixel_ranges = row_ranges
11603 .into_iter()
11604 .map(|range| {
11605 let start_y = row_to_y(range.start);
11606 let end_y = row_to_y(range.end)
11607 + self
11608 .text_unit_size
11609 .max(height_limit.min)
11610 .min(height_limit.max);
11611 ColoredRange {
11612 start: start_y,
11613 end: end_y,
11614 color: range.color,
11615 }
11616 })
11617 .peekable();
11618
11619 let mut quads = Vec::new();
11620 while let Some(mut pixel_range) = pixel_ranges.next() {
11621 while let Some(next_pixel_range) = pixel_ranges.peek() {
11622 if pixel_range.end >= next_pixel_range.start - px(1.0)
11623 && pixel_range.color == next_pixel_range.color
11624 {
11625 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11626 pixel_ranges.next();
11627 } else {
11628 break;
11629 }
11630 }
11631
11632 let bounds = Bounds::from_corners(
11633 point(x_range.start, pixel_range.start),
11634 point(x_range.end, pixel_range.end),
11635 );
11636 quads.push(quad(
11637 bounds,
11638 Corners::default(),
11639 pixel_range.color,
11640 Edges::default(),
11641 Hsla::transparent_black(),
11642 BorderStyle::default(),
11643 ));
11644 }
11645
11646 quads
11647 }
11648}
11649
11650struct MinimapLayout {
11651 pub minimap: AnyElement,
11652 pub thumb_layout: ScrollbarLayout,
11653 pub minimap_scroll_top: ScrollOffset,
11654 pub minimap_line_height: Pixels,
11655 pub thumb_border_style: MinimapThumbBorder,
11656 pub max_scroll_top: ScrollOffset,
11657}
11658
11659impl MinimapLayout {
11660 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11661 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11662 /// The minimap width as a percentage of the editor width.
11663 const MINIMAP_WIDTH_PCT: f32 = 0.15;
11664 /// Calculates the scroll top offset the minimap editor has to have based on the
11665 /// current scroll progress.
11666 fn calculate_minimap_top_offset(
11667 document_lines: f64,
11668 visible_editor_lines: f64,
11669 visible_minimap_lines: f64,
11670 scroll_position: f64,
11671 ) -> ScrollOffset {
11672 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11673 if non_visible_document_lines == 0. {
11674 0.
11675 } else {
11676 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11677 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11678 }
11679 }
11680}
11681
11682struct CreaseTrailerLayout {
11683 element: AnyElement,
11684 bounds: Bounds<Pixels>,
11685}
11686
11687pub(crate) struct PositionMap {
11688 pub size: Size<Pixels>,
11689 pub line_height: Pixels,
11690 pub scroll_position: gpui::Point<ScrollOffset>,
11691 pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11692 pub scroll_max: gpui::Point<ScrollOffset>,
11693 pub em_width: Pixels,
11694 pub em_advance: Pixels,
11695 pub em_layout_width: Pixels,
11696 pub visible_row_range: Range<DisplayRow>,
11697 pub line_layouts: Vec<LineWithInvisibles>,
11698 pub snapshot: EditorSnapshot,
11699 pub text_align: TextAlign,
11700 pub content_width: Pixels,
11701 pub text_hitbox: Hitbox,
11702 pub gutter_hitbox: Hitbox,
11703 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11704 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11705 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11706}
11707
11708#[derive(Debug, Copy, Clone)]
11709pub struct PointForPosition {
11710 pub previous_valid: DisplayPoint,
11711 pub next_valid: DisplayPoint,
11712 pub exact_unclipped: DisplayPoint,
11713 pub column_overshoot_after_line_end: u32,
11714}
11715
11716impl PointForPosition {
11717 pub fn as_valid(&self) -> Option<DisplayPoint> {
11718 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11719 Some(self.previous_valid)
11720 } else {
11721 None
11722 }
11723 }
11724
11725 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11726 let Some(valid_point) = self.as_valid() else {
11727 return false;
11728 };
11729 let range = selection.range();
11730
11731 let candidate_row = valid_point.row();
11732 let candidate_col = valid_point.column();
11733
11734 let start_row = range.start.row();
11735 let start_col = range.start.column();
11736 let end_row = range.end.row();
11737 let end_col = range.end.column();
11738
11739 if candidate_row < start_row || candidate_row > end_row {
11740 false
11741 } else if start_row == end_row {
11742 candidate_col >= start_col && candidate_col < end_col
11743 } else if candidate_row == start_row {
11744 candidate_col >= start_col
11745 } else if candidate_row == end_row {
11746 candidate_col < end_col
11747 } else {
11748 true
11749 }
11750 }
11751}
11752
11753impl PositionMap {
11754 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11755 let text_bounds = self.text_hitbox.bounds;
11756 let scroll_position = self.snapshot.scroll_position();
11757 let position = position - text_bounds.origin;
11758 let y = position.y.max(px(0.)).min(self.size.height);
11759 let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11760 let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11761
11762 let (column, x_overshoot_after_line_end) = if let Some(line) = self
11763 .line_layouts
11764 .get(row as usize - scroll_position.y as usize)
11765 {
11766 let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11767 let x_relative_to_text = x - alignment_offset;
11768 if let Some(ix) = line.index_for_x(x_relative_to_text) {
11769 (ix as u32, px(0.))
11770 } else {
11771 (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11772 }
11773 } else {
11774 (0, x)
11775 };
11776
11777 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11778 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11779 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11780
11781 let column_overshoot_after_line_end =
11782 (x_overshoot_after_line_end / self.em_layout_width) as u32;
11783 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11784 PointForPosition {
11785 previous_valid,
11786 next_valid,
11787 exact_unclipped,
11788 column_overshoot_after_line_end,
11789 }
11790 }
11791}
11792
11793pub(crate) struct BlockLayout {
11794 pub(crate) id: BlockId,
11795 pub(crate) x_offset: Pixels,
11796 pub(crate) row: Option<DisplayRow>,
11797 pub(crate) element: AnyElement,
11798 pub(crate) available_space: Size<AvailableSpace>,
11799 pub(crate) style: BlockStyle,
11800 pub(crate) overlaps_gutter: bool,
11801 pub(crate) is_buffer_header: bool,
11802}
11803
11804pub fn layout_line(
11805 row: DisplayRow,
11806 snapshot: &EditorSnapshot,
11807 style: &EditorStyle,
11808 text_width: Pixels,
11809 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
11810 window: &mut Window,
11811 cx: &mut App,
11812) -> LineWithInvisibles {
11813 let use_tree_sitter =
11814 !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
11815 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), use_tree_sitter, style);
11816 LineWithInvisibles::from_chunks(
11817 chunks,
11818 style,
11819 MAX_LINE_LEN,
11820 1,
11821 &snapshot.mode,
11822 text_width,
11823 is_row_soft_wrapped,
11824 &[],
11825 window,
11826 cx,
11827 )
11828 .pop()
11829 .unwrap()
11830}
11831
11832#[derive(Debug)]
11833pub struct IndentGuideLayout {
11834 origin: gpui::Point<Pixels>,
11835 length: Pixels,
11836 single_indent_width: Pixels,
11837 depth: u32,
11838 active: bool,
11839 settings: IndentGuideSettings,
11840}
11841
11842pub struct CursorLayout {
11843 origin: gpui::Point<Pixels>,
11844 block_width: Pixels,
11845 line_height: Pixels,
11846 color: Hsla,
11847 shape: CursorShape,
11848 block_text: Option<ShapedLine>,
11849 cursor_name: Option<AnyElement>,
11850}
11851
11852#[derive(Debug)]
11853pub struct CursorName {
11854 string: SharedString,
11855 color: Hsla,
11856 is_top_row: bool,
11857}
11858
11859impl CursorLayout {
11860 pub fn new(
11861 origin: gpui::Point<Pixels>,
11862 block_width: Pixels,
11863 line_height: Pixels,
11864 color: Hsla,
11865 shape: CursorShape,
11866 block_text: Option<ShapedLine>,
11867 ) -> CursorLayout {
11868 CursorLayout {
11869 origin,
11870 block_width,
11871 line_height,
11872 color,
11873 shape,
11874 block_text,
11875 cursor_name: None,
11876 }
11877 }
11878
11879 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11880 Bounds {
11881 origin: self.origin + origin,
11882 size: size(self.block_width, self.line_height),
11883 }
11884 }
11885
11886 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11887 match self.shape {
11888 CursorShape::Bar => Bounds {
11889 origin: self.origin + origin,
11890 size: size(px(2.0), self.line_height),
11891 },
11892 CursorShape::Block | CursorShape::Hollow => Bounds {
11893 origin: self.origin + origin,
11894 size: size(self.block_width, self.line_height),
11895 },
11896 CursorShape::Underline => Bounds {
11897 origin: self.origin
11898 + origin
11899 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11900 size: size(self.block_width, px(2.0)),
11901 },
11902 }
11903 }
11904
11905 pub fn layout(
11906 &mut self,
11907 origin: gpui::Point<Pixels>,
11908 cursor_name: Option<CursorName>,
11909 window: &mut Window,
11910 cx: &mut App,
11911 ) {
11912 if let Some(cursor_name) = cursor_name {
11913 let bounds = self.bounds(origin);
11914 let text_size = self.line_height / 1.5;
11915
11916 let name_origin = if cursor_name.is_top_row {
11917 point(bounds.right() - px(1.), bounds.top())
11918 } else {
11919 match self.shape {
11920 CursorShape::Bar => point(
11921 bounds.right() - px(2.),
11922 bounds.top() - text_size / 2. - px(1.),
11923 ),
11924 _ => point(
11925 bounds.right() - px(1.),
11926 bounds.top() - text_size / 2. - px(1.),
11927 ),
11928 }
11929 };
11930 let mut name_element = div()
11931 .bg(self.color)
11932 .text_size(text_size)
11933 .px_0p5()
11934 .line_height(text_size + px(2.))
11935 .text_color(cursor_name.color)
11936 .child(cursor_name.string)
11937 .into_any_element();
11938
11939 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11940
11941 self.cursor_name = Some(name_element);
11942 }
11943 }
11944
11945 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11946 let bounds = self.bounds(origin);
11947
11948 //Draw background or border quad
11949 let cursor = if matches!(self.shape, CursorShape::Hollow) {
11950 outline(bounds, self.color, BorderStyle::Solid)
11951 } else {
11952 fill(bounds, self.color)
11953 };
11954
11955 if let Some(name) = &mut self.cursor_name {
11956 name.paint(window, cx);
11957 }
11958
11959 window.paint_quad(cursor);
11960
11961 if let Some(block_text) = &self.block_text {
11962 block_text
11963 .paint(
11964 self.origin + origin,
11965 self.line_height,
11966 TextAlign::Left,
11967 None,
11968 window,
11969 cx,
11970 )
11971 .log_err();
11972 }
11973 }
11974
11975 pub fn shape(&self) -> CursorShape {
11976 self.shape
11977 }
11978}
11979
11980#[derive(Debug)]
11981pub struct HighlightedRange {
11982 pub start_y: Pixels,
11983 pub line_height: Pixels,
11984 pub lines: Vec<HighlightedRangeLine>,
11985 pub color: Hsla,
11986 pub corner_radius: Pixels,
11987}
11988
11989#[derive(Debug)]
11990pub struct HighlightedRangeLine {
11991 pub start_x: Pixels,
11992 pub end_x: Pixels,
11993}
11994
11995impl HighlightedRange {
11996 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
11997 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
11998 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
11999 self.paint_lines(
12000 self.start_y + self.line_height,
12001 &self.lines[1..],
12002 fill,
12003 bounds,
12004 window,
12005 );
12006 } else {
12007 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
12008 }
12009 }
12010
12011 fn paint_lines(
12012 &self,
12013 start_y: Pixels,
12014 lines: &[HighlightedRangeLine],
12015 fill: bool,
12016 _bounds: Bounds<Pixels>,
12017 window: &mut Window,
12018 ) {
12019 if lines.is_empty() {
12020 return;
12021 }
12022
12023 let first_line = lines.first().unwrap();
12024 let last_line = lines.last().unwrap();
12025
12026 let first_top_left = point(first_line.start_x, start_y);
12027 let first_top_right = point(first_line.end_x, start_y);
12028
12029 let curve_height = point(Pixels::ZERO, self.corner_radius);
12030 let curve_width = |start_x: Pixels, end_x: Pixels| {
12031 let max = (end_x - start_x) / 2.;
12032 let width = if max < self.corner_radius {
12033 max
12034 } else {
12035 self.corner_radius
12036 };
12037
12038 point(width, Pixels::ZERO)
12039 };
12040
12041 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12042 let mut builder = if fill {
12043 gpui::PathBuilder::fill()
12044 } else {
12045 gpui::PathBuilder::stroke(px(1.))
12046 };
12047 builder.move_to(first_top_right - top_curve_width);
12048 builder.curve_to(first_top_right + curve_height, first_top_right);
12049
12050 let mut iter = lines.iter().enumerate().peekable();
12051 while let Some((ix, line)) = iter.next() {
12052 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12053
12054 if let Some((_, next_line)) = iter.peek() {
12055 let next_top_right = point(next_line.end_x, bottom_right.y);
12056
12057 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12058 Ordering::Equal => {
12059 builder.line_to(bottom_right);
12060 }
12061 Ordering::Less => {
12062 let curve_width = curve_width(next_top_right.x, bottom_right.x);
12063 builder.line_to(bottom_right - curve_height);
12064 if self.corner_radius > Pixels::ZERO {
12065 builder.curve_to(bottom_right - curve_width, bottom_right);
12066 }
12067 builder.line_to(next_top_right + curve_width);
12068 if self.corner_radius > Pixels::ZERO {
12069 builder.curve_to(next_top_right + curve_height, next_top_right);
12070 }
12071 }
12072 Ordering::Greater => {
12073 let curve_width = curve_width(bottom_right.x, next_top_right.x);
12074 builder.line_to(bottom_right - curve_height);
12075 if self.corner_radius > Pixels::ZERO {
12076 builder.curve_to(bottom_right + curve_width, bottom_right);
12077 }
12078 builder.line_to(next_top_right - curve_width);
12079 if self.corner_radius > Pixels::ZERO {
12080 builder.curve_to(next_top_right + curve_height, next_top_right);
12081 }
12082 }
12083 }
12084 } else {
12085 let curve_width = curve_width(line.start_x, line.end_x);
12086 builder.line_to(bottom_right - curve_height);
12087 if self.corner_radius > Pixels::ZERO {
12088 builder.curve_to(bottom_right - curve_width, bottom_right);
12089 }
12090
12091 let bottom_left = point(line.start_x, bottom_right.y);
12092 builder.line_to(bottom_left + curve_width);
12093 if self.corner_radius > Pixels::ZERO {
12094 builder.curve_to(bottom_left - curve_height, bottom_left);
12095 }
12096 }
12097 }
12098
12099 if first_line.start_x > last_line.start_x {
12100 let curve_width = curve_width(last_line.start_x, first_line.start_x);
12101 let second_top_left = point(last_line.start_x, start_y + self.line_height);
12102 builder.line_to(second_top_left + curve_height);
12103 if self.corner_radius > Pixels::ZERO {
12104 builder.curve_to(second_top_left + curve_width, second_top_left);
12105 }
12106 let first_bottom_left = point(first_line.start_x, second_top_left.y);
12107 builder.line_to(first_bottom_left - curve_width);
12108 if self.corner_radius > Pixels::ZERO {
12109 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12110 }
12111 }
12112
12113 builder.line_to(first_top_left + curve_height);
12114 if self.corner_radius > Pixels::ZERO {
12115 builder.curve_to(first_top_left + top_curve_width, first_top_left);
12116 }
12117 builder.line_to(first_top_right - top_curve_width);
12118
12119 if let Ok(path) = builder.build() {
12120 window.paint_path(path, self.color);
12121 }
12122 }
12123}
12124
12125pub(crate) struct StickyHeader {
12126 pub item: language::OutlineItem<Anchor>,
12127 pub sticky_row: DisplayRow,
12128 pub start_point: Point,
12129 pub offset: ScrollOffset,
12130}
12131
12132enum CursorPopoverType {
12133 CodeContextMenu,
12134 EditPrediction,
12135}
12136
12137pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12138 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12139}
12140
12141fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12142 (delta.pow(1.2) / 300.0).into()
12143}
12144
12145pub fn register_action<T: Action>(
12146 editor: &Entity<Editor>,
12147 window: &mut Window,
12148 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12149) {
12150 let editor = editor.clone();
12151 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12152 let action = action.downcast_ref().unwrap();
12153 if phase == DispatchPhase::Bubble {
12154 editor.update(cx, |editor, cx| {
12155 listener(editor, action, window, cx);
12156 })
12157 }
12158 })
12159}
12160
12161/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12162/// both full and auto-height editors compute wrap widths consistently.
12163fn calculate_wrap_width(
12164 soft_wrap: SoftWrap,
12165 editor_width: Pixels,
12166 em_width: Pixels,
12167) -> Option<Pixels> {
12168 let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12169
12170 match soft_wrap {
12171 SoftWrap::GitDiff => None,
12172 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12173 SoftWrap::EditorWidth => Some(editor_width),
12174 SoftWrap::Column(column) => Some(wrap_width_for(column)),
12175 SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12176 }
12177}
12178
12179fn compute_auto_height_layout(
12180 editor: &mut Editor,
12181 min_lines: usize,
12182 max_lines: Option<usize>,
12183 known_dimensions: Size<Option<Pixels>>,
12184 available_width: AvailableSpace,
12185 window: &mut Window,
12186 cx: &mut Context<Editor>,
12187) -> Option<Size<Pixels>> {
12188 let width = known_dimensions.width.or({
12189 if let AvailableSpace::Definite(available_width) = available_width {
12190 Some(available_width)
12191 } else {
12192 None
12193 }
12194 })?;
12195 if let Some(height) = known_dimensions.height {
12196 return Some(size(width, height));
12197 }
12198
12199 let style = editor.style.as_ref().unwrap();
12200 let font_id = window.text_system().resolve_font(&style.text.font());
12201 let font_size = style.text.font_size.to_pixels(window.rem_size());
12202 let line_height = style.text.line_height_in_pixels(window.rem_size());
12203 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12204
12205 let mut snapshot = editor.snapshot(window, cx);
12206 let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12207
12208 editor.gutter_dimensions = gutter_dimensions;
12209 let text_width = width - gutter_dimensions.width;
12210 let overscroll = size(em_width, px(0.));
12211
12212 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12213 let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width);
12214 if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12215 snapshot = editor.snapshot(window, cx);
12216 }
12217
12218 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12219
12220 let min_height = line_height * min_lines as f32;
12221 let content_height = scroll_height.max(min_height);
12222
12223 let final_height = if let Some(max_lines) = max_lines {
12224 let max_height = line_height * max_lines as f32;
12225 content_height.min(max_height)
12226 } else {
12227 content_height
12228 };
12229
12230 Some(size(width, final_height))
12231}
12232
12233#[cfg(test)]
12234mod tests {
12235 use super::*;
12236 use crate::{
12237 Editor, MultiBuffer, SelectionEffects,
12238 display_map::{BlockPlacement, BlockProperties},
12239 editor_tests::{init_test, update_test_language_settings},
12240 };
12241 use gpui::{TestAppContext, VisualTestContext};
12242 use language::{Buffer, language_settings, tree_sitter_python};
12243 use log::info;
12244 use rand::{RngCore, rngs::StdRng};
12245 use std::num::NonZeroU32;
12246 use util::test::sample_text;
12247
12248 #[gpui::test]
12249 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12250 init_test(cx, |_| {});
12251 // Ensure wrap completes synchronously by giving block_with_timeout enough ticks
12252 cx.dispatcher.scheduler().set_timeout_ticks(1000..=1000);
12253
12254 let window = cx.add_window(|window, cx| {
12255 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12256 let mut editor = Editor::new(
12257 EditorMode::AutoHeight {
12258 min_lines: 1,
12259 max_lines: None,
12260 },
12261 buffer,
12262 None,
12263 window,
12264 cx,
12265 );
12266 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12267 editor
12268 });
12269 let cx = &mut VisualTestContext::from_window(*window, cx);
12270 let editor = window.root(cx).unwrap();
12271 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12272
12273 for x in 1..=100 {
12274 let (_, state) = cx.draw(
12275 Default::default(),
12276 size(px(200. + 0.13 * x as f32), px(500.)),
12277 |_, _| EditorElement::new(&editor, style.clone()),
12278 );
12279
12280 assert!(
12281 state.position_map.scroll_max.x == 0.,
12282 "Soft wrapped editor should have no horizontal scrolling!"
12283 );
12284 }
12285 }
12286
12287 #[gpui::test]
12288 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12289 init_test(cx, |_| {});
12290 // Ensure wrap completes synchronously by giving block_with_timeout enough ticks
12291 cx.dispatcher.scheduler().set_timeout_ticks(1000..=1000);
12292
12293 let window = cx.add_window(|window, cx| {
12294 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12295 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12296 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12297 editor
12298 });
12299 let cx = &mut VisualTestContext::from_window(*window, cx);
12300 let editor = window.root(cx).unwrap();
12301 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12302
12303 for x in 1..=100 {
12304 let (_, state) = cx.draw(
12305 Default::default(),
12306 size(px(200. + 0.13 * x as f32), px(500.)),
12307 |_, _| EditorElement::new(&editor, style.clone()),
12308 );
12309
12310 assert!(
12311 state.position_map.scroll_max.x == 0.,
12312 "Soft wrapped editor should have no horizontal scrolling!"
12313 );
12314 }
12315 }
12316
12317 #[gpui::test]
12318 fn test_layout_line_numbers(cx: &mut TestAppContext) {
12319 init_test(cx, |_| {});
12320 let window = cx.add_window(|window, cx| {
12321 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12322 Editor::new(EditorMode::full(), buffer, None, window, cx)
12323 });
12324
12325 let editor = window.root(cx).unwrap();
12326 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12327 let line_height = window
12328 .update(cx, |_, window, _| {
12329 style.text.line_height_in_pixels(window.rem_size())
12330 })
12331 .unwrap();
12332 let element = EditorElement::new(&editor, style);
12333 let snapshot = window
12334 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12335 .unwrap();
12336
12337 let layouts = cx
12338 .update_window(*window, |_, window, cx| {
12339 element.layout_line_numbers(
12340 None,
12341 GutterDimensions {
12342 left_padding: Pixels::ZERO,
12343 right_padding: Pixels::ZERO,
12344 width: px(30.0),
12345 margin: Pixels::ZERO,
12346 git_blame_entries_width: None,
12347 },
12348 line_height,
12349 gpui::Point::default(),
12350 DisplayRow(0)..DisplayRow(6),
12351 &(0..6)
12352 .map(|row| RowInfo {
12353 buffer_row: Some(row),
12354 ..Default::default()
12355 })
12356 .collect::<Vec<_>>(),
12357 &BTreeMap::default(),
12358 Some(DisplayRow(0)),
12359 &snapshot,
12360 window,
12361 cx,
12362 )
12363 })
12364 .unwrap();
12365 assert_eq!(layouts.len(), 6);
12366
12367 let relative_rows = window
12368 .update(cx, |editor, window, cx| {
12369 let snapshot = editor.snapshot(window, cx);
12370 snapshot.calculate_relative_line_numbers(
12371 &(DisplayRow(0)..DisplayRow(6)),
12372 DisplayRow(3),
12373 false,
12374 )
12375 })
12376 .unwrap();
12377 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12378 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12379 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12380 // current line has no relative number
12381 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12382 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12383 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12384
12385 // works if cursor is before screen
12386 let relative_rows = window
12387 .update(cx, |editor, window, cx| {
12388 let snapshot = editor.snapshot(window, cx);
12389 snapshot.calculate_relative_line_numbers(
12390 &(DisplayRow(3)..DisplayRow(6)),
12391 DisplayRow(1),
12392 false,
12393 )
12394 })
12395 .unwrap();
12396 assert_eq!(relative_rows.len(), 3);
12397 assert_eq!(relative_rows[&DisplayRow(3)], 2);
12398 assert_eq!(relative_rows[&DisplayRow(4)], 3);
12399 assert_eq!(relative_rows[&DisplayRow(5)], 4);
12400
12401 // works if cursor is after screen
12402 let relative_rows = window
12403 .update(cx, |editor, window, cx| {
12404 let snapshot = editor.snapshot(window, cx);
12405 snapshot.calculate_relative_line_numbers(
12406 &(DisplayRow(0)..DisplayRow(3)),
12407 DisplayRow(6),
12408 false,
12409 )
12410 })
12411 .unwrap();
12412 assert_eq!(relative_rows.len(), 3);
12413 assert_eq!(relative_rows[&DisplayRow(0)], 5);
12414 assert_eq!(relative_rows[&DisplayRow(1)], 4);
12415 assert_eq!(relative_rows[&DisplayRow(2)], 3);
12416
12417 const DELETED_LINE: u32 = 3;
12418 let layouts = cx
12419 .update_window(*window, |_, window, cx| {
12420 element.layout_line_numbers(
12421 None,
12422 GutterDimensions {
12423 left_padding: Pixels::ZERO,
12424 right_padding: Pixels::ZERO,
12425 width: px(30.0),
12426 margin: Pixels::ZERO,
12427 git_blame_entries_width: None,
12428 },
12429 line_height,
12430 gpui::Point::default(),
12431 DisplayRow(0)..DisplayRow(6),
12432 &(0..6)
12433 .map(|row| RowInfo {
12434 buffer_row: Some(row),
12435 diff_status: (row == DELETED_LINE).then(|| {
12436 DiffHunkStatus::deleted(
12437 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12438 )
12439 }),
12440 ..Default::default()
12441 })
12442 .collect::<Vec<_>>(),
12443 &BTreeMap::default(),
12444 Some(DisplayRow(0)),
12445 &snapshot,
12446 window,
12447 cx,
12448 )
12449 })
12450 .unwrap();
12451 assert_eq!(layouts.len(), 5,);
12452 assert!(
12453 layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12454 "Deleted line should not have a line number"
12455 );
12456 }
12457
12458 #[gpui::test]
12459 async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12460 init_test(cx, |_| {});
12461
12462 let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12463
12464 let window = cx.add_window(|window, cx| {
12465 let buffer = cx.new(|cx| {
12466 Buffer::local(
12467 indoc::indoc! {"
12468 fn test() -> int {
12469 return 2;
12470 }
12471
12472 fn another_test() -> int {
12473 # This is a very peculiar method that is hard to grasp.
12474 return 4;
12475 }
12476 "},
12477 cx,
12478 )
12479 .with_language(python_lang, cx)
12480 });
12481
12482 let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12483 Editor::new(EditorMode::full(), buffer, None, window, cx)
12484 });
12485
12486 let editor = window.root(cx).unwrap();
12487 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12488 let line_height = window
12489 .update(cx, |_, window, _| {
12490 style.text.line_height_in_pixels(window.rem_size())
12491 })
12492 .unwrap();
12493 let element = EditorElement::new(&editor, style);
12494 let snapshot = window
12495 .update(cx, |editor, window, cx| {
12496 editor.fold_at(MultiBufferRow(0), window, cx);
12497 editor.snapshot(window, cx)
12498 })
12499 .unwrap();
12500
12501 let layouts = cx
12502 .update_window(*window, |_, window, cx| {
12503 element.layout_line_numbers(
12504 None,
12505 GutterDimensions {
12506 left_padding: Pixels::ZERO,
12507 right_padding: Pixels::ZERO,
12508 width: px(30.0),
12509 margin: Pixels::ZERO,
12510 git_blame_entries_width: None,
12511 },
12512 line_height,
12513 gpui::Point::default(),
12514 DisplayRow(0)..DisplayRow(6),
12515 &(0..6)
12516 .map(|row| RowInfo {
12517 buffer_row: Some(row),
12518 ..Default::default()
12519 })
12520 .collect::<Vec<_>>(),
12521 &BTreeMap::default(),
12522 Some(DisplayRow(3)),
12523 &snapshot,
12524 window,
12525 cx,
12526 )
12527 })
12528 .unwrap();
12529 assert_eq!(layouts.len(), 6);
12530
12531 let relative_rows = window
12532 .update(cx, |editor, window, cx| {
12533 let snapshot = editor.snapshot(window, cx);
12534 snapshot.calculate_relative_line_numbers(
12535 &(DisplayRow(0)..DisplayRow(6)),
12536 DisplayRow(3),
12537 false,
12538 )
12539 })
12540 .unwrap();
12541 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12542 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12543 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12544 // current line has no relative number
12545 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12546 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12547 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12548 }
12549
12550 #[gpui::test]
12551 fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12552 init_test(cx, |_| {});
12553 let window = cx.add_window(|window, cx| {
12554 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12555 Editor::new(EditorMode::full(), buffer, None, window, cx)
12556 });
12557
12558 update_test_language_settings(cx, |s| {
12559 s.defaults.preferred_line_length = Some(5_u32);
12560 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12561 });
12562
12563 let editor = window.root(cx).unwrap();
12564 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12565 let line_height = window
12566 .update(cx, |_, window, _| {
12567 style.text.line_height_in_pixels(window.rem_size())
12568 })
12569 .unwrap();
12570 let element = EditorElement::new(&editor, style);
12571 let snapshot = window
12572 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12573 .unwrap();
12574
12575 let layouts = cx
12576 .update_window(*window, |_, window, cx| {
12577 element.layout_line_numbers(
12578 None,
12579 GutterDimensions {
12580 left_padding: Pixels::ZERO,
12581 right_padding: Pixels::ZERO,
12582 width: px(30.0),
12583 margin: Pixels::ZERO,
12584 git_blame_entries_width: None,
12585 },
12586 line_height,
12587 gpui::Point::default(),
12588 DisplayRow(0)..DisplayRow(6),
12589 &(0..6)
12590 .map(|row| RowInfo {
12591 buffer_row: Some(row),
12592 ..Default::default()
12593 })
12594 .collect::<Vec<_>>(),
12595 &BTreeMap::default(),
12596 Some(DisplayRow(0)),
12597 &snapshot,
12598 window,
12599 cx,
12600 )
12601 })
12602 .unwrap();
12603 assert_eq!(layouts.len(), 3);
12604
12605 let relative_rows = window
12606 .update(cx, |editor, window, cx| {
12607 let snapshot = editor.snapshot(window, cx);
12608 snapshot.calculate_relative_line_numbers(
12609 &(DisplayRow(0)..DisplayRow(6)),
12610 DisplayRow(3),
12611 true,
12612 )
12613 })
12614 .unwrap();
12615
12616 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12617 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12618 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12619 // current line has no relative number
12620 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12621 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12622 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12623
12624 let layouts = cx
12625 .update_window(*window, |_, window, cx| {
12626 element.layout_line_numbers(
12627 None,
12628 GutterDimensions {
12629 left_padding: Pixels::ZERO,
12630 right_padding: Pixels::ZERO,
12631 width: px(30.0),
12632 margin: Pixels::ZERO,
12633 git_blame_entries_width: None,
12634 },
12635 line_height,
12636 gpui::Point::default(),
12637 DisplayRow(0)..DisplayRow(6),
12638 &(0..6)
12639 .map(|row| RowInfo {
12640 buffer_row: Some(row),
12641 diff_status: Some(DiffHunkStatus::deleted(
12642 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12643 )),
12644 ..Default::default()
12645 })
12646 .collect::<Vec<_>>(),
12647 &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12648 Some(DisplayRow(0)),
12649 &snapshot,
12650 window,
12651 cx,
12652 )
12653 })
12654 .unwrap();
12655 assert!(
12656 layouts.is_empty(),
12657 "Deleted lines should have no line number"
12658 );
12659
12660 let relative_rows = window
12661 .update(cx, |editor, window, cx| {
12662 let snapshot = editor.snapshot(window, cx);
12663 snapshot.calculate_relative_line_numbers(
12664 &(DisplayRow(0)..DisplayRow(6)),
12665 DisplayRow(3),
12666 true,
12667 )
12668 })
12669 .unwrap();
12670
12671 // Deleted lines should still have relative numbers
12672 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12673 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12674 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12675 // current line, even if deleted, has no relative number
12676 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12677 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12678 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12679 }
12680
12681 #[gpui::test]
12682 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12683 init_test(cx, |_| {});
12684
12685 let window = cx.add_window(|window, cx| {
12686 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12687 Editor::new(EditorMode::full(), buffer, None, window, cx)
12688 });
12689 let cx = &mut VisualTestContext::from_window(*window, cx);
12690 let editor = window.root(cx).unwrap();
12691 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12692
12693 window
12694 .update(cx, |editor, window, cx| {
12695 editor.cursor_offset_on_selection = true;
12696 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12697 s.select_ranges([
12698 Point::new(0, 0)..Point::new(1, 0),
12699 Point::new(3, 2)..Point::new(3, 3),
12700 Point::new(5, 6)..Point::new(6, 0),
12701 ]);
12702 });
12703 })
12704 .unwrap();
12705
12706 let (_, state) = cx.draw(
12707 point(px(500.), px(500.)),
12708 size(px(500.), px(500.)),
12709 |_, _| EditorElement::new(&editor, style),
12710 );
12711
12712 assert_eq!(state.selections.len(), 1);
12713 let local_selections = &state.selections[0].1;
12714 assert_eq!(local_selections.len(), 3);
12715 // moves cursor back one line
12716 assert_eq!(
12717 local_selections[0].head,
12718 DisplayPoint::new(DisplayRow(0), 6)
12719 );
12720 assert_eq!(
12721 local_selections[0].range,
12722 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12723 );
12724
12725 // moves cursor back one column
12726 assert_eq!(
12727 local_selections[1].range,
12728 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12729 );
12730 assert_eq!(
12731 local_selections[1].head,
12732 DisplayPoint::new(DisplayRow(3), 2)
12733 );
12734
12735 // leaves cursor on the max point
12736 assert_eq!(
12737 local_selections[2].range,
12738 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12739 );
12740 assert_eq!(
12741 local_selections[2].head,
12742 DisplayPoint::new(DisplayRow(6), 0)
12743 );
12744
12745 // active lines does not include 1 (even though the range of the selection does)
12746 assert_eq!(
12747 state.active_rows.keys().cloned().collect::<Vec<_>>(),
12748 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12749 );
12750 }
12751
12752 #[gpui::test]
12753 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12754 init_test(cx, |_| {});
12755
12756 let window = cx.add_window(|window, cx| {
12757 let buffer = MultiBuffer::build_simple("", cx);
12758 Editor::new(EditorMode::full(), buffer, None, window, cx)
12759 });
12760 let cx = &mut VisualTestContext::from_window(*window, cx);
12761 let editor = window.root(cx).unwrap();
12762 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12763 window
12764 .update(cx, |editor, window, cx| {
12765 editor.set_placeholder_text("hello", window, cx);
12766 editor.insert_blocks(
12767 [BlockProperties {
12768 style: BlockStyle::Fixed,
12769 placement: BlockPlacement::Above(Anchor::min()),
12770 height: Some(3),
12771 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12772 priority: 0,
12773 }],
12774 None,
12775 cx,
12776 );
12777
12778 // Blur the editor so that it displays placeholder text.
12779 window.blur();
12780 })
12781 .unwrap();
12782
12783 let (_, state) = cx.draw(
12784 point(px(500.), px(500.)),
12785 size(px(500.), px(500.)),
12786 |_, _| EditorElement::new(&editor, style),
12787 );
12788 assert_eq!(state.position_map.line_layouts.len(), 4);
12789 assert_eq!(state.line_numbers.len(), 1);
12790 assert_eq!(
12791 state
12792 .line_numbers
12793 .get(&MultiBufferRow(0))
12794 .map(|line_number| line_number
12795 .segments
12796 .first()
12797 .unwrap()
12798 .shaped_line
12799 .text
12800 .as_ref()),
12801 Some("1")
12802 );
12803 }
12804
12805 #[gpui::test]
12806 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12807 const TAB_SIZE: u32 = 4;
12808
12809 let input_text = "\t \t|\t| a b";
12810 let expected_invisibles = vec![
12811 Invisible::Tab {
12812 line_start_offset: 0,
12813 line_end_offset: TAB_SIZE as usize,
12814 },
12815 Invisible::Whitespace {
12816 line_offset: TAB_SIZE as usize,
12817 },
12818 Invisible::Tab {
12819 line_start_offset: TAB_SIZE as usize + 1,
12820 line_end_offset: TAB_SIZE as usize * 2,
12821 },
12822 Invisible::Tab {
12823 line_start_offset: TAB_SIZE as usize * 2 + 1,
12824 line_end_offset: TAB_SIZE as usize * 3,
12825 },
12826 Invisible::Whitespace {
12827 line_offset: TAB_SIZE as usize * 3 + 1,
12828 },
12829 Invisible::Whitespace {
12830 line_offset: TAB_SIZE as usize * 3 + 3,
12831 },
12832 ];
12833 assert_eq!(
12834 expected_invisibles.len(),
12835 input_text
12836 .chars()
12837 .filter(|initial_char| initial_char.is_whitespace())
12838 .count(),
12839 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12840 );
12841
12842 for show_line_numbers in [true, false] {
12843 init_test(cx, |s| {
12844 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12845 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
12846 });
12847
12848 let actual_invisibles = collect_invisibles_from_new_editor(
12849 cx,
12850 EditorMode::full(),
12851 input_text,
12852 px(500.0),
12853 show_line_numbers,
12854 );
12855
12856 assert_eq!(expected_invisibles, actual_invisibles);
12857 }
12858 }
12859
12860 #[gpui::test]
12861 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
12862 init_test(cx, |s| {
12863 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12864 s.defaults.tab_size = NonZeroU32::new(4);
12865 });
12866
12867 for editor_mode_without_invisibles in [
12868 EditorMode::SingleLine,
12869 EditorMode::AutoHeight {
12870 min_lines: 1,
12871 max_lines: Some(100),
12872 },
12873 ] {
12874 for show_line_numbers in [true, false] {
12875 let invisibles = collect_invisibles_from_new_editor(
12876 cx,
12877 editor_mode_without_invisibles.clone(),
12878 "\t\t\t| | a b",
12879 px(500.0),
12880 show_line_numbers,
12881 );
12882 assert!(
12883 invisibles.is_empty(),
12884 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
12885 );
12886 }
12887 }
12888 }
12889
12890 #[gpui::test]
12891 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
12892 let tab_size = 4;
12893 let input_text = "a\tbcd ".repeat(9);
12894 let repeated_invisibles = [
12895 Invisible::Tab {
12896 line_start_offset: 1,
12897 line_end_offset: tab_size as usize,
12898 },
12899 Invisible::Whitespace {
12900 line_offset: tab_size as usize + 3,
12901 },
12902 Invisible::Whitespace {
12903 line_offset: tab_size as usize + 4,
12904 },
12905 Invisible::Whitespace {
12906 line_offset: tab_size as usize + 5,
12907 },
12908 Invisible::Whitespace {
12909 line_offset: tab_size as usize + 6,
12910 },
12911 Invisible::Whitespace {
12912 line_offset: tab_size as usize + 7,
12913 },
12914 ];
12915 let expected_invisibles = std::iter::once(repeated_invisibles)
12916 .cycle()
12917 .take(9)
12918 .flatten()
12919 .collect::<Vec<_>>();
12920 assert_eq!(
12921 expected_invisibles.len(),
12922 input_text
12923 .chars()
12924 .filter(|initial_char| initial_char.is_whitespace())
12925 .count(),
12926 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12927 );
12928 info!("Expected invisibles: {expected_invisibles:?}");
12929
12930 init_test(cx, |_| {});
12931
12932 // Put the same string with repeating whitespace pattern into editors of various size,
12933 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
12934 let resize_step = 10.0;
12935 let mut editor_width = 200.0;
12936 while editor_width <= 1000.0 {
12937 for show_line_numbers in [true, false] {
12938 update_test_language_settings(cx, |s| {
12939 s.defaults.tab_size = NonZeroU32::new(tab_size);
12940 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12941 s.defaults.preferred_line_length = Some(editor_width as u32);
12942 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12943 });
12944
12945 let actual_invisibles = collect_invisibles_from_new_editor(
12946 cx,
12947 EditorMode::full(),
12948 &input_text,
12949 px(editor_width),
12950 show_line_numbers,
12951 );
12952
12953 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
12954 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
12955 let mut i = 0;
12956 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
12957 i = actual_index;
12958 match expected_invisibles.get(i) {
12959 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
12960 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
12961 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
12962 _ => {
12963 panic!(
12964 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
12965 )
12966 }
12967 },
12968 None => {
12969 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
12970 }
12971 }
12972 }
12973 let missing_expected_invisibles = &expected_invisibles[i + 1..];
12974 assert!(
12975 missing_expected_invisibles.is_empty(),
12976 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
12977 );
12978
12979 editor_width += resize_step;
12980 }
12981 }
12982 }
12983
12984 fn collect_invisibles_from_new_editor(
12985 cx: &mut TestAppContext,
12986 editor_mode: EditorMode,
12987 input_text: &str,
12988 editor_width: Pixels,
12989 show_line_numbers: bool,
12990 ) -> Vec<Invisible> {
12991 info!(
12992 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
12993 f32::from(editor_width)
12994 );
12995 let window = cx.add_window(|window, cx| {
12996 let buffer = MultiBuffer::build_simple(input_text, cx);
12997 Editor::new(editor_mode, buffer, None, window, cx)
12998 });
12999 let cx = &mut VisualTestContext::from_window(*window, cx);
13000 let editor = window.root(cx).unwrap();
13001
13002 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13003 window
13004 .update(cx, |editor, _, cx| {
13005 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
13006 editor.set_wrap_width(Some(editor_width), cx);
13007 editor.set_show_line_numbers(show_line_numbers, cx);
13008 })
13009 .unwrap();
13010 let (_, state) = cx.draw(
13011 point(px(500.), px(500.)),
13012 size(px(500.), px(500.)),
13013 |_, _| EditorElement::new(&editor, style),
13014 );
13015 state
13016 .position_map
13017 .line_layouts
13018 .iter()
13019 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13020 .cloned()
13021 .collect()
13022 }
13023
13024 #[gpui::test]
13025 fn test_merge_overlapping_ranges() {
13026 let base_bg = Hsla::white();
13027 let color1 = Hsla {
13028 h: 0.0,
13029 s: 0.5,
13030 l: 0.5,
13031 a: 0.5,
13032 };
13033 let color2 = Hsla {
13034 h: 120.0,
13035 s: 0.5,
13036 l: 0.5,
13037 a: 0.5,
13038 };
13039
13040 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13041 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13042 v.iter()
13043 .map(|(r, _)| (r.start.column(), r.end.column()))
13044 .collect()
13045 };
13046
13047 // Test overlapping ranges blend colors
13048 let overlapping = vec![
13049 (display_point(5)..display_point(15), color1),
13050 (display_point(10)..display_point(20), color2),
13051 ];
13052 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13053 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13054
13055 // Test middle segment should have blended color
13056 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13057 assert_eq!(result[1].1, blended);
13058
13059 // Test adjacent same-color ranges merge
13060 let adjacent_same = vec![
13061 (display_point(5)..display_point(10), color1),
13062 (display_point(10)..display_point(15), color1),
13063 ];
13064 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13065 assert_eq!(cols(&result), vec![(5, 15)]);
13066
13067 // Test contained range splits
13068 let contained = vec![
13069 (display_point(5)..display_point(20), color1),
13070 (display_point(10)..display_point(15), color2),
13071 ];
13072 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13073 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13074
13075 // Test multiple overlaps split at every boundary
13076 let color3 = Hsla {
13077 h: 240.0,
13078 s: 0.5,
13079 l: 0.5,
13080 a: 0.5,
13081 };
13082 let complex = vec![
13083 (display_point(5)..display_point(12), color1),
13084 (display_point(8)..display_point(16), color2),
13085 (display_point(10)..display_point(14), color3),
13086 ];
13087 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13088 assert_eq!(
13089 cols(&result),
13090 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13091 );
13092 }
13093
13094 #[gpui::test]
13095 fn test_bg_segments_per_row() {
13096 let base_bg = Hsla::white();
13097
13098 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13099 {
13100 let selection_color = Hsla {
13101 h: 200.0,
13102 s: 0.5,
13103 l: 0.5,
13104 a: 0.5,
13105 };
13106 let player_color = PlayerColor {
13107 cursor: selection_color,
13108 background: selection_color,
13109 selection: selection_color,
13110 };
13111
13112 let spanning_selection = SelectionLayout {
13113 head: DisplayPoint::new(DisplayRow(3), 7),
13114 cursor_shape: CursorShape::Bar,
13115 is_newest: true,
13116 is_local: true,
13117 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13118 active_rows: DisplayRow(1)..DisplayRow(4),
13119 user_name: None,
13120 };
13121
13122 let selections = vec![(player_color, vec![spanning_selection])];
13123 let result = EditorElement::bg_segments_per_row(
13124 DisplayRow(0)..DisplayRow(5),
13125 &selections,
13126 &[],
13127 base_bg,
13128 );
13129
13130 assert_eq!(result.len(), 5);
13131 assert!(result[0].is_empty());
13132 assert_eq!(result[1].len(), 1);
13133 assert_eq!(result[2].len(), 1);
13134 assert_eq!(result[3].len(), 1);
13135 assert!(result[4].is_empty());
13136
13137 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13138 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13139 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13140 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13141 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13142 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13143 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13144 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13145 }
13146
13147 // Case B: selection ends exactly at the start of row 3, excluding row 3
13148 {
13149 let selection_color = Hsla {
13150 h: 120.0,
13151 s: 0.5,
13152 l: 0.5,
13153 a: 0.5,
13154 };
13155 let player_color = PlayerColor {
13156 cursor: selection_color,
13157 background: selection_color,
13158 selection: selection_color,
13159 };
13160
13161 let selection = SelectionLayout {
13162 head: DisplayPoint::new(DisplayRow(2), 0),
13163 cursor_shape: CursorShape::Bar,
13164 is_newest: true,
13165 is_local: true,
13166 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13167 active_rows: DisplayRow(1)..DisplayRow(3),
13168 user_name: None,
13169 };
13170
13171 let selections = vec![(player_color, vec![selection])];
13172 let result = EditorElement::bg_segments_per_row(
13173 DisplayRow(0)..DisplayRow(4),
13174 &selections,
13175 &[],
13176 base_bg,
13177 );
13178
13179 assert_eq!(result.len(), 4);
13180 assert!(result[0].is_empty());
13181 assert_eq!(result[1].len(), 1);
13182 assert_eq!(result[2].len(), 1);
13183 assert!(result[3].is_empty());
13184
13185 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13186 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13187 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13188 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13189 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13190 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13191 }
13192 }
13193
13194 #[cfg(test)]
13195 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13196 TextRun {
13197 len,
13198 color,
13199 ..Default::default()
13200 }
13201 }
13202
13203 #[gpui::test]
13204 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13205 init_test(cx, |_| {});
13206
13207 let dx = |start: u32, end: u32| {
13208 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13209 };
13210
13211 let text_color = Hsla {
13212 h: 210.0,
13213 s: 0.1,
13214 l: 0.4,
13215 a: 1.0,
13216 };
13217 let bg_1 = Hsla {
13218 h: 30.0,
13219 s: 0.6,
13220 l: 0.8,
13221 a: 1.0,
13222 };
13223 let bg_2 = Hsla {
13224 h: 200.0,
13225 s: 0.6,
13226 l: 0.2,
13227 a: 1.0,
13228 };
13229 let min_contrast = 45.0;
13230 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13231 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13232
13233 // Case A: single run; disjoint segments inside the run
13234 {
13235 let runs = vec![generate_test_run(20, text_color)];
13236 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13237 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13238 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13239 assert_eq!(
13240 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13241 vec![5, 5, 2, 4, 4]
13242 );
13243 assert_eq!(out[0].color, text_color);
13244 assert_eq!(out[1].color, adjusted_bg1);
13245 assert_eq!(out[2].color, text_color);
13246 assert_eq!(out[3].color, adjusted_bg2);
13247 assert_eq!(out[4].color, text_color);
13248 }
13249
13250 // Case B: multiple runs; segment extends to end of line (u32::MAX)
13251 {
13252 let runs = vec![
13253 generate_test_run(8, text_color),
13254 generate_test_run(7, text_color),
13255 ];
13256 let segs = vec![(dx(6, u32::MAX), bg_1)];
13257 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13258 // Expected slices across runs: [0,6) [6,8) | [0,7)
13259 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13260 assert_eq!(out[0].color, text_color);
13261 assert_eq!(out[1].color, adjusted_bg1);
13262 assert_eq!(out[2].color, adjusted_bg1);
13263 }
13264
13265 // Case C: multi-byte characters
13266 {
13267 // for text: "Hello π δΈη!"
13268 let runs = vec![
13269 generate_test_run(5, text_color), // "Hello"
13270 generate_test_run(6, text_color), // " π "
13271 generate_test_run(6, text_color), // "δΈη"
13272 generate_test_run(1, text_color), // "!"
13273 ];
13274 // selecting "π δΈ"
13275 let segs = vec![(dx(6, 14), bg_1)];
13276 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13277 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
13278 assert_eq!(
13279 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13280 vec![5, 1, 5, 3, 3, 1]
13281 );
13282 assert_eq!(out[0].color, text_color); // "Hello"
13283 assert_eq!(out[2].color, adjusted_bg1); // "π "
13284 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
13285 assert_eq!(out[4].color, text_color); // "η"
13286 assert_eq!(out[5].color, text_color); // "!"
13287 }
13288
13289 // Case D: split multiple consecutive text runs with segments
13290 {
13291 let segs = vec![
13292 (dx(2, 4), bg_1), // selecting "cd"
13293 (dx(4, 8), bg_2), // selecting "efgh"
13294 (dx(9, 11), bg_1), // selecting "jk"
13295 (dx(12, 16), bg_2), // selecting "mnop"
13296 (dx(18, 19), bg_1), // selecting "s"
13297 ];
13298
13299 // for text: "abcdef"
13300 let runs = vec![
13301 generate_test_run(2, text_color), // ab
13302 generate_test_run(4, text_color), // cdef
13303 ];
13304 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13305 // new splits "ab", "cd", "ef"
13306 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13307 assert_eq!(out[0].color, text_color);
13308 assert_eq!(out[1].color, adjusted_bg1);
13309 assert_eq!(out[2].color, adjusted_bg2);
13310
13311 // for text: "ghijklmn"
13312 let runs = vec![
13313 generate_test_run(3, text_color), // ghi
13314 generate_test_run(2, text_color), // jk
13315 generate_test_run(3, text_color), // lmn
13316 ];
13317 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13318 // new splits "gh", "i", "jk", "l", "mn"
13319 assert_eq!(
13320 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13321 vec![2, 1, 2, 1, 2]
13322 );
13323 assert_eq!(out[0].color, adjusted_bg2);
13324 assert_eq!(out[1].color, text_color);
13325 assert_eq!(out[2].color, adjusted_bg1);
13326 assert_eq!(out[3].color, text_color);
13327 assert_eq!(out[4].color, adjusted_bg2);
13328
13329 // for text: "opqrs"
13330 let runs = vec![
13331 generate_test_run(1, text_color), // o
13332 generate_test_run(4, text_color), // pqrs
13333 ];
13334 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13335 // new splits "o", "p", "qr", "s"
13336 assert_eq!(
13337 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13338 vec![1, 1, 2, 1]
13339 );
13340 assert_eq!(out[0].color, adjusted_bg2);
13341 assert_eq!(out[1].color, adjusted_bg2);
13342 assert_eq!(out[2].color, text_color);
13343 assert_eq!(out[3].color, adjusted_bg1);
13344 }
13345 }
13346
13347 #[test]
13348 fn test_checkerboard_size() {
13349 // line height is smaller than target height, so we just return half the line height
13350 assert_eq!(EditorElement::checkerboard_size(10.0, 20.0), 5.0);
13351
13352 // line height is exactly half the target height, perfect match
13353 assert_eq!(EditorElement::checkerboard_size(20.0, 10.0), 10.0);
13354
13355 // line height is close to half the target height
13356 assert_eq!(EditorElement::checkerboard_size(20.0, 9.0), 10.0);
13357
13358 // line height is close to 1/4 the target height
13359 assert_eq!(EditorElement::checkerboard_size(20.0, 4.8), 5.0);
13360 }
13361
13362 #[gpui::test(iterations = 100)]
13363 fn test_random_checkerboard_size(mut rng: StdRng) {
13364 let line_height = rng.next_u32() as f32;
13365 let target_height = rng.next_u32() as f32;
13366
13367 let result = EditorElement::checkerboard_size(line_height, target_height);
13368
13369 let k = line_height / result;
13370 assert!(k - k.round() < 0.0000001); // approximately integer
13371 assert!((k.round() as u32).is_multiple_of(2));
13372 }
13373
13374 #[test]
13375 fn test_calculate_wrap_width() {
13376 let editor_width = px(800.0);
13377 let em_width = px(8.0);
13378
13379 assert_eq!(
13380 calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13381 None,
13382 );
13383
13384 assert_eq!(
13385 calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13386 Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13387 );
13388
13389 assert_eq!(
13390 calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13391 Some(px(800.0)),
13392 );
13393
13394 assert_eq!(
13395 calculate_wrap_width(SoftWrap::Column(72), editor_width, em_width),
13396 Some(px((72.0 * 8.0_f32).ceil())),
13397 );
13398
13399 assert_eq!(
13400 calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13401 Some(px((72.0 * 8.0_f32).ceil())),
13402 );
13403 assert_eq!(
13404 calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13405 Some(px(400.0)),
13406 );
13407 }
13408}