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