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