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