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