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