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