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