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