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