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