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 delta = delta.coalesce(event.delta);
7677
7678 if event.modifiers.secondary() && editor.read(cx).enable_mouse_wheel_zoom {
7679 let delta_y = match event.delta {
7680 ScrollDelta::Pixels(pixels) => pixels.y.into(),
7681 ScrollDelta::Lines(lines) => lines.y,
7682 };
7683
7684 if delta_y > 0.0 {
7685 theme_settings::increase_buffer_font_size(cx);
7686 } else if delta_y < 0.0 {
7687 theme_settings::decrease_buffer_font_size(cx);
7688 }
7689
7690 cx.stop_propagation();
7691 } else {
7692 let scroll_sensitivity = {
7693 if event.modifiers.alt {
7694 fast_scroll_sensitivity
7695 } else {
7696 base_scroll_sensitivity
7697 }
7698 };
7699
7700 editor.update(cx, |editor, cx| {
7701 let line_height = position_map.line_height;
7702 let glyph_width = position_map.em_layout_width;
7703 let (delta, axis) = match delta {
7704 gpui::ScrollDelta::Pixels(mut pixels) => {
7705 //Trackpad
7706 let axis =
7707 position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7708 (pixels, axis)
7709 }
7710
7711 gpui::ScrollDelta::Lines(lines) => {
7712 //Not trackpad
7713 let pixels =
7714 point(lines.x * glyph_width, lines.y * line_height);
7715 (pixels, None)
7716 }
7717 };
7718
7719 let current_scroll_position = position_map.snapshot.scroll_position();
7720 let x = (current_scroll_position.x
7721 * ScrollPixelOffset::from(glyph_width)
7722 - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
7723 / ScrollPixelOffset::from(glyph_width);
7724 let y = (current_scroll_position.y
7725 * ScrollPixelOffset::from(line_height)
7726 - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
7727 / ScrollPixelOffset::from(line_height);
7728 let mut scroll_position =
7729 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7730 let forbid_vertical_scroll =
7731 editor.scroll_manager.forbid_vertical_scroll();
7732 if forbid_vertical_scroll {
7733 scroll_position.y = current_scroll_position.y;
7734 }
7735
7736 if scroll_position != current_scroll_position {
7737 editor.scroll(scroll_position, axis, window, cx);
7738 cx.stop_propagation();
7739 } else if y < 0. {
7740 // Due to clamping, we may fail to detect cases of overscroll to the top;
7741 // We want the scroll manager to get an update in such cases and detect the change of direction
7742 // on the next frame.
7743 cx.notify();
7744 }
7745 });
7746 }
7747 }
7748 }
7749 });
7750 }
7751
7752 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7753 if layout.mode.is_minimap() {
7754 return;
7755 }
7756
7757 self.paint_scroll_wheel_listener(layout, window, cx);
7758
7759 window.on_mouse_event({
7760 let position_map = layout.position_map.clone();
7761 let editor = self.editor.clone();
7762 let line_numbers = layout.line_numbers.clone();
7763
7764 move |event: &MouseDownEvent, phase, window, cx| {
7765 if phase == DispatchPhase::Bubble {
7766 match event.button {
7767 MouseButton::Left => editor.update(cx, |editor, cx| {
7768 let pending_mouse_down = editor
7769 .pending_mouse_down
7770 .get_or_insert_with(Default::default)
7771 .clone();
7772
7773 *pending_mouse_down.borrow_mut() = Some(event.clone());
7774
7775 Self::mouse_left_down(
7776 editor,
7777 event,
7778 &position_map,
7779 line_numbers.as_ref(),
7780 window,
7781 cx,
7782 );
7783 }),
7784 MouseButton::Right => editor.update(cx, |editor, cx| {
7785 Self::mouse_right_down(editor, event, &position_map, window, cx);
7786 }),
7787 MouseButton::Middle => editor.update(cx, |editor, cx| {
7788 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7789 }),
7790 _ => {}
7791 };
7792 }
7793 }
7794 });
7795
7796 window.on_mouse_event({
7797 let editor = self.editor.clone();
7798 let position_map = layout.position_map.clone();
7799
7800 move |event: &MouseUpEvent, phase, window, cx| {
7801 if phase == DispatchPhase::Bubble {
7802 editor.update(cx, |editor, cx| {
7803 Self::mouse_up(editor, event, &position_map, window, cx)
7804 });
7805 }
7806 }
7807 });
7808
7809 window.on_mouse_event({
7810 let editor = self.editor.clone();
7811 let position_map = layout.position_map.clone();
7812 let mut captured_mouse_down = None;
7813
7814 move |event: &MouseUpEvent, phase, window, cx| match phase {
7815 // Clear the pending mouse down during the capture phase,
7816 // so that it happens even if another event handler stops
7817 // propagation.
7818 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7819 let pending_mouse_down = editor
7820 .pending_mouse_down
7821 .get_or_insert_with(Default::default)
7822 .clone();
7823
7824 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7825 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7826 captured_mouse_down = pending_mouse_down.take();
7827 window.refresh();
7828 }
7829 }),
7830 // Fire click handlers during the bubble phase.
7831 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7832 if let Some(mouse_down) = captured_mouse_down.take() {
7833 let event = ClickEvent::Mouse(MouseClickEvent {
7834 down: mouse_down,
7835 up: event.clone(),
7836 });
7837 Self::click(editor, &event, &position_map, window, cx);
7838 }
7839 }),
7840 }
7841 });
7842
7843 window.on_mouse_event({
7844 let position_map = layout.position_map.clone();
7845 let editor = self.editor.clone();
7846
7847 move |event: &MousePressureEvent, phase, window, cx| {
7848 if phase == DispatchPhase::Bubble {
7849 editor.update(cx, |editor, cx| {
7850 Self::pressure_click(editor, &event, &position_map, window, cx);
7851 })
7852 }
7853 }
7854 });
7855
7856 window.on_mouse_event({
7857 let position_map = layout.position_map.clone();
7858 let editor = self.editor.clone();
7859 let split_side = self.split_side;
7860
7861 move |event: &MouseMoveEvent, phase, window, cx| {
7862 if phase == DispatchPhase::Bubble {
7863 editor.update(cx, |editor, cx| {
7864 if editor.hover_state.focused(window, cx) {
7865 return;
7866 }
7867 if event.pressed_button == Some(MouseButton::Left)
7868 || event.pressed_button == Some(MouseButton::Middle)
7869 {
7870 Self::mouse_dragged(editor, event, &position_map, window, cx)
7871 }
7872
7873 Self::mouse_moved(editor, event, &position_map, split_side, window, cx)
7874 });
7875 }
7876 }
7877 });
7878 }
7879
7880 fn shape_line_number(
7881 &self,
7882 text: SharedString,
7883 color: Hsla,
7884 window: &mut Window,
7885 ) -> ShapedLine {
7886 let run = TextRun {
7887 len: text.len(),
7888 font: self.style.text.font(),
7889 color,
7890 ..Default::default()
7891 };
7892 window.text_system().shape_line(
7893 text,
7894 self.style.text.font_size.to_pixels(window.rem_size()),
7895 &[run],
7896 None,
7897 )
7898 }
7899
7900 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7901 let unstaged = status.has_secondary_hunk();
7902 let unstaged_hollow = matches!(
7903 ProjectSettings::get_global(cx).git.hunk_style,
7904 GitHunkStyleSetting::UnstagedHollow
7905 );
7906
7907 unstaged == unstaged_hollow
7908 }
7909
7910 #[cfg(debug_assertions)]
7911 fn layout_debug_ranges(
7912 selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
7913 anchor_range: Range<Anchor>,
7914 display_snapshot: &DisplaySnapshot,
7915 cx: &App,
7916 ) {
7917 let theme = cx.theme();
7918 text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
7919 if debug_ranges.ranges.is_empty() {
7920 return;
7921 }
7922 let buffer_snapshot = &display_snapshot.buffer_snapshot();
7923 for (excerpt_buffer_snapshot, buffer_range, _) in
7924 buffer_snapshot.range_to_buffer_ranges(anchor_range.start..anchor_range.end)
7925 {
7926 let buffer_range = excerpt_buffer_snapshot.anchor_after(buffer_range.start)
7927 ..excerpt_buffer_snapshot.anchor_before(buffer_range.end);
7928 selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
7929 debug_range.ranges.iter().filter_map(|range| {
7930 let player_color = theme
7931 .players()
7932 .color_for_participant(debug_range.occurrence_index as u32 + 1);
7933 if range.start.buffer_id != excerpt_buffer_snapshot.remote_id() {
7934 return None;
7935 }
7936 let clipped_start = range
7937 .start
7938 .max(&buffer_range.start, &excerpt_buffer_snapshot);
7939 let clipped_end =
7940 range.end.min(&buffer_range.end, &excerpt_buffer_snapshot);
7941 let range = buffer_snapshot
7942 .buffer_anchor_range_to_anchor_range(*clipped_start..*clipped_end)?;
7943 let start = range.start.to_display_point(display_snapshot);
7944 let end = range.end.to_display_point(display_snapshot);
7945 let selection_layout = SelectionLayout {
7946 head: start,
7947 range: start..end,
7948 cursor_shape: CursorShape::Bar,
7949 is_newest: false,
7950 is_local: false,
7951 active_rows: start.row()..end.row(),
7952 user_name: Some(SharedString::new(debug_range.value.clone())),
7953 };
7954 Some((player_color, vec![selection_layout]))
7955 })
7956 }));
7957 }
7958 });
7959 }
7960}
7961
7962pub fn render_breadcrumb_text(
7963 mut segments: Vec<HighlightedText>,
7964 breadcrumb_font: Option<Font>,
7965 prefix: Option<gpui::AnyElement>,
7966 active_item: &dyn ItemHandle,
7967 multibuffer_header: bool,
7968 window: &mut Window,
7969 cx: &App,
7970) -> gpui::AnyElement {
7971 const MAX_SEGMENTS: usize = 12;
7972
7973 let element = h_flex().flex_grow().text_ui(cx);
7974
7975 let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
7976 let suffix_start_ix = cmp::max(
7977 prefix_end_ix,
7978 segments.len().saturating_sub(MAX_SEGMENTS / 2),
7979 );
7980
7981 if suffix_start_ix > prefix_end_ix {
7982 segments.splice(
7983 prefix_end_ix..suffix_start_ix,
7984 Some(HighlightedText {
7985 text: "β―".into(),
7986 highlights: vec![],
7987 }),
7988 );
7989 }
7990
7991 let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
7992 let mut text_style = window.text_style();
7993 if let Some(font) = &breadcrumb_font {
7994 text_style.font_family = font.family.clone();
7995 text_style.font_features = font.features.clone();
7996 text_style.font_style = font.style;
7997 text_style.font_weight = font.weight;
7998 }
7999 text_style.color = Color::Muted.color(cx);
8000
8001 if index == 0
8002 && !workspace::TabBarSettings::get_global(cx).show
8003 && active_item.is_dirty(cx)
8004 && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
8005 {
8006 return styled_element;
8007 }
8008
8009 StyledText::new(segment.text.replace('\n', " "))
8010 .with_default_highlights(&text_style, segment.highlights)
8011 .into_any()
8012 });
8013
8014 let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
8015 Label::new("βΊ").color(Color::Placeholder).into_any_element()
8016 });
8017
8018 let breadcrumbs_stack = h_flex()
8019 .gap_1()
8020 .when(multibuffer_header, |this| {
8021 this.pl_2()
8022 .border_l_1()
8023 .border_color(cx.theme().colors().border.opacity(0.6))
8024 })
8025 .children(breadcrumbs);
8026
8027 let breadcrumbs = if let Some(prefix) = prefix {
8028 h_flex().gap_1p5().child(prefix).child(breadcrumbs_stack)
8029 } else {
8030 breadcrumbs_stack
8031 };
8032
8033 let editor = active_item
8034 .downcast::<Editor>()
8035 .map(|editor| editor.downgrade());
8036
8037 let has_project_path = active_item.project_path(cx).is_some();
8038
8039 match editor {
8040 Some(editor) => element
8041 .id("breadcrumb_container")
8042 .when(!multibuffer_header, |this| this.overflow_x_scroll())
8043 .child(
8044 ButtonLike::new("toggle outline view")
8045 .child(breadcrumbs)
8046 .when(multibuffer_header, |this| {
8047 this.style(ButtonStyle::Transparent)
8048 })
8049 .when(!multibuffer_header, |this| {
8050 let focus_handle = editor.upgrade().unwrap().focus_handle(&cx);
8051
8052 this.tooltip(Tooltip::element(move |_window, cx| {
8053 v_flex()
8054 .gap_1()
8055 .child(
8056 h_flex()
8057 .gap_1()
8058 .justify_between()
8059 .child(Label::new("Show Symbol Outline"))
8060 .child(ui::KeyBinding::for_action_in(
8061 &zed_actions::outline::ToggleOutline,
8062 &focus_handle,
8063 cx,
8064 )),
8065 )
8066 .when(has_project_path, |this| {
8067 this.child(
8068 h_flex()
8069 .gap_1()
8070 .justify_between()
8071 .pt_1()
8072 .border_t_1()
8073 .border_color(cx.theme().colors().border_variant)
8074 .child(Label::new("Right-Click to Copy Path")),
8075 )
8076 })
8077 .into_any_element()
8078 }))
8079 .on_click({
8080 let editor = editor.clone();
8081 move |_, window, cx| {
8082 if let Some((editor, callback)) = editor
8083 .upgrade()
8084 .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
8085 {
8086 callback(editor.to_any_view(), window, cx);
8087 }
8088 }
8089 })
8090 .when(has_project_path, |this| {
8091 this.on_right_click({
8092 let editor = editor.clone();
8093 move |_, _, cx| {
8094 if let Some(abs_path) = editor.upgrade().and_then(|editor| {
8095 editor.update(cx, |editor, cx| {
8096 editor.target_file_abs_path(cx)
8097 })
8098 }) {
8099 if let Some(path_str) = abs_path.to_str() {
8100 cx.write_to_clipboard(ClipboardItem::new_string(
8101 path_str.to_string(),
8102 ));
8103 }
8104 }
8105 }
8106 })
8107 })
8108 }),
8109 )
8110 .into_any_element(),
8111 None => element
8112 .h(rems_from_px(22.)) // Match the height and padding of the `ButtonLike` in the other arm.
8113 .pl_1()
8114 .child(breadcrumbs)
8115 .into_any_element(),
8116 }
8117}
8118
8119fn apply_dirty_filename_style(
8120 segment: &HighlightedText,
8121 text_style: &gpui::TextStyle,
8122 cx: &App,
8123) -> Option<gpui::AnyElement> {
8124 let text = segment.text.replace('\n', " ");
8125
8126 let filename_position = std::path::Path::new(segment.text.as_ref())
8127 .file_name()
8128 .and_then(|f| {
8129 let filename_str = f.to_string_lossy();
8130 segment.text.rfind(filename_str.as_ref())
8131 })?;
8132
8133 let bold_weight = FontWeight::BOLD;
8134 let default_color = Color::Default.color(cx);
8135
8136 if filename_position == 0 {
8137 let mut filename_style = text_style.clone();
8138 filename_style.font_weight = bold_weight;
8139 filename_style.color = default_color;
8140
8141 return Some(
8142 StyledText::new(text)
8143 .with_default_highlights(&filename_style, [])
8144 .into_any(),
8145 );
8146 }
8147
8148 let highlight_style = gpui::HighlightStyle {
8149 font_weight: Some(bold_weight),
8150 color: Some(default_color),
8151 ..Default::default()
8152 };
8153
8154 let highlight = vec![(filename_position..text.len(), highlight_style)];
8155 Some(
8156 StyledText::new(text)
8157 .with_default_highlights(text_style, highlight)
8158 .into_any(),
8159 )
8160}
8161
8162fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
8163 file_status.map_or(Color::Default, |status| {
8164 if status.is_conflicted() {
8165 Color::Conflict
8166 } else if status.is_modified() {
8167 Color::Modified
8168 } else if status.is_deleted() {
8169 Color::Disabled
8170 } else if status.is_created() {
8171 Color::Created
8172 } else {
8173 Color::Default
8174 }
8175 })
8176}
8177
8178pub(crate) fn header_jump_data(
8179 editor_snapshot: &EditorSnapshot,
8180 block_row_start: DisplayRow,
8181 height: u32,
8182 first_excerpt: &ExcerptBoundaryInfo,
8183 latest_selection_anchors: &HashMap<BufferId, Anchor>,
8184) -> JumpData {
8185 let multibuffer_snapshot = editor_snapshot.buffer_snapshot();
8186 let buffer = first_excerpt.buffer(multibuffer_snapshot);
8187 let (jump_anchor, jump_buffer) = if let Some(anchor) =
8188 latest_selection_anchors.get(&first_excerpt.buffer_id())
8189 && let Some((jump_anchor, selection_buffer)) =
8190 multibuffer_snapshot.anchor_to_buffer_anchor(*anchor)
8191 {
8192 (jump_anchor, selection_buffer)
8193 } else {
8194 (first_excerpt.range.primary.start, buffer)
8195 };
8196 let excerpt_start = first_excerpt.range.context.start;
8197 let jump_position = language::ToPoint::to_point(&jump_anchor, jump_buffer);
8198 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
8199 0
8200 } else {
8201 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
8202 jump_position.row.saturating_sub(excerpt_start_point.row)
8203 };
8204
8205 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
8206 .saturating_sub(
8207 editor_snapshot
8208 .scroll_anchor
8209 .scroll_position(&editor_snapshot.display_snapshot)
8210 .y as u32,
8211 );
8212
8213 JumpData::MultiBufferPoint {
8214 anchor: jump_anchor,
8215 position: jump_position,
8216 line_offset_from_top,
8217 }
8218}
8219
8220pub(crate) fn render_buffer_header(
8221 editor: &Entity<Editor>,
8222 for_excerpt: &ExcerptBoundaryInfo,
8223 is_folded: bool,
8224 is_selected: bool,
8225 is_sticky: bool,
8226 jump_data: JumpData,
8227 window: &mut Window,
8228 cx: &mut App,
8229) -> impl IntoElement {
8230 let editor_read = editor.read(cx);
8231 let multi_buffer = editor_read.buffer.read(cx);
8232 let is_read_only = editor_read.read_only(cx);
8233 let editor_handle: &dyn ItemHandle = editor;
8234 let multibuffer_snapshot = multi_buffer.snapshot(cx);
8235 let buffer = for_excerpt.buffer(&multibuffer_snapshot);
8236
8237 let breadcrumbs = if is_selected {
8238 editor_read.breadcrumbs_inner(cx)
8239 } else {
8240 None
8241 };
8242
8243 let buffer_id = for_excerpt.buffer_id();
8244 let file_status = multi_buffer
8245 .all_diff_hunks_expanded()
8246 .then(|| editor_read.status_for_buffer_id(buffer_id, cx))
8247 .flatten();
8248 let indicator = multi_buffer.buffer(buffer_id).and_then(|buffer| {
8249 let buffer = buffer.read(cx);
8250 let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
8251 (true, _) => Some(Color::Warning),
8252 (_, true) => Some(Color::Accent),
8253 (false, false) => None,
8254 };
8255 indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
8256 });
8257
8258 let include_root = editor_read
8259 .project
8260 .as_ref()
8261 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
8262 .unwrap_or_default();
8263 let file = buffer.file();
8264 let can_open_excerpts = file.is_none_or(|file| file.can_open());
8265 let path_style = file.map(|file| file.path_style(cx));
8266 let relative_path = buffer.resolve_file_path(include_root, cx);
8267 let (parent_path, filename) = if let Some(path) = &relative_path {
8268 if let Some(path_style) = path_style {
8269 let (dir, file_name) = path_style.split(path);
8270 (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
8271 } else {
8272 (None, Some(path.clone()))
8273 }
8274 } else {
8275 (None, None)
8276 };
8277 let focus_handle = editor_read.focus_handle(cx);
8278 let colors = cx.theme().colors();
8279
8280 let header = div()
8281 .id(("buffer-header", buffer_id.to_proto()))
8282 .p(BUFFER_HEADER_PADDING)
8283 .w_full()
8284 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
8285 .child(
8286 h_flex()
8287 .group("buffer-header-group")
8288 .size_full()
8289 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
8290 .pl_1()
8291 .pr_2()
8292 .rounded_sm()
8293 .gap_1p5()
8294 .when(is_sticky, |el| el.shadow_md())
8295 .border_1()
8296 .map(|border| {
8297 let border_color =
8298 if is_selected && is_folded && focus_handle.contains_focused(window, cx) {
8299 colors.border_focused
8300 } else {
8301 colors.border
8302 };
8303 border.border_color(border_color)
8304 })
8305 .bg(colors.editor_subheader_background)
8306 .hover(|style| style.bg(colors.element_hover))
8307 .map(|header| {
8308 let editor = editor.clone();
8309 let buffer_id = for_excerpt.buffer_id();
8310 let toggle_chevron_icon =
8311 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
8312 let button_size = rems_from_px(28.);
8313
8314 header.child(
8315 div()
8316 .hover(|style| style.bg(colors.element_selected))
8317 .rounded_xs()
8318 .child(
8319 ButtonLike::new("toggle-buffer-fold")
8320 .style(ButtonStyle::Transparent)
8321 .height(button_size.into())
8322 .width(button_size)
8323 .children(toggle_chevron_icon)
8324 .tooltip({
8325 let focus_handle = focus_handle.clone();
8326 let is_folded_for_tooltip = is_folded;
8327 move |_window, cx| {
8328 Tooltip::with_meta_in(
8329 if is_folded_for_tooltip {
8330 "Unfold Excerpt"
8331 } else {
8332 "Fold Excerpt"
8333 },
8334 Some(&ToggleFold),
8335 format!(
8336 "{} to toggle all",
8337 text_for_keystroke(
8338 &Modifiers::alt(),
8339 "click",
8340 cx
8341 )
8342 ),
8343 &focus_handle,
8344 cx,
8345 )
8346 }
8347 })
8348 .on_click(move |event, window, cx| {
8349 if event.modifiers().alt {
8350 editor.update(cx, |editor, cx| {
8351 editor.toggle_fold_all(&ToggleFoldAll, window, cx);
8352 });
8353 } else {
8354 if is_folded {
8355 editor.update(cx, |editor, cx| {
8356 editor.unfold_buffer(buffer_id, cx);
8357 });
8358 } else {
8359 editor.update(cx, |editor, cx| {
8360 editor.fold_buffer(buffer_id, cx);
8361 });
8362 }
8363 }
8364 }),
8365 ),
8366 )
8367 })
8368 .children(
8369 editor_read
8370 .addons
8371 .values()
8372 .filter_map(|addon| {
8373 addon.render_buffer_header_controls(for_excerpt, buffer, window, cx)
8374 })
8375 .take(1),
8376 )
8377 .when(!is_read_only, |this| {
8378 this.child(
8379 h_flex()
8380 .size_3()
8381 .justify_center()
8382 .flex_shrink_0()
8383 .children(indicator),
8384 )
8385 })
8386 .child(
8387 h_flex()
8388 .cursor_pointer()
8389 .id("path_header_block")
8390 .min_w_0()
8391 .size_full()
8392 .gap_1()
8393 .justify_between()
8394 .overflow_hidden()
8395 .child(h_flex().min_w_0().flex_1().gap_0p5().overflow_hidden().map(
8396 |path_header| {
8397 let filename = filename
8398 .map(SharedString::from)
8399 .unwrap_or_else(|| "untitled".into());
8400
8401 let full_path = match parent_path.as_deref() {
8402 Some(parent) if !parent.is_empty() => {
8403 format!("{}{}", parent, filename.as_str())
8404 }
8405 _ => filename.as_str().to_string(),
8406 };
8407
8408 path_header
8409 .child(
8410 ButtonLike::new("filename-button")
8411 .when(ItemSettings::get_global(cx).file_icons, |this| {
8412 let path = path::Path::new(filename.as_str());
8413 let icon = FileIcons::get_icon(path, cx)
8414 .unwrap_or_default();
8415
8416 this.child(
8417 Icon::from_path(icon).color(Color::Muted),
8418 )
8419 })
8420 .child(
8421 Label::new(filename)
8422 .single_line()
8423 .color(file_status_label_color(file_status))
8424 .buffer_font(cx)
8425 .when(
8426 file_status.is_some_and(|s| s.is_deleted()),
8427 |label| label.strikethrough(),
8428 ),
8429 )
8430 .tooltip(move |_, cx| {
8431 Tooltip::with_meta(
8432 "Open File",
8433 None,
8434 full_path.clone(),
8435 cx,
8436 )
8437 })
8438 .on_click(window.listener_for(editor, {
8439 let jump_data = jump_data.clone();
8440 move |editor, e: &ClickEvent, window, cx| {
8441 editor.open_excerpts_common(
8442 Some(jump_data.clone()),
8443 e.modifiers().secondary(),
8444 window,
8445 cx,
8446 );
8447 }
8448 })),
8449 )
8450 .when_some(parent_path, |then, path| {
8451 then.child(
8452 Label::new(path)
8453 .buffer_font(cx)
8454 .truncate_start()
8455 .color(
8456 if file_status
8457 .is_some_and(FileStatus::is_deleted)
8458 {
8459 Color::Custom(colors.text_disabled)
8460 } else {
8461 Color::Custom(colors.text_muted)
8462 },
8463 ),
8464 )
8465 })
8466 .when(!buffer.capability.editable(), |el| {
8467 el.child(Icon::new(IconName::FileLock).color(Color::Muted))
8468 })
8469 .when_some(breadcrumbs, |then, breadcrumbs| {
8470 let font = theme_settings::ThemeSettings::get_global(cx)
8471 .buffer_font
8472 .clone();
8473 then.child(render_breadcrumb_text(
8474 breadcrumbs,
8475 Some(font),
8476 None,
8477 editor_handle,
8478 true,
8479 window,
8480 cx,
8481 ))
8482 })
8483 },
8484 ))
8485 .when(can_open_excerpts && relative_path.is_some(), |this| {
8486 this.child(
8487 div()
8488 .when(!is_selected, |this| {
8489 this.visible_on_hover("buffer-header-group")
8490 })
8491 .child(
8492 Button::new("open-file-button", "Open File")
8493 .style(ButtonStyle::OutlinedGhost)
8494 .when(is_selected, |this| {
8495 this.key_binding(KeyBinding::for_action_in(
8496 &OpenExcerpts,
8497 &focus_handle,
8498 cx,
8499 ))
8500 })
8501 .on_click(window.listener_for(editor, {
8502 let jump_data = jump_data.clone();
8503 move |editor, e: &ClickEvent, window, cx| {
8504 editor.open_excerpts_common(
8505 Some(jump_data.clone()),
8506 e.modifiers().secondary(),
8507 window,
8508 cx,
8509 );
8510 }
8511 })),
8512 ),
8513 )
8514 })
8515 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
8516 .on_click(window.listener_for(editor, {
8517 let buffer_id = for_excerpt.buffer_id();
8518 move |editor, e: &ClickEvent, window, cx| {
8519 if e.modifiers().alt {
8520 editor.open_excerpts_common(
8521 Some(jump_data.clone()),
8522 e.modifiers().secondary(),
8523 window,
8524 cx,
8525 );
8526 return;
8527 }
8528
8529 if is_folded {
8530 editor.unfold_buffer(buffer_id, cx);
8531 } else {
8532 editor.fold_buffer(buffer_id, cx);
8533 }
8534 }
8535 })),
8536 ),
8537 );
8538
8539 let file = buffer.file().cloned();
8540 let editor = editor.clone();
8541
8542 right_click_menu("buffer-header-context-menu")
8543 .trigger(move |_, _, _| header)
8544 .menu(move |window, cx| {
8545 let menu_context = focus_handle.clone();
8546 let editor = editor.clone();
8547 let file = file.clone();
8548 ContextMenu::build(window, cx, move |mut menu, window, cx| {
8549 if let Some(file) = file
8550 && let Some(project) = editor.read(cx).project()
8551 && let Some(worktree) =
8552 project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
8553 {
8554 let path_style = file.path_style(cx);
8555 let worktree = worktree.read(cx);
8556 let relative_path = file.path();
8557 let entry_for_path = worktree.entry_for_path(relative_path);
8558 let abs_path = entry_for_path.map(|e| {
8559 e.canonical_path
8560 .as_deref()
8561 .map_or_else(|| worktree.absolutize(relative_path), Path::to_path_buf)
8562 });
8563 let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
8564
8565 let parent_abs_path = abs_path
8566 .as_ref()
8567 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
8568 let relative_path = has_relative_path
8569 .then_some(relative_path)
8570 .map(ToOwned::to_owned);
8571
8572 let visible_in_project_panel = relative_path.is_some() && worktree.is_visible();
8573 let reveal_in_project_panel = entry_for_path
8574 .filter(|_| visible_in_project_panel)
8575 .map(|entry| entry.id);
8576 menu = menu
8577 .when_some(abs_path, |menu, abs_path| {
8578 menu.entry(
8579 "Copy Path",
8580 Some(Box::new(zed_actions::workspace::CopyPath)),
8581 window.handler_for(&editor, move |_, _, cx| {
8582 cx.write_to_clipboard(ClipboardItem::new_string(
8583 abs_path.to_string_lossy().into_owned(),
8584 ));
8585 }),
8586 )
8587 })
8588 .when_some(relative_path, |menu, relative_path| {
8589 menu.entry(
8590 "Copy Relative Path",
8591 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
8592 window.handler_for(&editor, move |_, _, cx| {
8593 cx.write_to_clipboard(ClipboardItem::new_string(
8594 relative_path.display(path_style).to_string(),
8595 ));
8596 }),
8597 )
8598 })
8599 .when(
8600 reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
8601 |menu| menu.separator(),
8602 )
8603 .when_some(reveal_in_project_panel, |menu, entry_id| {
8604 menu.entry(
8605 "Reveal In Project Panel",
8606 Some(Box::new(RevealInProjectPanel::default())),
8607 window.handler_for(&editor, move |editor, _, cx| {
8608 if let Some(project) = &mut editor.project {
8609 project.update(cx, |_, cx| {
8610 cx.emit(project::Event::RevealInProjectPanel(entry_id))
8611 });
8612 }
8613 }),
8614 )
8615 })
8616 .when_some(parent_abs_path, |menu, parent_abs_path| {
8617 menu.entry(
8618 "Open in Terminal",
8619 Some(Box::new(OpenInTerminal)),
8620 window.handler_for(&editor, move |_, window, cx| {
8621 window.dispatch_action(
8622 OpenTerminal {
8623 working_directory: parent_abs_path.clone(),
8624 local: false,
8625 }
8626 .boxed_clone(),
8627 cx,
8628 );
8629 }),
8630 )
8631 });
8632 }
8633
8634 menu.context(menu_context)
8635 })
8636 })
8637}
8638
8639fn prepaint_gutter_button(
8640 mut button: AnyElement,
8641 row: DisplayRow,
8642 line_height: Pixels,
8643 gutter_dimensions: &GutterDimensions,
8644 scroll_position: gpui::Point<ScrollOffset>,
8645 gutter_hitbox: &Hitbox,
8646 window: &mut Window,
8647 cx: &mut App,
8648) -> AnyElement {
8649 let available_space = size(
8650 AvailableSpace::MinContent,
8651 AvailableSpace::Definite(line_height),
8652 );
8653 let indicator_size = button.layout_as_root(available_space, window, cx);
8654 let git_gutter_width = EditorElement::gutter_strip_width(line_height)
8655 + gutter_dimensions
8656 .git_blame_entries_width
8657 .unwrap_or_default();
8658
8659 let x = git_gutter_width + px(2.);
8660
8661 let mut y =
8662 Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
8663 y += (line_height - indicator_size.height) / 2.;
8664
8665 button.prepaint_as_root(
8666 gutter_hitbox.origin + point(x, y),
8667 available_space,
8668 window,
8669 cx,
8670 );
8671 button
8672}
8673
8674fn render_inline_blame_entry(
8675 blame_entry: BlameEntry,
8676 style: &EditorStyle,
8677 cx: &mut App,
8678) -> Option<AnyElement> {
8679 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8680 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
8681}
8682
8683fn render_blame_entry_popover(
8684 blame_entry: BlameEntry,
8685 scroll_handle: ScrollHandle,
8686 commit_message: Option<ParsedCommitMessage>,
8687 markdown: Entity<Markdown>,
8688 workspace: WeakEntity<Workspace>,
8689 blame: &Entity<GitBlame>,
8690 buffer: BufferId,
8691 window: &mut Window,
8692 cx: &mut App,
8693) -> Option<AnyElement> {
8694 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8695 let blame = blame.read(cx);
8696 let repository = blame.repository(cx, buffer)?;
8697 renderer.render_blame_entry_popover(
8698 blame_entry,
8699 scroll_handle,
8700 commit_message,
8701 markdown,
8702 repository,
8703 workspace,
8704 window,
8705 cx,
8706 )
8707}
8708
8709fn render_blame_entry(
8710 ix: usize,
8711 blame: &Entity<GitBlame>,
8712 blame_entry: BlameEntry,
8713 style: &EditorStyle,
8714 last_used_color: &mut Option<(Hsla, Oid)>,
8715 editor: Entity<Editor>,
8716 workspace: Entity<Workspace>,
8717 buffer: BufferId,
8718 renderer: &dyn BlameRenderer,
8719 window: &mut Window,
8720 cx: &mut App,
8721) -> Option<AnyElement> {
8722 let index: u32 = blame_entry.sha.into();
8723 let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
8724
8725 // If the last color we used is the same as the one we get for this line, but
8726 // the commit SHAs are different, then we try again to get a different color.
8727 if let Some((color, sha)) = *last_used_color
8728 && sha != blame_entry.sha
8729 && color == sha_color
8730 {
8731 sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
8732 }
8733 last_used_color.replace((sha_color, blame_entry.sha));
8734
8735 let blame = blame.read(cx);
8736 let details = blame.details_for_entry(buffer, &blame_entry);
8737 let repository = blame.repository(cx, buffer)?;
8738 renderer.render_blame_entry(
8739 &style.text,
8740 blame_entry,
8741 details,
8742 repository,
8743 workspace.downgrade(),
8744 editor,
8745 ix,
8746 sha_color,
8747 window,
8748 cx,
8749 )
8750}
8751
8752#[derive(Debug)]
8753pub(crate) struct LineWithInvisibles {
8754 fragments: SmallVec<[LineFragment; 1]>,
8755 invisibles: Vec<Invisible>,
8756 len: usize,
8757 pub(crate) width: Pixels,
8758 font_size: Pixels,
8759}
8760
8761enum LineFragment {
8762 Text(ShapedLine),
8763 Element {
8764 id: ChunkRendererId,
8765 element: Option<AnyElement>,
8766 size: Size<Pixels>,
8767 len: usize,
8768 },
8769}
8770
8771impl fmt::Debug for LineFragment {
8772 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8773 match self {
8774 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
8775 LineFragment::Element { size, len, .. } => f
8776 .debug_struct("Element")
8777 .field("size", size)
8778 .field("len", len)
8779 .finish(),
8780 }
8781 }
8782}
8783
8784impl LineWithInvisibles {
8785 fn from_chunks<'a>(
8786 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
8787 editor_style: &EditorStyle,
8788 max_line_len: usize,
8789 max_line_count: usize,
8790 editor_mode: &EditorMode,
8791 text_width: Pixels,
8792 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8793 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
8794 window: &mut Window,
8795 cx: &mut App,
8796 ) -> Vec<Self> {
8797 let text_style = &editor_style.text;
8798 let mut layouts = Vec::with_capacity(max_line_count);
8799 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
8800 let mut line = String::new();
8801 let mut invisibles = Vec::new();
8802 let mut width = Pixels::ZERO;
8803 let mut len = 0;
8804 let mut styles = Vec::new();
8805 let mut non_whitespace_added = false;
8806 let mut row = 0;
8807 let mut line_exceeded_max_len = false;
8808 let font_size = text_style.font_size.to_pixels(window.rem_size());
8809 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
8810
8811 let ellipsis = SharedString::from("β―");
8812
8813 for highlighted_chunk in chunks.chain([HighlightedChunk {
8814 text: "\n",
8815 style: None,
8816 is_tab: false,
8817 is_inlay: false,
8818 replacement: None,
8819 }]) {
8820 if let Some(replacement) = highlighted_chunk.replacement {
8821 if !line.is_empty() {
8822 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8823 let text_runs: &[TextRun] = if segments.is_empty() {
8824 &styles
8825 } else {
8826 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8827 };
8828 let shaped_line = window.text_system().shape_line(
8829 line.clone().into(),
8830 font_size,
8831 text_runs,
8832 None,
8833 );
8834 width += shaped_line.width;
8835 len += shaped_line.len;
8836 fragments.push(LineFragment::Text(shaped_line));
8837 line.clear();
8838 styles.clear();
8839 }
8840
8841 match replacement {
8842 ChunkReplacement::Renderer(renderer) => {
8843 let available_width = if renderer.constrain_width {
8844 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
8845 ellipsis.clone()
8846 } else {
8847 SharedString::from(Arc::from(highlighted_chunk.text))
8848 };
8849 let shaped_line = window.text_system().shape_line(
8850 chunk,
8851 font_size,
8852 &[text_style.to_run(highlighted_chunk.text.len())],
8853 None,
8854 );
8855 AvailableSpace::Definite(shaped_line.width)
8856 } else {
8857 AvailableSpace::MinContent
8858 };
8859
8860 let mut element = (renderer.render)(&mut ChunkRendererContext {
8861 context: cx,
8862 window,
8863 max_width: text_width,
8864 });
8865 let line_height = text_style.line_height_in_pixels(window.rem_size());
8866 let size = element.layout_as_root(
8867 size(available_width, AvailableSpace::Definite(line_height)),
8868 window,
8869 cx,
8870 );
8871
8872 width += size.width;
8873 len += highlighted_chunk.text.len();
8874 fragments.push(LineFragment::Element {
8875 id: renderer.id,
8876 element: Some(element),
8877 size,
8878 len: highlighted_chunk.text.len(),
8879 });
8880 }
8881 ChunkReplacement::Str(x) => {
8882 let text_style = if let Some(style) = highlighted_chunk.style {
8883 Cow::Owned(text_style.clone().highlight(style))
8884 } else {
8885 Cow::Borrowed(text_style)
8886 };
8887
8888 let run = TextRun {
8889 len: x.len(),
8890 font: text_style.font(),
8891 color: text_style.color,
8892 background_color: text_style.background_color,
8893 underline: text_style.underline,
8894 strikethrough: text_style.strikethrough,
8895 };
8896 let line_layout = window
8897 .text_system()
8898 .shape_line(x, font_size, &[run], None)
8899 .with_len(highlighted_chunk.text.len());
8900
8901 width += line_layout.width;
8902 len += highlighted_chunk.text.len();
8903 fragments.push(LineFragment::Text(line_layout))
8904 }
8905 }
8906 } else {
8907 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
8908 if ix > 0 {
8909 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8910 let text_runs = if segments.is_empty() {
8911 &styles
8912 } else {
8913 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8914 };
8915 let shaped_line = window.text_system().shape_line(
8916 line.clone().into(),
8917 font_size,
8918 text_runs,
8919 None,
8920 );
8921 width += shaped_line.width;
8922 len += shaped_line.len;
8923 fragments.push(LineFragment::Text(shaped_line));
8924 layouts.push(Self {
8925 width: mem::take(&mut width),
8926 len: mem::take(&mut len),
8927 fragments: mem::take(&mut fragments),
8928 invisibles: std::mem::take(&mut invisibles),
8929 font_size,
8930 });
8931
8932 line.clear();
8933 styles.clear();
8934 row += 1;
8935 line_exceeded_max_len = false;
8936 non_whitespace_added = false;
8937 if row == max_line_count {
8938 return layouts;
8939 }
8940 }
8941
8942 if !line_chunk.is_empty() && !line_exceeded_max_len {
8943 let text_style = if let Some(style) = highlighted_chunk.style {
8944 Cow::Owned(text_style.clone().highlight(style))
8945 } else {
8946 Cow::Borrowed(text_style)
8947 };
8948
8949 if line.len() + line_chunk.len() > max_line_len {
8950 let mut chunk_len = max_line_len - line.len();
8951 while !line_chunk.is_char_boundary(chunk_len) {
8952 chunk_len -= 1;
8953 }
8954 line_chunk = &line_chunk[..chunk_len];
8955 line_exceeded_max_len = true;
8956 }
8957
8958 styles.push(TextRun {
8959 len: line_chunk.len(),
8960 font: text_style.font(),
8961 color: text_style.color,
8962 background_color: text_style.background_color,
8963 underline: text_style.underline,
8964 strikethrough: text_style.strikethrough,
8965 });
8966
8967 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
8968 // Line wrap pads its contents with fake whitespaces,
8969 // avoid printing them
8970 let is_soft_wrapped = is_row_soft_wrapped(row);
8971 if highlighted_chunk.is_tab {
8972 if non_whitespace_added || !is_soft_wrapped {
8973 invisibles.push(Invisible::Tab {
8974 line_start_offset: line.len(),
8975 line_end_offset: line.len() + line_chunk.len(),
8976 });
8977 }
8978 } else {
8979 invisibles.extend(line_chunk.char_indices().filter_map(
8980 |(index, c)| {
8981 let is_whitespace = c.is_whitespace();
8982 non_whitespace_added |= !is_whitespace;
8983 if is_whitespace
8984 && (non_whitespace_added || !is_soft_wrapped)
8985 {
8986 Some(Invisible::Whitespace {
8987 line_offset: line.len() + index,
8988 })
8989 } else {
8990 None
8991 }
8992 },
8993 ))
8994 }
8995 }
8996
8997 line.push_str(line_chunk);
8998 }
8999 }
9000 }
9001 }
9002
9003 layouts
9004 }
9005
9006 /// Takes text runs and non-overlapping left-to-right background ranges with color.
9007 /// Returns new text runs with adjusted contrast as per background ranges.
9008 fn split_runs_by_bg_segments(
9009 text_runs: &[TextRun],
9010 bg_segments: &[(Range<DisplayPoint>, Hsla)],
9011 min_contrast: f32,
9012 start_col_offset: usize,
9013 ) -> Vec<TextRun> {
9014 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
9015 let mut line_col = start_col_offset;
9016 let mut segment_ix = 0usize;
9017
9018 for text_run in text_runs.iter() {
9019 let run_start_col = line_col;
9020 let run_end_col = run_start_col + text_run.len;
9021 while segment_ix < bg_segments.len()
9022 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
9023 {
9024 segment_ix += 1;
9025 }
9026 let mut cursor_col = run_start_col;
9027 let mut local_segment_ix = segment_ix;
9028 while local_segment_ix < bg_segments.len() {
9029 let (range, segment_color) = &bg_segments[local_segment_ix];
9030 let segment_start_col = range.start.column() as usize;
9031 let segment_end_col = range.end.column() as usize;
9032 if segment_start_col >= run_end_col {
9033 break;
9034 }
9035 if segment_start_col > cursor_col {
9036 let span_len = segment_start_col - cursor_col;
9037 output_runs.push(TextRun {
9038 len: span_len,
9039 font: text_run.font.clone(),
9040 color: text_run.color,
9041 background_color: text_run.background_color,
9042 underline: text_run.underline,
9043 strikethrough: text_run.strikethrough,
9044 });
9045 cursor_col = segment_start_col;
9046 }
9047 let segment_slice_end_col = segment_end_col.min(run_end_col);
9048 if segment_slice_end_col > cursor_col {
9049 let new_text_color =
9050 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
9051 output_runs.push(TextRun {
9052 len: segment_slice_end_col - cursor_col,
9053 font: text_run.font.clone(),
9054 color: new_text_color,
9055 background_color: text_run.background_color,
9056 underline: text_run.underline,
9057 strikethrough: text_run.strikethrough,
9058 });
9059 cursor_col = segment_slice_end_col;
9060 }
9061 if segment_end_col >= run_end_col {
9062 break;
9063 }
9064 local_segment_ix += 1;
9065 }
9066 if cursor_col < run_end_col {
9067 output_runs.push(TextRun {
9068 len: run_end_col - cursor_col,
9069 font: text_run.font.clone(),
9070 color: text_run.color,
9071 background_color: text_run.background_color,
9072 underline: text_run.underline,
9073 strikethrough: text_run.strikethrough,
9074 });
9075 }
9076 line_col = run_end_col;
9077 segment_ix = local_segment_ix;
9078 }
9079 output_runs
9080 }
9081
9082 fn prepaint(
9083 &mut self,
9084 line_height: Pixels,
9085 scroll_position: gpui::Point<ScrollOffset>,
9086 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
9087 row: DisplayRow,
9088 content_origin: gpui::Point<Pixels>,
9089 line_elements: &mut SmallVec<[AnyElement; 1]>,
9090 window: &mut Window,
9091 cx: &mut App,
9092 ) {
9093 let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
9094 self.prepaint_with_custom_offset(
9095 line_height,
9096 scroll_pixel_position,
9097 content_origin,
9098 line_y,
9099 line_elements,
9100 window,
9101 cx,
9102 );
9103 }
9104
9105 fn prepaint_with_custom_offset(
9106 &mut self,
9107 line_height: Pixels,
9108 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
9109 content_origin: gpui::Point<Pixels>,
9110 line_y: Pixels,
9111 line_elements: &mut SmallVec<[AnyElement; 1]>,
9112 window: &mut Window,
9113 cx: &mut App,
9114 ) {
9115 let mut fragment_origin =
9116 content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
9117 for fragment in &mut self.fragments {
9118 match fragment {
9119 LineFragment::Text(line) => {
9120 fragment_origin.x += line.width;
9121 }
9122 LineFragment::Element { element, size, .. } => {
9123 let mut element = element
9124 .take()
9125 .expect("you can't prepaint LineWithInvisibles twice");
9126
9127 // Center the element vertically within the line.
9128 let mut element_origin = fragment_origin;
9129 element_origin.y += (line_height - size.height) / 2.;
9130 element.prepaint_at(element_origin, window, cx);
9131 line_elements.push(element);
9132
9133 fragment_origin.x += size.width;
9134 }
9135 }
9136 }
9137 }
9138
9139 fn draw(
9140 &self,
9141 layout: &EditorLayout,
9142 row: DisplayRow,
9143 content_origin: gpui::Point<Pixels>,
9144 whitespace_setting: ShowWhitespaceSetting,
9145 selection_ranges: &[Range<DisplayPoint>],
9146 window: &mut Window,
9147 cx: &mut App,
9148 ) {
9149 self.draw_with_custom_offset(
9150 layout,
9151 row,
9152 content_origin,
9153 layout.position_map.line_height
9154 * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
9155 whitespace_setting,
9156 selection_ranges,
9157 window,
9158 cx,
9159 );
9160 }
9161
9162 fn draw_with_custom_offset(
9163 &self,
9164 layout: &EditorLayout,
9165 row: DisplayRow,
9166 content_origin: gpui::Point<Pixels>,
9167 line_y: Pixels,
9168 whitespace_setting: ShowWhitespaceSetting,
9169 selection_ranges: &[Range<DisplayPoint>],
9170 window: &mut Window,
9171 cx: &mut App,
9172 ) {
9173 let line_height = layout.position_map.line_height;
9174 let mut fragment_origin = content_origin
9175 + gpui::point(
9176 Pixels::from(-layout.position_map.scroll_pixel_position.x),
9177 line_y,
9178 );
9179
9180 for fragment in &self.fragments {
9181 match fragment {
9182 LineFragment::Text(line) => {
9183 line.paint(
9184 fragment_origin,
9185 line_height,
9186 layout.text_align,
9187 Some(layout.content_width),
9188 window,
9189 cx,
9190 )
9191 .log_err();
9192 fragment_origin.x += line.width;
9193 }
9194 LineFragment::Element { size, .. } => {
9195 fragment_origin.x += size.width;
9196 }
9197 }
9198 }
9199
9200 self.draw_invisibles(
9201 selection_ranges,
9202 layout,
9203 content_origin,
9204 line_y,
9205 row,
9206 line_height,
9207 whitespace_setting,
9208 window,
9209 cx,
9210 );
9211 }
9212
9213 fn draw_background(
9214 &self,
9215 layout: &EditorLayout,
9216 row: DisplayRow,
9217 content_origin: gpui::Point<Pixels>,
9218 window: &mut Window,
9219 cx: &mut App,
9220 ) {
9221 let line_height = layout.position_map.line_height;
9222 let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
9223
9224 let mut fragment_origin = content_origin
9225 + gpui::point(
9226 Pixels::from(-layout.position_map.scroll_pixel_position.x),
9227 line_y,
9228 );
9229
9230 for fragment in &self.fragments {
9231 match fragment {
9232 LineFragment::Text(line) => {
9233 line.paint_background(
9234 fragment_origin,
9235 line_height,
9236 layout.text_align,
9237 Some(layout.content_width),
9238 window,
9239 cx,
9240 )
9241 .log_err();
9242 fragment_origin.x += line.width;
9243 }
9244 LineFragment::Element { size, .. } => {
9245 fragment_origin.x += size.width;
9246 }
9247 }
9248 }
9249 }
9250
9251 fn draw_invisibles(
9252 &self,
9253 selection_ranges: &[Range<DisplayPoint>],
9254 layout: &EditorLayout,
9255 content_origin: gpui::Point<Pixels>,
9256 line_y: Pixels,
9257 row: DisplayRow,
9258 line_height: Pixels,
9259 whitespace_setting: ShowWhitespaceSetting,
9260 window: &mut Window,
9261 cx: &mut App,
9262 ) {
9263 let extract_whitespace_info = |invisible: &Invisible| {
9264 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
9265 Invisible::Tab {
9266 line_start_offset,
9267 line_end_offset,
9268 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
9269 Invisible::Whitespace { line_offset } => {
9270 (*line_offset, line_offset + 1, &layout.space_invisible)
9271 }
9272 };
9273
9274 let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
9275 let invisible_offset: ScrollPixelOffset =
9276 ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
9277 .into();
9278 let origin = content_origin
9279 + gpui::point(
9280 Pixels::from(
9281 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
9282 ),
9283 line_y,
9284 );
9285
9286 (
9287 [token_offset, token_end_offset],
9288 Box::new(move |window: &mut Window, cx: &mut App| {
9289 invisible_symbol
9290 .paint(origin, line_height, TextAlign::Left, None, window, cx)
9291 .log_err();
9292 }),
9293 )
9294 };
9295
9296 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
9297 match whitespace_setting {
9298 ShowWhitespaceSetting::None => (),
9299 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
9300 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
9301 let invisible_point = DisplayPoint::new(row, start as u32);
9302 if !selection_ranges
9303 .iter()
9304 .any(|region| region.start <= invisible_point && invisible_point < region.end)
9305 {
9306 return;
9307 }
9308
9309 paint(window, cx);
9310 }),
9311
9312 ShowWhitespaceSetting::Trailing => {
9313 let mut previous_start = self.len;
9314 for ([start, end], paint) in invisible_iter.rev() {
9315 if previous_start != end {
9316 break;
9317 }
9318 previous_start = start;
9319 paint(window, cx);
9320 }
9321 }
9322
9323 // For a whitespace to be on a boundary, any of the following conditions need to be met:
9324 // - It is a tab
9325 // - It is adjacent to an edge (start or end)
9326 // - It is adjacent to a whitespace (left or right)
9327 ShowWhitespaceSetting::Boundary => {
9328 // 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
9329 // the above cases.
9330 // Note: We zip in the original `invisibles` to check for tab equality
9331 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
9332 for (([start, end], paint), invisible) in
9333 invisible_iter.zip_eq(self.invisibles.iter())
9334 {
9335 let should_render = match (&last_seen, invisible) {
9336 (_, Invisible::Tab { .. }) => true,
9337 (Some((_, last_end, _)), _) => *last_end == start,
9338 _ => false,
9339 };
9340
9341 if should_render || start == 0 || end == self.len {
9342 paint(window, cx);
9343
9344 // Since we are scanning from the left, we will skip over the first available whitespace that is part
9345 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
9346 if let Some((should_render_last, last_end, paint_last)) = last_seen {
9347 // Note that we need to make sure that the last one is actually adjacent
9348 if !should_render_last && last_end == start {
9349 paint_last(window, cx);
9350 }
9351 }
9352 }
9353
9354 // Manually render anything within a selection
9355 let invisible_point = DisplayPoint::new(row, start as u32);
9356 if selection_ranges.iter().any(|region| {
9357 region.start <= invisible_point && invisible_point < region.end
9358 }) {
9359 paint(window, cx);
9360 }
9361
9362 last_seen = Some((should_render, end, paint));
9363 }
9364 }
9365 }
9366 }
9367
9368 pub fn x_for_index(&self, index: usize) -> Pixels {
9369 let mut fragment_start_x = Pixels::ZERO;
9370 let mut fragment_start_index = 0;
9371
9372 for fragment in &self.fragments {
9373 match fragment {
9374 LineFragment::Text(shaped_line) => {
9375 let fragment_end_index = fragment_start_index + shaped_line.len;
9376 if index < fragment_end_index {
9377 return fragment_start_x
9378 + shaped_line.x_for_index(index - fragment_start_index);
9379 }
9380 fragment_start_x += shaped_line.width;
9381 fragment_start_index = fragment_end_index;
9382 }
9383 LineFragment::Element { len, size, .. } => {
9384 let fragment_end_index = fragment_start_index + len;
9385 if index < fragment_end_index {
9386 return fragment_start_x;
9387 }
9388 fragment_start_x += size.width;
9389 fragment_start_index = fragment_end_index;
9390 }
9391 }
9392 }
9393
9394 fragment_start_x
9395 }
9396
9397 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
9398 let mut fragment_start_x = Pixels::ZERO;
9399 let mut fragment_start_index = 0;
9400
9401 for fragment in &self.fragments {
9402 match fragment {
9403 LineFragment::Text(shaped_line) => {
9404 let fragment_end_x = fragment_start_x + shaped_line.width;
9405 if x < fragment_end_x {
9406 return Some(
9407 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
9408 );
9409 }
9410 fragment_start_x = fragment_end_x;
9411 fragment_start_index += shaped_line.len;
9412 }
9413 LineFragment::Element { len, size, .. } => {
9414 let fragment_end_x = fragment_start_x + size.width;
9415 if x < fragment_end_x {
9416 return Some(fragment_start_index);
9417 }
9418 fragment_start_index += len;
9419 fragment_start_x = fragment_end_x;
9420 }
9421 }
9422 }
9423
9424 None
9425 }
9426
9427 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
9428 let mut fragment_start_index = 0;
9429
9430 for fragment in &self.fragments {
9431 match fragment {
9432 LineFragment::Text(shaped_line) => {
9433 let fragment_end_index = fragment_start_index + shaped_line.len;
9434 if index < fragment_end_index {
9435 return shaped_line.font_id_for_index(index - fragment_start_index);
9436 }
9437 fragment_start_index = fragment_end_index;
9438 }
9439 LineFragment::Element { len, .. } => {
9440 let fragment_end_index = fragment_start_index + len;
9441 if index < fragment_end_index {
9442 return None;
9443 }
9444 fragment_start_index = fragment_end_index;
9445 }
9446 }
9447 }
9448
9449 None
9450 }
9451
9452 pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
9453 let line_width = self.width;
9454 match text_align {
9455 TextAlign::Left => px(0.0),
9456 TextAlign::Center => (content_width - line_width) / 2.0,
9457 TextAlign::Right => content_width - line_width,
9458 }
9459 }
9460}
9461
9462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9463enum Invisible {
9464 /// A tab character
9465 ///
9466 /// A tab character is internally represented by spaces (configured by the user's tab width)
9467 /// aligned to the nearest column, so it's necessary to store the start and end offset for
9468 /// adjacency checks.
9469 Tab {
9470 line_start_offset: usize,
9471 line_end_offset: usize,
9472 },
9473 Whitespace {
9474 line_offset: usize,
9475 },
9476}
9477
9478impl EditorElement {
9479 /// Returns the rem size to use when rendering the [`EditorElement`].
9480 ///
9481 /// This allows UI elements to scale based on the `buffer_font_size`.
9482 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
9483 match self.editor.read(cx).mode {
9484 EditorMode::Full {
9485 scale_ui_elements_with_buffer_font_size: true,
9486 ..
9487 }
9488 | EditorMode::Minimap { .. } => {
9489 let buffer_font_size = self.style.text.font_size;
9490 match buffer_font_size {
9491 AbsoluteLength::Pixels(pixels) => {
9492 let rem_size_scale = {
9493 // Our default UI font size is 14px on a 16px base scale.
9494 // This means the default UI font size is 0.875rems.
9495 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
9496
9497 // We then determine the delta between a single rem and the default font
9498 // size scale.
9499 let default_font_size_delta = 1. - default_font_size_scale;
9500
9501 // Finally, we add this delta to 1rem to get the scale factor that
9502 // should be used to scale up the UI.
9503 1. + default_font_size_delta
9504 };
9505
9506 Some(pixels * rem_size_scale)
9507 }
9508 AbsoluteLength::Rems(rems) => {
9509 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
9510 }
9511 }
9512 }
9513 // We currently use single-line and auto-height editors in UI contexts,
9514 // so we don't want to scale everything with the buffer font size, as it
9515 // ends up looking off.
9516 _ => None,
9517 }
9518 }
9519
9520 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
9521 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
9522 parent.upgrade()
9523 } else {
9524 Some(self.editor.clone())
9525 }
9526 }
9527}
9528
9529#[derive(Default)]
9530pub struct EditorRequestLayoutState {
9531 // We use prepaint depth to limit the number of times prepaint is
9532 // called recursively. We need this so that we can update stale
9533 // data for e.g. block heights in block map.
9534 prepaint_depth: Rc<Cell<usize>>,
9535}
9536
9537impl EditorRequestLayoutState {
9538 // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
9539 // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
9540 // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
9541 // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
9542 // that subsequent shrinking does not lead to incorrect block placing.
9543 const MAX_PREPAINT_DEPTH: usize = 5;
9544
9545 fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
9546 let depth = self.prepaint_depth.get();
9547 self.prepaint_depth.set(depth + 1);
9548 EditorPrepaintGuard {
9549 prepaint_depth: self.prepaint_depth.clone(),
9550 }
9551 }
9552
9553 fn has_remaining_prepaint_depth(&self) -> bool {
9554 self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
9555 }
9556}
9557
9558struct EditorPrepaintGuard {
9559 prepaint_depth: Rc<Cell<usize>>,
9560}
9561
9562impl Drop for EditorPrepaintGuard {
9563 fn drop(&mut self) {
9564 let depth = self.prepaint_depth.get();
9565 self.prepaint_depth.set(depth.saturating_sub(1));
9566 }
9567}
9568
9569impl Element for EditorElement {
9570 type RequestLayoutState = EditorRequestLayoutState;
9571 type PrepaintState = EditorLayout;
9572
9573 fn id(&self) -> Option<ElementId> {
9574 None
9575 }
9576
9577 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
9578 None
9579 }
9580
9581 fn request_layout(
9582 &mut self,
9583 _: Option<&GlobalElementId>,
9584 _inspector_id: Option<&gpui::InspectorElementId>,
9585 window: &mut Window,
9586 cx: &mut App,
9587 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
9588 let rem_size = self.rem_size(cx);
9589 window.with_rem_size(rem_size, |window| {
9590 self.editor.update(cx, |editor, cx| {
9591 editor.set_style(self.style.clone(), window, cx);
9592
9593 let layout_id = match editor.mode {
9594 EditorMode::SingleLine => {
9595 let rem_size = window.rem_size();
9596 let height = self.style.text.line_height_in_pixels(rem_size);
9597 let mut style = Style::default();
9598 style.size.height = height.into();
9599 style.size.width = relative(1.).into();
9600 window.request_layout(style, None, cx)
9601 }
9602 EditorMode::AutoHeight {
9603 min_lines,
9604 max_lines,
9605 } => {
9606 let editor_handle = cx.entity();
9607 window.request_measured_layout(
9608 Style::default(),
9609 move |known_dimensions, available_space, window, cx| {
9610 editor_handle
9611 .update(cx, |editor, cx| {
9612 compute_auto_height_layout(
9613 editor,
9614 min_lines,
9615 max_lines,
9616 known_dimensions,
9617 available_space.width,
9618 window,
9619 cx,
9620 )
9621 })
9622 .unwrap_or_default()
9623 },
9624 )
9625 }
9626 EditorMode::Minimap { .. } => {
9627 let mut style = Style::default();
9628 style.size.width = relative(1.).into();
9629 style.size.height = relative(1.).into();
9630 window.request_layout(style, None, cx)
9631 }
9632 EditorMode::Full {
9633 sizing_behavior, ..
9634 } => {
9635 let mut style = Style::default();
9636 style.size.width = relative(1.).into();
9637 if sizing_behavior == SizingBehavior::SizeByContent {
9638 let snapshot = editor.snapshot(window, cx);
9639 let line_height =
9640 self.style.text.line_height_in_pixels(window.rem_size());
9641 let scroll_height =
9642 (snapshot.max_point().row().next_row().0 as f32) * line_height;
9643 style.size.height = scroll_height.into();
9644 } else {
9645 style.size.height = relative(1.).into();
9646 }
9647 window.request_layout(style, None, cx)
9648 }
9649 };
9650
9651 (layout_id, EditorRequestLayoutState::default())
9652 })
9653 })
9654 }
9655
9656 fn prepaint(
9657 &mut self,
9658 _: Option<&GlobalElementId>,
9659 _inspector_id: Option<&gpui::InspectorElementId>,
9660 bounds: Bounds<Pixels>,
9661 request_layout: &mut Self::RequestLayoutState,
9662 window: &mut Window,
9663 cx: &mut App,
9664 ) -> Self::PrepaintState {
9665 let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
9666 let text_style = TextStyleRefinement {
9667 font_size: Some(self.style.text.font_size),
9668 line_height: Some(self.style.text.line_height),
9669 ..Default::default()
9670 };
9671
9672 let is_minimap = self.editor.read(cx).mode.is_minimap();
9673 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
9674
9675 if !is_minimap {
9676 let focus_handle = self.editor.focus_handle(cx);
9677 window.set_view_id(self.editor.entity_id());
9678 window.set_focus_handle(&focus_handle, cx);
9679 }
9680
9681 let rem_size = self.rem_size(cx);
9682 window.with_rem_size(rem_size, |window| {
9683 window.with_text_style(Some(text_style), |window| {
9684 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9685 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
9686 (editor.snapshot(window, cx), editor.read_only(cx))
9687 });
9688 let style = &self.style;
9689
9690 let rem_size = window.rem_size();
9691 let font_id = window.text_system().resolve_font(&style.text.font());
9692 let font_size = style.text.font_size.to_pixels(rem_size);
9693 let line_height = style.text.line_height_in_pixels(rem_size);
9694 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
9695 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
9696 let em_layout_width = window.text_system().em_layout_width(font_id, font_size);
9697 let glyph_grid_cell = size(em_advance, line_height);
9698
9699 let gutter_dimensions =
9700 snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
9701 let text_width = bounds.size.width - gutter_dimensions.width;
9702
9703 let settings = EditorSettings::get_global(cx);
9704 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
9705 let vertical_scrollbar_width = (scrollbars_shown
9706 && settings.scrollbar.axes.vertical
9707 && self.editor.read(cx).show_scrollbars.vertical)
9708 .then_some(style.scrollbar_width)
9709 .unwrap_or_default();
9710 let minimap_width = self
9711 .get_minimap_width(
9712 &settings.minimap,
9713 scrollbars_shown,
9714 text_width,
9715 em_width,
9716 font_size,
9717 rem_size,
9718 cx,
9719 )
9720 .unwrap_or_default();
9721
9722 let right_margin = minimap_width + vertical_scrollbar_width;
9723
9724 let extended_right = 2 * em_width + right_margin;
9725 let editor_width = text_width - gutter_dimensions.margin - extended_right;
9726 let editor_margins = EditorMargins {
9727 gutter: gutter_dimensions,
9728 right: right_margin,
9729 extended_right,
9730 };
9731
9732 snapshot = self.editor.update(cx, |editor, cx| {
9733 editor.last_bounds = Some(bounds);
9734 editor.gutter_dimensions = gutter_dimensions;
9735 editor.set_visible_line_count(
9736 (bounds.size.height / line_height) as f64,
9737 window,
9738 cx,
9739 );
9740 editor.set_visible_column_count(f64::from(editor_width / em_advance));
9741
9742 if matches!(
9743 editor.mode,
9744 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
9745 ) {
9746 snapshot
9747 } else {
9748 let wrap_width = calculate_wrap_width(
9749 editor.soft_wrap_mode(cx),
9750 editor_width,
9751 em_layout_width,
9752 );
9753
9754 if editor.set_wrap_width(wrap_width, cx) {
9755 editor.snapshot(window, cx)
9756 } else {
9757 snapshot
9758 }
9759 }
9760 });
9761
9762 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
9763 let gutter_hitbox = window.insert_hitbox(
9764 gutter_bounds(bounds, gutter_dimensions),
9765 HitboxBehavior::Normal,
9766 );
9767 let text_hitbox = window.insert_hitbox(
9768 Bounds {
9769 origin: gutter_hitbox.top_right(),
9770 size: size(text_width, bounds.size.height),
9771 },
9772 HitboxBehavior::Normal,
9773 );
9774
9775 // Offset the content_bounds from the text_bounds by the gutter margin (which
9776 // is roughly half a character wide) to make hit testing work more like how we want.
9777 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
9778 let content_origin = text_hitbox.origin + content_offset;
9779
9780 let height_in_lines = f64::from(bounds.size.height / line_height);
9781 let max_row = snapshot.max_point().row().as_f64();
9782
9783 // Calculate how much of the editor is clipped by parent containers (e.g., List).
9784 // This allows us to only render lines that are actually visible, which is
9785 // critical for performance when large AutoHeight editors are inside Lists.
9786 let visible_bounds = window.content_mask().bounds;
9787 let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
9788 let clipped_top_in_lines = f64::from(clipped_top / line_height);
9789 let visible_height_in_lines =
9790 f64::from(visible_bounds.size.height / line_height);
9791
9792 // The max scroll position for the top of the window
9793 let scroll_beyond_last_line = self.editor.read(cx).scroll_beyond_last_line(cx);
9794 let max_scroll_top = match scroll_beyond_last_line {
9795 ScrollBeyondLastLine::OnePage => max_row,
9796 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
9797 ScrollBeyondLastLine::VerticalScrollMargin => {
9798 let settings = EditorSettings::get_global(cx);
9799 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
9800 .max(0.)
9801 }
9802 };
9803
9804 let (
9805 autoscroll_request,
9806 autoscroll_containing_element,
9807 needs_horizontal_autoscroll,
9808 ) = self.editor.update(cx, |editor, cx| {
9809 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
9810
9811 let autoscroll_containing_element =
9812 autoscroll_request.is_some() || editor.has_pending_selection();
9813
9814 let (needs_horizontal_autoscroll, was_scrolled) = editor
9815 .autoscroll_vertically(
9816 bounds,
9817 line_height,
9818 max_scroll_top,
9819 autoscroll_request,
9820 window,
9821 cx,
9822 );
9823 if was_scrolled.0 {
9824 snapshot = editor.snapshot(window, cx);
9825 }
9826 (
9827 autoscroll_request,
9828 autoscroll_containing_element,
9829 needs_horizontal_autoscroll,
9830 )
9831 });
9832
9833 let mut scroll_position = snapshot.scroll_position();
9834 // The scroll position is a fractional point, the whole number of which represents
9835 // the top of the window in terms of display rows.
9836 // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
9837 // but we don't modify scroll_position itself since the parent handles positioning.
9838 let max_row = snapshot.max_point().row();
9839 let start_row = cmp::min(
9840 DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
9841 max_row,
9842 );
9843 let end_row = cmp::min(
9844 (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
9845 as u32,
9846 max_row.next_row().0,
9847 );
9848 let end_row = DisplayRow(end_row);
9849
9850 let row_infos = snapshot // note we only get the visual range
9851 .row_infos(start_row)
9852 .take((start_row..end_row).len())
9853 .collect::<Vec<RowInfo>>();
9854 let is_row_soft_wrapped = |row: usize| {
9855 row_infos
9856 .get(row)
9857 .is_none_or(|info| info.buffer_row.is_none())
9858 };
9859
9860 let start_anchor = if start_row == Default::default() {
9861 Anchor::Min
9862 } else {
9863 snapshot.buffer_snapshot().anchor_before(
9864 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
9865 )
9866 };
9867 let end_anchor = if end_row > max_row {
9868 Anchor::Max
9869 } else {
9870 snapshot.buffer_snapshot().anchor_before(
9871 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
9872 )
9873 };
9874
9875 let mut highlighted_rows = self
9876 .editor
9877 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
9878
9879 let is_light = cx.theme().appearance().is_light();
9880
9881 let mut highlighted_ranges = self
9882 .editor_with_selections(cx)
9883 .map(|editor| {
9884 if editor == self.editor {
9885 editor.read(cx).background_highlights_in_range(
9886 start_anchor..end_anchor,
9887 &snapshot.display_snapshot,
9888 cx.theme(),
9889 )
9890 } else {
9891 editor.update(cx, |editor, cx| {
9892 let snapshot = editor.snapshot(window, cx);
9893 let start_anchor = if start_row == Default::default() {
9894 Anchor::Min
9895 } else {
9896 snapshot.buffer_snapshot().anchor_before(
9897 DisplayPoint::new(start_row, 0)
9898 .to_offset(&snapshot, Bias::Left),
9899 )
9900 };
9901 let end_anchor = if end_row > max_row {
9902 Anchor::Max
9903 } else {
9904 snapshot.buffer_snapshot().anchor_before(
9905 DisplayPoint::new(end_row, 0)
9906 .to_offset(&snapshot, Bias::Right),
9907 )
9908 };
9909
9910 editor.background_highlights_in_range(
9911 start_anchor..end_anchor,
9912 &snapshot.display_snapshot,
9913 cx.theme(),
9914 )
9915 })
9916 }
9917 })
9918 .unwrap_or_default();
9919
9920 for (ix, row_info) in row_infos.iter().enumerate() {
9921 let Some(diff_status) = row_info.diff_status else {
9922 continue;
9923 };
9924
9925 let background_color = match diff_status.kind {
9926 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
9927 DiffHunkStatusKind::Deleted => {
9928 cx.theme().colors().version_control_deleted
9929 }
9930 DiffHunkStatusKind::Modified => {
9931 debug_panic!("modified diff status for row info");
9932 continue;
9933 }
9934 };
9935
9936 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
9937
9938 let hollow_highlight = LineHighlight {
9939 background: (background_color.opacity(if is_light {
9940 0.08
9941 } else {
9942 0.06
9943 }))
9944 .into(),
9945 border: Some(if is_light {
9946 background_color.opacity(0.48)
9947 } else {
9948 background_color.opacity(0.36)
9949 }),
9950 include_gutter: true,
9951 type_id: None,
9952 };
9953
9954 let filled_highlight = LineHighlight {
9955 background: solid_background(background_color.opacity(hunk_opacity)),
9956 border: None,
9957 include_gutter: true,
9958 type_id: None,
9959 };
9960
9961 let background = if Self::diff_hunk_hollow(diff_status, cx) {
9962 hollow_highlight
9963 } else {
9964 filled_highlight
9965 };
9966
9967 let base_display_point =
9968 DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
9969
9970 highlighted_rows
9971 .entry(base_display_point.row())
9972 .or_insert(background);
9973 }
9974
9975 // Add diff review drag selection highlight to text area
9976 if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
9977 let range = drag_state.row_range(&snapshot.display_snapshot);
9978 let start_row = range.start().0;
9979 let end_row = range.end().0;
9980 let drag_highlight_color =
9981 cx.theme().colors().editor_active_line_background;
9982 let drag_highlight = LineHighlight {
9983 background: solid_background(drag_highlight_color),
9984 border: Some(cx.theme().colors().border_focused),
9985 include_gutter: true,
9986 type_id: None,
9987 };
9988 for row_num in start_row..=end_row {
9989 highlighted_rows
9990 .entry(DisplayRow(row_num))
9991 .or_insert(drag_highlight);
9992 }
9993 }
9994
9995 let highlighted_gutter_ranges =
9996 self.editor.read(cx).gutter_highlights_in_range(
9997 start_anchor..end_anchor,
9998 &snapshot.display_snapshot,
9999 cx,
10000 );
10001
10002 let document_colors = self
10003 .editor
10004 .read(cx)
10005 .colors
10006 .as_ref()
10007 .map(|colors| colors.editor_display_highlights(&snapshot));
10008 let redacted_ranges = self.editor.read(cx).redacted_ranges(
10009 start_anchor..end_anchor,
10010 &snapshot.display_snapshot,
10011 cx,
10012 );
10013
10014 let (local_selections, selected_buffer_ids, latest_selection_anchors): (
10015 Vec<Selection<Point>>,
10016 Vec<BufferId>,
10017 HashMap<BufferId, Anchor>,
10018 ) = self
10019 .editor_with_selections(cx)
10020 .map(|editor| {
10021 editor.update(cx, |editor, cx| {
10022 let all_selections =
10023 editor.selections.all::<Point>(&snapshot.display_snapshot);
10024 let all_anchor_selections =
10025 editor.selections.all_anchors(&snapshot.display_snapshot);
10026 let selected_buffer_ids =
10027 if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
10028 Vec::new()
10029 } else {
10030 let mut selected_buffer_ids =
10031 Vec::with_capacity(all_selections.len());
10032
10033 for selection in all_selections {
10034 for buffer_id in snapshot
10035 .buffer_snapshot()
10036 .buffer_ids_for_range(selection.range())
10037 {
10038 if selected_buffer_ids.last() != Some(&buffer_id) {
10039 selected_buffer_ids.push(buffer_id);
10040 }
10041 }
10042 }
10043
10044 selected_buffer_ids
10045 };
10046
10047 let mut selections = editor.selections.disjoint_in_range(
10048 start_anchor..end_anchor,
10049 &snapshot.display_snapshot,
10050 );
10051 selections
10052 .extend(editor.selections.pending(&snapshot.display_snapshot));
10053
10054 let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
10055 HashMap::default();
10056 for selection in all_anchor_selections.iter() {
10057 let head = selection.head();
10058 if let Some((text_anchor, _)) =
10059 snapshot.buffer_snapshot().anchor_to_buffer_anchor(head)
10060 {
10061 anchors_by_buffer
10062 .entry(text_anchor.buffer_id)
10063 .and_modify(|(latest_id, latest_anchor)| {
10064 if selection.id > *latest_id {
10065 *latest_id = selection.id;
10066 *latest_anchor = head;
10067 }
10068 })
10069 .or_insert((selection.id, head));
10070 }
10071 }
10072 let latest_selection_anchors = anchors_by_buffer
10073 .into_iter()
10074 .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
10075 .collect();
10076
10077 (selections, selected_buffer_ids, latest_selection_anchors)
10078 })
10079 })
10080 .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
10081
10082 let (selections, mut active_rows, newest_selection_head) = self
10083 .layout_selections(
10084 start_anchor,
10085 end_anchor,
10086 &local_selections,
10087 &snapshot,
10088 start_row,
10089 end_row,
10090 window,
10091 cx,
10092 );
10093
10094 // relative rows are based on newest selection, even outside the visible area
10095 let current_selection_head = self.editor.update(cx, |editor, cx| {
10096 (editor.selections.count() != 0).then(|| {
10097 let newest = editor
10098 .selections
10099 .newest::<Point>(&editor.display_snapshot(cx));
10100
10101 SelectionLayout::new(
10102 newest,
10103 editor.selections.line_mode(),
10104 editor.cursor_offset_on_selection,
10105 editor.cursor_shape,
10106 &snapshot,
10107 true,
10108 true,
10109 None,
10110 )
10111 .head
10112 .row()
10113 })
10114 });
10115
10116 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
10117 editor.active_breakpoints(start_row..end_row, window, cx)
10118 });
10119 for (display_row, (_, bp, state)) in &breakpoint_rows {
10120 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
10121 active_rows.entry(*display_row).or_default().breakpoint = true;
10122 }
10123 }
10124
10125 let line_numbers = self.layout_line_numbers(
10126 Some(&gutter_hitbox),
10127 gutter_dimensions,
10128 line_height,
10129 scroll_position,
10130 start_row..end_row,
10131 &row_infos,
10132 &active_rows,
10133 current_selection_head,
10134 &snapshot,
10135 window,
10136 cx,
10137 );
10138
10139 // We add the gutter breakpoint indicator to breakpoint_rows after painting
10140 // line numbers so we don't paint a line number debug accent color if a user
10141 // has their mouse over that line when a breakpoint isn't there
10142 self.editor.update(cx, |editor, _| {
10143 if let Some(phantom_breakpoint) = &mut editor
10144 .gutter_breakpoint_indicator
10145 .0
10146 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
10147 {
10148 // Is there a non-phantom breakpoint on this line?
10149 phantom_breakpoint.collides_with_existing_breakpoint = true;
10150 breakpoint_rows
10151 .entry(phantom_breakpoint.display_row)
10152 .or_insert_with(|| {
10153 let position = snapshot.display_point_to_anchor(
10154 DisplayPoint::new(phantom_breakpoint.display_row, 0),
10155 Bias::Right,
10156 );
10157 let breakpoint = Breakpoint::new_standard();
10158 phantom_breakpoint.collides_with_existing_breakpoint = false;
10159 (position, breakpoint, None)
10160 });
10161 }
10162 });
10163
10164 let mut expand_toggles =
10165 window.with_element_namespace("expand_toggles", |window| {
10166 self.layout_expand_toggles(
10167 &gutter_hitbox,
10168 gutter_dimensions,
10169 em_width,
10170 line_height,
10171 scroll_position,
10172 &row_infos,
10173 window,
10174 cx,
10175 )
10176 });
10177
10178 let mut crease_toggles =
10179 window.with_element_namespace("crease_toggles", |window| {
10180 self.layout_crease_toggles(
10181 start_row..end_row,
10182 &row_infos,
10183 &active_rows,
10184 &snapshot,
10185 window,
10186 cx,
10187 )
10188 });
10189 let crease_trailers =
10190 window.with_element_namespace("crease_trailers", |window| {
10191 self.layout_crease_trailers(
10192 row_infos.iter().cloned(),
10193 &snapshot,
10194 window,
10195 cx,
10196 )
10197 });
10198
10199 let display_hunks = self.layout_gutter_diff_hunks(
10200 line_height,
10201 &gutter_hitbox,
10202 start_row..end_row,
10203 &snapshot,
10204 window,
10205 cx,
10206 );
10207
10208 Self::layout_word_diff_highlights(
10209 &display_hunks,
10210 &row_infos,
10211 start_row,
10212 &snapshot,
10213 &mut highlighted_ranges,
10214 cx,
10215 );
10216
10217 let merged_highlighted_ranges =
10218 if let Some((_, colors)) = document_colors.as_ref() {
10219 &highlighted_ranges
10220 .clone()
10221 .into_iter()
10222 .chain(colors.clone())
10223 .collect()
10224 } else {
10225 &highlighted_ranges
10226 };
10227 let bg_segments_per_row = Self::bg_segments_per_row(
10228 start_row..end_row,
10229 &selections,
10230 &merged_highlighted_ranges,
10231 self.style.background,
10232 );
10233
10234 let mut line_layouts = Self::layout_lines(
10235 start_row..end_row,
10236 &snapshot,
10237 &self.style,
10238 editor_width,
10239 is_row_soft_wrapped,
10240 &bg_segments_per_row,
10241 window,
10242 cx,
10243 );
10244 let new_renderer_widths = (!is_minimap).then(|| {
10245 line_layouts
10246 .iter()
10247 .flat_map(|layout| &layout.fragments)
10248 .filter_map(|fragment| {
10249 if let LineFragment::Element { id, size, .. } = fragment {
10250 Some((*id, size.width))
10251 } else {
10252 None
10253 }
10254 })
10255 });
10256 let renderer_widths_changed = request_layout.has_remaining_prepaint_depth()
10257 && new_renderer_widths.is_some_and(|new_renderer_widths| {
10258 self.editor.update(cx, |editor, cx| {
10259 editor.update_renderer_widths(new_renderer_widths, cx)
10260 })
10261 });
10262 if renderer_widths_changed {
10263 return self.prepaint(
10264 None,
10265 _inspector_id,
10266 bounds,
10267 request_layout,
10268 window,
10269 cx,
10270 );
10271 }
10272
10273 let longest_line_blame_width = self
10274 .editor
10275 .update(cx, |editor, cx| {
10276 if !editor.show_git_blame_inline {
10277 return None;
10278 }
10279 let blame = editor.blame.as_ref()?;
10280 let (_, blame_entry) = blame
10281 .update(cx, |blame, cx| {
10282 let row_infos =
10283 snapshot.row_infos(snapshot.longest_row()).next()?;
10284 blame.blame_for_rows(&[row_infos], cx).next()
10285 })
10286 .flatten()?;
10287 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
10288 let inline_blame_padding =
10289 ProjectSettings::get_global(cx).git.inline_blame.padding as f32
10290 * em_advance;
10291 Some(
10292 element
10293 .layout_as_root(AvailableSpace::min_size(), window, cx)
10294 .width
10295 + inline_blame_padding,
10296 )
10297 })
10298 .unwrap_or(Pixels::ZERO);
10299
10300 let longest_line_width = layout_line(
10301 snapshot.longest_row(),
10302 &snapshot,
10303 style,
10304 editor_width,
10305 is_row_soft_wrapped,
10306 window,
10307 cx,
10308 )
10309 .width;
10310
10311 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
10312 text_hitbox.bounds,
10313 glyph_grid_cell,
10314 size(
10315 longest_line_width,
10316 Pixels::from(max_row.as_f64() * f64::from(line_height)),
10317 ),
10318 longest_line_blame_width,
10319 EditorSettings::get_global(cx),
10320 scroll_beyond_last_line,
10321 );
10322
10323 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
10324
10325 let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
10326 snapshot.sticky_header_excerpt(scroll_position.y)
10327 } else {
10328 None
10329 };
10330 let sticky_header_excerpt_id = sticky_header_excerpt
10331 .as_ref()
10332 .map(|top| top.excerpt.buffer_id());
10333
10334 let buffer = snapshot.buffer_snapshot();
10335 let start_buffer_row = MultiBufferRow(start_anchor.to_point(&buffer).row);
10336 let end_buffer_row = MultiBufferRow(end_anchor.to_point(&buffer).row);
10337
10338 let preliminary_scroll_pixel_position = point(
10339 scroll_position.x * f64::from(em_layout_width),
10340 scroll_position.y * f64::from(line_height),
10341 );
10342 let indent_guides = self.layout_indent_guides(
10343 content_origin,
10344 text_hitbox.origin,
10345 start_buffer_row..end_buffer_row,
10346 preliminary_scroll_pixel_position,
10347 line_height,
10348 &snapshot,
10349 window,
10350 cx,
10351 );
10352 let indent_guides_for_spacers = indent_guides.clone();
10353
10354 let blocks = (!is_minimap)
10355 .then(|| {
10356 window.with_element_namespace("blocks", |window| {
10357 self.render_blocks(
10358 start_row..end_row,
10359 &snapshot,
10360 &hitbox,
10361 &text_hitbox,
10362 editor_width,
10363 &mut scroll_width,
10364 &editor_margins,
10365 em_width,
10366 gutter_dimensions.full_width(),
10367 line_height,
10368 &mut line_layouts,
10369 &local_selections,
10370 &selected_buffer_ids,
10371 &latest_selection_anchors,
10372 is_row_soft_wrapped,
10373 sticky_header_excerpt_id,
10374 &indent_guides_for_spacers,
10375 window,
10376 cx,
10377 )
10378 })
10379 })
10380 .unwrap_or_default();
10381 let RenderBlocksOutput {
10382 non_spacer_blocks: mut blocks,
10383 mut spacer_blocks,
10384 row_block_types,
10385 resized_blocks,
10386 } = blocks;
10387 if let Some(resized_blocks) = resized_blocks {
10388 if request_layout.has_remaining_prepaint_depth() {
10389 self.editor.update(cx, |editor, cx| {
10390 editor.resize_blocks(
10391 resized_blocks,
10392 autoscroll_request.map(|(autoscroll, _)| autoscroll),
10393 cx,
10394 )
10395 });
10396 return self.prepaint(
10397 None,
10398 _inspector_id,
10399 bounds,
10400 request_layout,
10401 window,
10402 cx,
10403 );
10404 } else {
10405 debug_panic!(
10406 "dropping block resize because prepaint depth \
10407 limit was reached"
10408 );
10409 }
10410 }
10411
10412 let sticky_buffer_header = if self.should_show_buffer_headers() {
10413 sticky_header_excerpt.map(|sticky_header_excerpt| {
10414 window.with_element_namespace("blocks", |window| {
10415 self.layout_sticky_buffer_header(
10416 sticky_header_excerpt,
10417 scroll_position,
10418 line_height,
10419 right_margin,
10420 &snapshot,
10421 &hitbox,
10422 &selected_buffer_ids,
10423 &blocks,
10424 &latest_selection_anchors,
10425 window,
10426 cx,
10427 )
10428 })
10429 })
10430 } else {
10431 None
10432 };
10433
10434 let scroll_max: gpui::Point<ScrollPixelOffset> = point(
10435 ScrollPixelOffset::from(
10436 ((scroll_width - editor_width) / em_layout_width).max(0.0),
10437 ),
10438 max_scroll_top,
10439 );
10440
10441 self.editor.update(cx, |editor, cx| {
10442 if editor.scroll_manager.clamp_scroll_left(scroll_max.x, cx) {
10443 scroll_position.x = scroll_max.x.min(scroll_position.x);
10444 }
10445
10446 if needs_horizontal_autoscroll.0
10447 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
10448 start_row,
10449 editor_width,
10450 scroll_width,
10451 em_advance,
10452 &line_layouts,
10453 autoscroll_request,
10454 window,
10455 cx,
10456 )
10457 {
10458 scroll_position = new_scroll_position;
10459 }
10460 });
10461
10462 let scroll_pixel_position = point(
10463 scroll_position.x * f64::from(em_layout_width),
10464 scroll_position.y * f64::from(line_height),
10465 );
10466 let sticky_headers = if !is_minimap
10467 && is_singleton
10468 && EditorSettings::get_global(cx).sticky_scroll.enabled
10469 {
10470 let relative = self.editor.read(cx).relative_line_numbers(cx);
10471 self.layout_sticky_headers(
10472 &snapshot,
10473 editor_width,
10474 is_row_soft_wrapped,
10475 line_height,
10476 scroll_pixel_position,
10477 content_origin,
10478 &gutter_dimensions,
10479 &gutter_hitbox,
10480 &text_hitbox,
10481 relative,
10482 current_selection_head,
10483 window,
10484 cx,
10485 )
10486 } else {
10487 None
10488 };
10489 self.editor.update(cx, |editor, _| {
10490 editor.scroll_manager.set_sticky_header_line_count(
10491 sticky_headers.as_ref().map_or(0, |h| h.lines.len()),
10492 );
10493 });
10494 let indent_guides =
10495 if scroll_pixel_position != preliminary_scroll_pixel_position {
10496 self.layout_indent_guides(
10497 content_origin,
10498 text_hitbox.origin,
10499 start_buffer_row..end_buffer_row,
10500 scroll_pixel_position,
10501 line_height,
10502 &snapshot,
10503 window,
10504 cx,
10505 )
10506 } else {
10507 indent_guides
10508 };
10509
10510 let crease_trailers =
10511 window.with_element_namespace("crease_trailers", |window| {
10512 self.prepaint_crease_trailers(
10513 crease_trailers,
10514 &line_layouts,
10515 line_height,
10516 content_origin,
10517 scroll_pixel_position,
10518 em_width,
10519 window,
10520 cx,
10521 )
10522 });
10523
10524 let (edit_prediction_popover, edit_prediction_popover_origin) = self
10525 .editor
10526 .update(cx, |editor, cx| {
10527 editor.render_edit_prediction_popover(
10528 &text_hitbox.bounds,
10529 content_origin,
10530 right_margin,
10531 &snapshot,
10532 start_row..end_row,
10533 scroll_position.y,
10534 scroll_position.y + height_in_lines,
10535 &line_layouts,
10536 line_height,
10537 scroll_position,
10538 scroll_pixel_position,
10539 newest_selection_head,
10540 editor_width,
10541 style,
10542 window,
10543 cx,
10544 )
10545 })
10546 .unzip();
10547
10548 let mut inline_diagnostics = self.layout_inline_diagnostics(
10549 &line_layouts,
10550 &crease_trailers,
10551 &row_block_types,
10552 content_origin,
10553 scroll_position,
10554 scroll_pixel_position,
10555 edit_prediction_popover_origin,
10556 start_row,
10557 end_row,
10558 line_height,
10559 em_width,
10560 style,
10561 window,
10562 cx,
10563 );
10564
10565 let mut inline_blame_layout = None;
10566 let mut inline_code_actions = None;
10567 if let Some(newest_selection_head) = newest_selection_head {
10568 let display_row = newest_selection_head.row();
10569 if (start_row..end_row).contains(&display_row)
10570 && !row_block_types.contains_key(&display_row)
10571 {
10572 inline_code_actions = self.layout_inline_code_actions(
10573 newest_selection_head,
10574 content_origin,
10575 scroll_position,
10576 scroll_pixel_position,
10577 line_height,
10578 &snapshot,
10579 window,
10580 cx,
10581 );
10582
10583 let line_ix = display_row.minus(start_row) as usize;
10584 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10585 row_infos.get(line_ix),
10586 line_layouts.get(line_ix),
10587 crease_trailers.get(line_ix),
10588 ) {
10589 let crease_trailer_layout = crease_trailer.as_ref();
10590 if let Some(layout) = self.layout_inline_blame(
10591 display_row,
10592 row_info,
10593 line_layout,
10594 crease_trailer_layout,
10595 em_width,
10596 content_origin,
10597 scroll_position,
10598 scroll_pixel_position,
10599 line_height,
10600 window,
10601 cx,
10602 ) {
10603 inline_blame_layout = Some(layout);
10604 // Blame overrides inline diagnostics
10605 inline_diagnostics.remove(&display_row);
10606 }
10607 } else {
10608 log::error!(
10609 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10610 line_layouts.len(): {}, \
10611 crease_trailers.len(): {}",
10612 line_ix,
10613 row_infos.len(),
10614 line_layouts.len(),
10615 crease_trailers.len(),
10616 );
10617 }
10618 }
10619 }
10620
10621 let blamed_display_rows = self.layout_blame_entries(
10622 &row_infos,
10623 em_width,
10624 scroll_position,
10625 line_height,
10626 &gutter_hitbox,
10627 gutter_dimensions.git_blame_entries_width,
10628 window,
10629 cx,
10630 );
10631
10632 let line_elements = self.prepaint_lines(
10633 start_row,
10634 &mut line_layouts,
10635 line_height,
10636 scroll_position,
10637 scroll_pixel_position,
10638 content_origin,
10639 window,
10640 cx,
10641 );
10642
10643 window.with_element_namespace("blocks", |window| {
10644 self.layout_blocks(
10645 &mut blocks,
10646 &hitbox,
10647 &gutter_hitbox,
10648 line_height,
10649 scroll_position,
10650 scroll_pixel_position,
10651 &editor_margins,
10652 window,
10653 cx,
10654 );
10655 self.layout_blocks(
10656 &mut spacer_blocks,
10657 &hitbox,
10658 &gutter_hitbox,
10659 line_height,
10660 scroll_position,
10661 scroll_pixel_position,
10662 &editor_margins,
10663 window,
10664 cx,
10665 );
10666 });
10667
10668 let cursors = self.collect_cursors(&snapshot, cx);
10669 let visible_row_range = start_row..end_row;
10670 let non_visible_cursors = cursors
10671 .iter()
10672 .any(|c| !visible_row_range.contains(&c.0.row()));
10673
10674 let visible_cursors = self.layout_visible_cursors(
10675 &snapshot,
10676 &selections,
10677 &row_block_types,
10678 start_row..end_row,
10679 &line_layouts,
10680 &text_hitbox,
10681 content_origin,
10682 scroll_position,
10683 scroll_pixel_position,
10684 line_height,
10685 em_width,
10686 em_advance,
10687 autoscroll_containing_element,
10688 &redacted_ranges,
10689 window,
10690 cx,
10691 );
10692
10693 let scrollbars_layout = self.layout_scrollbars(
10694 &snapshot,
10695 &scrollbar_layout_information,
10696 content_offset,
10697 scroll_position,
10698 non_visible_cursors,
10699 right_margin,
10700 editor_width,
10701 window,
10702 cx,
10703 );
10704
10705 let gutter_settings = EditorSettings::get_global(cx).gutter;
10706
10707 let context_menu_layout =
10708 if let Some(newest_selection_head) = newest_selection_head {
10709 let newest_selection_point =
10710 newest_selection_head.to_point(&snapshot.display_snapshot);
10711 if (start_row..end_row).contains(&newest_selection_head.row()) {
10712 self.layout_cursor_popovers(
10713 line_height,
10714 &text_hitbox,
10715 content_origin,
10716 right_margin,
10717 start_row,
10718 scroll_pixel_position,
10719 &line_layouts,
10720 newest_selection_head,
10721 newest_selection_point,
10722 style,
10723 window,
10724 cx,
10725 )
10726 } else {
10727 None
10728 }
10729 } else {
10730 None
10731 };
10732
10733 self.layout_gutter_menu(
10734 line_height,
10735 &text_hitbox,
10736 content_origin,
10737 right_margin,
10738 scroll_pixel_position,
10739 gutter_dimensions.width - gutter_dimensions.left_padding,
10740 window,
10741 cx,
10742 );
10743
10744 let test_indicators = if gutter_settings.runnables {
10745 self.layout_run_indicators(
10746 line_height,
10747 start_row..end_row,
10748 &row_infos,
10749 scroll_position,
10750 &gutter_dimensions,
10751 &gutter_hitbox,
10752 &snapshot,
10753 &mut breakpoint_rows,
10754 window,
10755 cx,
10756 )
10757 } else {
10758 Vec::new()
10759 };
10760
10761 let show_breakpoints = snapshot
10762 .show_breakpoints
10763 .unwrap_or(gutter_settings.breakpoints);
10764 let breakpoints = if show_breakpoints {
10765 self.layout_breakpoints(
10766 line_height,
10767 start_row..end_row,
10768 scroll_position,
10769 &gutter_dimensions,
10770 &gutter_hitbox,
10771 &snapshot,
10772 breakpoint_rows,
10773 &row_infos,
10774 window,
10775 cx,
10776 )
10777 } else {
10778 Vec::new()
10779 };
10780
10781 let git_gutter_width = Self::gutter_strip_width(line_height)
10782 + gutter_dimensions
10783 .git_blame_entries_width
10784 .unwrap_or_default();
10785 let available_width = gutter_dimensions.left_padding - git_gutter_width;
10786
10787 let max_line_number_length = self
10788 .editor
10789 .read(cx)
10790 .buffer()
10791 .read(cx)
10792 .snapshot(cx)
10793 .widest_line_number()
10794 .ilog10()
10795 + 1;
10796
10797 let diff_review_button = self
10798 .should_render_diff_review_button(
10799 start_row..end_row,
10800 &row_infos,
10801 &snapshot,
10802 cx,
10803 )
10804 .map(|(display_row, buffer_row)| {
10805 let is_wide = max_line_number_length
10806 >= EditorSettings::get_global(cx).gutter.min_line_number_digits
10807 as u32
10808 && buffer_row.is_some_and(|row| {
10809 (row + 1).ilog10() + 1 == max_line_number_length
10810 })
10811 || gutter_dimensions.right_padding == px(0.);
10812
10813 let button_width = if is_wide {
10814 available_width - px(6.)
10815 } else {
10816 available_width + em_width - px(6.)
10817 };
10818
10819 let button = self.editor.update(cx, |editor, cx| {
10820 editor
10821 .render_diff_review_button(display_row, button_width, cx)
10822 .into_any_element()
10823 });
10824 prepaint_gutter_button(
10825 button,
10826 display_row,
10827 line_height,
10828 &gutter_dimensions,
10829 scroll_position,
10830 &gutter_hitbox,
10831 window,
10832 cx,
10833 )
10834 });
10835
10836 self.layout_signature_help(
10837 &hitbox,
10838 content_origin,
10839 scroll_pixel_position,
10840 newest_selection_head,
10841 start_row,
10842 &line_layouts,
10843 line_height,
10844 em_width,
10845 context_menu_layout,
10846 window,
10847 cx,
10848 );
10849
10850 if !cx.has_active_drag() {
10851 self.layout_hover_popovers(
10852 &snapshot,
10853 &hitbox,
10854 start_row..end_row,
10855 content_origin,
10856 scroll_pixel_position,
10857 &line_layouts,
10858 line_height,
10859 em_width,
10860 context_menu_layout,
10861 window,
10862 cx,
10863 );
10864
10865 self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10866 }
10867
10868 let mouse_context_menu = self.layout_mouse_context_menu(
10869 &snapshot,
10870 start_row..end_row,
10871 content_origin,
10872 window,
10873 cx,
10874 );
10875
10876 window.with_element_namespace("crease_toggles", |window| {
10877 self.prepaint_crease_toggles(
10878 &mut crease_toggles,
10879 line_height,
10880 &gutter_dimensions,
10881 gutter_settings,
10882 scroll_pixel_position,
10883 &gutter_hitbox,
10884 window,
10885 cx,
10886 )
10887 });
10888
10889 window.with_element_namespace("expand_toggles", |window| {
10890 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10891 });
10892
10893 let wrap_guides = self.layout_wrap_guides(
10894 em_advance,
10895 scroll_position,
10896 content_origin,
10897 scrollbars_layout.as_ref(),
10898 vertical_scrollbar_width,
10899 &hitbox,
10900 window,
10901 cx,
10902 );
10903
10904 let minimap = window.with_element_namespace("minimap", |window| {
10905 self.layout_minimap(
10906 &snapshot,
10907 minimap_width,
10908 scroll_position,
10909 &scrollbar_layout_information,
10910 scrollbars_layout.as_ref(),
10911 window,
10912 cx,
10913 )
10914 });
10915
10916 let invisible_symbol_font_size = font_size / 2.;
10917 let whitespace_map = &self
10918 .editor
10919 .read(cx)
10920 .buffer
10921 .read(cx)
10922 .language_settings(cx)
10923 .whitespace_map;
10924
10925 let tab_char = whitespace_map.tab.clone();
10926 let tab_len = tab_char.len();
10927 let tab_invisible = window.text_system().shape_line(
10928 tab_char,
10929 invisible_symbol_font_size,
10930 &[TextRun {
10931 len: tab_len,
10932 font: self.style.text.font(),
10933 color: cx.theme().colors().editor_invisible,
10934 ..Default::default()
10935 }],
10936 None,
10937 );
10938
10939 let space_char = whitespace_map.space.clone();
10940 let space_len = space_char.len();
10941 let space_invisible = window.text_system().shape_line(
10942 space_char,
10943 invisible_symbol_font_size,
10944 &[TextRun {
10945 len: space_len,
10946 font: self.style.text.font(),
10947 color: cx.theme().colors().editor_invisible,
10948 ..Default::default()
10949 }],
10950 None,
10951 );
10952
10953 let mode = snapshot.mode.clone();
10954
10955 let sticky_scroll_header_height = sticky_headers
10956 .as_ref()
10957 .and_then(|headers| headers.lines.last())
10958 .map_or(Pixels::ZERO, |last| last.offset + line_height);
10959
10960 let has_sticky_buffer_header =
10961 sticky_buffer_header.is_some() || sticky_header_excerpt_id.is_some();
10962 let sticky_header_height = if has_sticky_buffer_header {
10963 let full_height = FILE_HEADER_HEIGHT as f32 * line_height;
10964 let display_row = blocks
10965 .iter()
10966 .filter(|block| block.is_buffer_header)
10967 .find_map(|block| {
10968 block.row.filter(|row| row.0 > scroll_position.y as u32)
10969 });
10970 let offset = match display_row {
10971 Some(display_row) => {
10972 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
10973 let offset = (scroll_position.y - max_row as f64).max(0.0);
10974 let slide_up =
10975 Pixels::from(offset * ScrollPixelOffset::from(line_height));
10976
10977 (full_height - slide_up).max(Pixels::ZERO)
10978 }
10979 None => full_height,
10980 };
10981 let header_bottom_padding =
10982 BUFFER_HEADER_PADDING.to_pixels(window.rem_size());
10983 sticky_scroll_header_height + offset - header_bottom_padding
10984 } else {
10985 sticky_scroll_header_height
10986 };
10987
10988 let (diff_hunk_controls, diff_hunk_control_bounds) =
10989 if is_read_only && !self.editor.read(cx).delegate_stage_and_restore {
10990 (vec![], vec![])
10991 } else {
10992 self.layout_diff_hunk_controls(
10993 start_row..end_row,
10994 &row_infos,
10995 &text_hitbox,
10996 current_selection_head,
10997 line_height,
10998 right_margin,
10999 scroll_pixel_position,
11000 sticky_header_height,
11001 &display_hunks,
11002 &highlighted_rows,
11003 self.editor.clone(),
11004 window,
11005 cx,
11006 )
11007 };
11008
11009 let position_map = Rc::new(PositionMap {
11010 size: bounds.size,
11011 visible_row_range,
11012 scroll_position,
11013 scroll_pixel_position,
11014 scroll_max,
11015 line_layouts,
11016 line_height,
11017 em_width,
11018 em_advance,
11019 em_layout_width,
11020 snapshot,
11021 text_align: self.style.text.text_align,
11022 content_width: text_hitbox.size.width,
11023 gutter_hitbox: gutter_hitbox.clone(),
11024 text_hitbox: text_hitbox.clone(),
11025 inline_blame_bounds: inline_blame_layout
11026 .as_ref()
11027 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
11028 display_hunks: display_hunks.clone(),
11029 diff_hunk_control_bounds,
11030 });
11031
11032 self.editor.update(cx, |editor, _| {
11033 editor.last_position_map = Some(position_map.clone())
11034 });
11035
11036 EditorLayout {
11037 mode,
11038 position_map,
11039 visible_display_row_range: start_row..end_row,
11040 wrap_guides,
11041 indent_guides,
11042 hitbox,
11043 gutter_hitbox,
11044 display_hunks,
11045 content_origin,
11046 scrollbars_layout,
11047 minimap,
11048 active_rows,
11049 highlighted_rows,
11050 highlighted_ranges,
11051 highlighted_gutter_ranges,
11052 redacted_ranges,
11053 document_colors,
11054 line_elements,
11055 line_numbers,
11056 blamed_display_rows,
11057 inline_diagnostics,
11058 inline_blame_layout,
11059 inline_code_actions,
11060 blocks,
11061 spacer_blocks,
11062 cursors,
11063 visible_cursors,
11064 selections,
11065 edit_prediction_popover,
11066 diff_hunk_controls,
11067 mouse_context_menu,
11068 test_indicators,
11069 breakpoints,
11070 diff_review_button,
11071 crease_toggles,
11072 crease_trailers,
11073 tab_invisible,
11074 space_invisible,
11075 sticky_buffer_header,
11076 sticky_headers,
11077 expand_toggles,
11078 text_align: self.style.text.text_align,
11079 content_width: text_hitbox.size.width,
11080 }
11081 })
11082 })
11083 })
11084 }
11085
11086 fn paint(
11087 &mut self,
11088 _: Option<&GlobalElementId>,
11089 _inspector_id: Option<&gpui::InspectorElementId>,
11090 bounds: Bounds<gpui::Pixels>,
11091 _: &mut Self::RequestLayoutState,
11092 layout: &mut Self::PrepaintState,
11093 window: &mut Window,
11094 cx: &mut App,
11095 ) {
11096 if !layout.mode.is_minimap() {
11097 let focus_handle = self.editor.focus_handle(cx);
11098 let key_context = self
11099 .editor
11100 .update(cx, |editor, cx| editor.key_context(window, cx));
11101
11102 window.set_key_context(key_context);
11103 window.handle_input(
11104 &focus_handle,
11105 ElementInputHandler::new(bounds, self.editor.clone()),
11106 cx,
11107 );
11108 self.register_actions(window, cx);
11109 self.register_key_listeners(window, cx, layout);
11110 }
11111
11112 let text_style = TextStyleRefinement {
11113 font_size: Some(self.style.text.font_size),
11114 line_height: Some(self.style.text.line_height),
11115 ..Default::default()
11116 };
11117 let rem_size = self.rem_size(cx);
11118 window.with_rem_size(rem_size, |window| {
11119 window.with_text_style(Some(text_style), |window| {
11120 window.with_content_mask(Some(ContentMask { bounds }), |window| {
11121 self.paint_mouse_listeners(layout, window, cx);
11122 self.paint_background(layout, window, cx);
11123
11124 self.paint_indent_guides(layout, window, cx);
11125
11126 if layout.gutter_hitbox.size.width > Pixels::ZERO {
11127 self.paint_blamed_display_rows(layout, window, cx);
11128 self.paint_line_numbers(layout, window, cx);
11129 }
11130
11131 self.paint_text(layout, window, cx);
11132
11133 if !layout.spacer_blocks.is_empty() {
11134 window.with_element_namespace("blocks", |window| {
11135 self.paint_spacer_blocks(layout, window, cx);
11136 });
11137 }
11138
11139 if layout.gutter_hitbox.size.width > Pixels::ZERO {
11140 self.paint_gutter_highlights(layout, window, cx);
11141 self.paint_gutter_indicators(layout, window, cx);
11142 }
11143
11144 if !layout.blocks.is_empty() {
11145 window.with_element_namespace("blocks", |window| {
11146 self.paint_non_spacer_blocks(layout, window, cx);
11147 });
11148 }
11149
11150 window.with_element_namespace("blocks", |window| {
11151 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
11152 sticky_header.paint(window, cx)
11153 }
11154 });
11155
11156 self.paint_sticky_headers(layout, window, cx);
11157 self.paint_minimap(layout, window, cx);
11158 self.paint_scrollbars(layout, window, cx);
11159 self.paint_edit_prediction_popover(layout, window, cx);
11160 self.paint_mouse_context_menu(layout, window, cx);
11161 });
11162 })
11163 })
11164 }
11165}
11166
11167pub(super) fn gutter_bounds(
11168 editor_bounds: Bounds<Pixels>,
11169 gutter_dimensions: GutterDimensions,
11170) -> Bounds<Pixels> {
11171 Bounds {
11172 origin: editor_bounds.origin,
11173 size: size(gutter_dimensions.width, editor_bounds.size.height),
11174 }
11175}
11176
11177#[derive(Clone, Copy)]
11178struct ContextMenuLayout {
11179 y_flipped: bool,
11180 bounds: Bounds<Pixels>,
11181}
11182
11183/// Holds information required for layouting the editor scrollbars.
11184struct ScrollbarLayoutInformation {
11185 /// The bounds of the editor area (excluding the content offset).
11186 editor_bounds: Bounds<Pixels>,
11187 /// The available range to scroll within the document.
11188 scroll_range: Size<Pixels>,
11189 /// The space available for one glyph in the editor.
11190 glyph_grid_cell: Size<Pixels>,
11191}
11192
11193impl ScrollbarLayoutInformation {
11194 pub fn new(
11195 editor_bounds: Bounds<Pixels>,
11196 glyph_grid_cell: Size<Pixels>,
11197 document_size: Size<Pixels>,
11198 longest_line_blame_width: Pixels,
11199 settings: &EditorSettings,
11200 scroll_beyond_last_line: ScrollBeyondLastLine,
11201 ) -> Self {
11202 let vertical_overscroll = match scroll_beyond_last_line {
11203 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
11204 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
11205 ScrollBeyondLastLine::VerticalScrollMargin => {
11206 (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
11207 }
11208 };
11209
11210 let overscroll = size(longest_line_blame_width, vertical_overscroll);
11211
11212 ScrollbarLayoutInformation {
11213 editor_bounds,
11214 scroll_range: document_size + overscroll,
11215 glyph_grid_cell,
11216 }
11217 }
11218}
11219
11220impl IntoElement for EditorElement {
11221 type Element = Self;
11222
11223 fn into_element(self) -> Self::Element {
11224 self
11225 }
11226}
11227
11228pub struct EditorLayout {
11229 position_map: Rc<PositionMap>,
11230 hitbox: Hitbox,
11231 gutter_hitbox: Hitbox,
11232 content_origin: gpui::Point<Pixels>,
11233 scrollbars_layout: Option<EditorScrollbars>,
11234 minimap: Option<MinimapLayout>,
11235 mode: EditorMode,
11236 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
11237 indent_guides: Option<Vec<IndentGuideLayout>>,
11238 visible_display_row_range: Range<DisplayRow>,
11239 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
11240 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
11241 line_elements: SmallVec<[AnyElement; 1]>,
11242 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
11243 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11244 blamed_display_rows: Option<Vec<AnyElement>>,
11245 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
11246 inline_blame_layout: Option<InlineBlameLayout>,
11247 inline_code_actions: Option<AnyElement>,
11248 blocks: Vec<BlockLayout>,
11249 spacer_blocks: Vec<BlockLayout>,
11250 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11251 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11252 redacted_ranges: Vec<Range<DisplayPoint>>,
11253 cursors: Vec<(DisplayPoint, Hsla)>,
11254 visible_cursors: Vec<CursorLayout>,
11255 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
11256 test_indicators: Vec<AnyElement>,
11257 breakpoints: Vec<AnyElement>,
11258 diff_review_button: Option<AnyElement>,
11259 crease_toggles: Vec<Option<AnyElement>>,
11260 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
11261 diff_hunk_controls: Vec<AnyElement>,
11262 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
11263 edit_prediction_popover: Option<AnyElement>,
11264 mouse_context_menu: Option<AnyElement>,
11265 tab_invisible: ShapedLine,
11266 space_invisible: ShapedLine,
11267 sticky_buffer_header: Option<AnyElement>,
11268 sticky_headers: Option<StickyHeaders>,
11269 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
11270 text_align: TextAlign,
11271 content_width: Pixels,
11272}
11273
11274struct StickyHeaders {
11275 lines: Vec<StickyHeaderLine>,
11276 gutter_background: Hsla,
11277 content_background: Hsla,
11278 gutter_right_padding: Pixels,
11279}
11280
11281struct StickyHeaderLine {
11282 row: DisplayRow,
11283 offset: Pixels,
11284 line: Rc<LineWithInvisibles>,
11285 line_number: Option<ShapedLine>,
11286 elements: SmallVec<[AnyElement; 1]>,
11287 available_text_width: Pixels,
11288 hitbox: Hitbox,
11289}
11290
11291impl EditorLayout {
11292 fn line_end_overshoot(&self) -> Pixels {
11293 0.15 * self.position_map.line_height
11294 }
11295}
11296
11297impl StickyHeaders {
11298 fn paint(
11299 &mut self,
11300 layout: &mut EditorLayout,
11301 whitespace_setting: ShowWhitespaceSetting,
11302 window: &mut Window,
11303 cx: &mut App,
11304 ) {
11305 let line_height = layout.position_map.line_height;
11306
11307 for line in self.lines.iter_mut().rev() {
11308 window.paint_layer(
11309 Bounds::new(
11310 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11311 size(line.hitbox.size.width, line_height),
11312 ),
11313 |window| {
11314 let gutter_bounds = Bounds::new(
11315 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11316 size(layout.gutter_hitbox.size.width, line_height),
11317 );
11318 window.paint_quad(fill(gutter_bounds, self.gutter_background));
11319
11320 let text_bounds = Bounds::new(
11321 layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11322 size(line.available_text_width, line_height),
11323 );
11324 window.paint_quad(fill(text_bounds, self.content_background));
11325
11326 if line.hitbox.is_hovered(window) {
11327 let hover_overlay = cx.theme().colors().panel_overlay_hover;
11328 window.paint_quad(fill(gutter_bounds, hover_overlay));
11329 window.paint_quad(fill(text_bounds, hover_overlay));
11330 }
11331
11332 line.paint(
11333 layout,
11334 self.gutter_right_padding,
11335 line.available_text_width,
11336 layout.content_origin,
11337 line_height,
11338 whitespace_setting,
11339 window,
11340 cx,
11341 );
11342 },
11343 );
11344
11345 window.set_cursor_style(CursorStyle::IBeam, &line.hitbox);
11346 }
11347 }
11348}
11349
11350impl StickyHeaderLine {
11351 fn new(
11352 row: DisplayRow,
11353 offset: Pixels,
11354 mut line: LineWithInvisibles,
11355 line_number: Option<ShapedLine>,
11356 line_height: Pixels,
11357 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11358 content_origin: gpui::Point<Pixels>,
11359 gutter_hitbox: &Hitbox,
11360 text_hitbox: &Hitbox,
11361 window: &mut Window,
11362 cx: &mut App,
11363 ) -> Self {
11364 let mut elements = SmallVec::<[AnyElement; 1]>::new();
11365 line.prepaint_with_custom_offset(
11366 line_height,
11367 scroll_pixel_position,
11368 content_origin,
11369 offset,
11370 &mut elements,
11371 window,
11372 cx,
11373 );
11374
11375 let hitbox_bounds = Bounds::new(
11376 gutter_hitbox.origin + point(Pixels::ZERO, offset),
11377 size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11378 );
11379 let available_text_width =
11380 (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11381
11382 Self {
11383 row,
11384 offset,
11385 line: Rc::new(line),
11386 line_number,
11387 elements,
11388 available_text_width,
11389 hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11390 }
11391 }
11392
11393 fn paint(
11394 &mut self,
11395 layout: &EditorLayout,
11396 gutter_right_padding: Pixels,
11397 available_text_width: Pixels,
11398 content_origin: gpui::Point<Pixels>,
11399 line_height: Pixels,
11400 whitespace_setting: ShowWhitespaceSetting,
11401 window: &mut Window,
11402 cx: &mut App,
11403 ) {
11404 window.with_content_mask(
11405 Some(ContentMask {
11406 bounds: Bounds::new(
11407 layout.position_map.text_hitbox.bounds.origin
11408 + point(Pixels::ZERO, self.offset),
11409 size(available_text_width, line_height),
11410 ),
11411 }),
11412 |window| {
11413 self.line.draw_with_custom_offset(
11414 layout,
11415 self.row,
11416 content_origin,
11417 self.offset,
11418 whitespace_setting,
11419 &[],
11420 window,
11421 cx,
11422 );
11423 for element in &mut self.elements {
11424 element.paint(window, cx);
11425 }
11426 },
11427 );
11428
11429 if let Some(line_number) = &self.line_number {
11430 let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11431 let gutter_width = layout.gutter_hitbox.size.width;
11432 let origin = point(
11433 gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11434 gutter_origin.y,
11435 );
11436 line_number
11437 .paint(origin, line_height, TextAlign::Left, None, window, cx)
11438 .log_err();
11439 }
11440 }
11441}
11442
11443#[derive(Debug)]
11444struct LineNumberSegment {
11445 shaped_line: ShapedLine,
11446 hitbox: Option<Hitbox>,
11447}
11448
11449#[derive(Debug)]
11450struct LineNumberLayout {
11451 segments: SmallVec<[LineNumberSegment; 1]>,
11452}
11453
11454struct ColoredRange<T> {
11455 start: T,
11456 end: T,
11457 color: Hsla,
11458}
11459
11460impl Along for ScrollbarAxes {
11461 type Unit = bool;
11462
11463 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11464 match axis {
11465 ScrollbarAxis::Horizontal => self.horizontal,
11466 ScrollbarAxis::Vertical => self.vertical,
11467 }
11468 }
11469
11470 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11471 match axis {
11472 ScrollbarAxis::Horizontal => ScrollbarAxes {
11473 horizontal: f(self.horizontal),
11474 vertical: self.vertical,
11475 },
11476 ScrollbarAxis::Vertical => ScrollbarAxes {
11477 horizontal: self.horizontal,
11478 vertical: f(self.vertical),
11479 },
11480 }
11481 }
11482}
11483
11484#[derive(Clone)]
11485struct EditorScrollbars {
11486 pub vertical: Option<ScrollbarLayout>,
11487 pub horizontal: Option<ScrollbarLayout>,
11488 pub visible: bool,
11489}
11490
11491impl EditorScrollbars {
11492 pub fn from_scrollbar_axes(
11493 show_scrollbar: ScrollbarAxes,
11494 layout_information: &ScrollbarLayoutInformation,
11495 content_offset: gpui::Point<Pixels>,
11496 scroll_position: gpui::Point<f64>,
11497 scrollbar_width: Pixels,
11498 right_margin: Pixels,
11499 editor_width: Pixels,
11500 show_scrollbars: bool,
11501 scrollbar_state: Option<&ActiveScrollbarState>,
11502 window: &mut Window,
11503 ) -> Self {
11504 let ScrollbarLayoutInformation {
11505 editor_bounds,
11506 scroll_range,
11507 glyph_grid_cell,
11508 } = layout_information;
11509
11510 let viewport_size = size(editor_width, editor_bounds.size.height);
11511
11512 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11513 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
11514 Corner::BottomLeft,
11515 editor_bounds.bottom_left(),
11516 size(
11517 // The horizontal viewport size differs from the space available for the
11518 // horizontal scrollbar, so we have to manually stitch it together here.
11519 editor_bounds.size.width - right_margin,
11520 scrollbar_width,
11521 ),
11522 ),
11523 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
11524 Corner::TopRight,
11525 editor_bounds.top_right(),
11526 size(scrollbar_width, viewport_size.height),
11527 ),
11528 };
11529
11530 let mut create_scrollbar_layout = |axis| {
11531 let viewport_size = viewport_size.along(axis);
11532 let scroll_range = scroll_range.along(axis);
11533
11534 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11535 (show_scrollbar.along(axis)
11536 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11537 .then(|| {
11538 ScrollbarLayout::new(
11539 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11540 viewport_size,
11541 scroll_range,
11542 glyph_grid_cell.along(axis),
11543 content_offset.along(axis),
11544 scroll_position.along(axis),
11545 show_scrollbars,
11546 axis,
11547 )
11548 .with_thumb_state(
11549 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11550 )
11551 })
11552 };
11553
11554 Self {
11555 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11556 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11557 visible: show_scrollbars,
11558 }
11559 }
11560
11561 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11562 [
11563 (&self.vertical, ScrollbarAxis::Vertical),
11564 (&self.horizontal, ScrollbarAxis::Horizontal),
11565 ]
11566 .into_iter()
11567 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11568 }
11569
11570 /// Returns the currently hovered scrollbar axis, if any.
11571 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11572 self.iter_scrollbars()
11573 .find(|s| s.0.hitbox.is_hovered(window))
11574 }
11575}
11576
11577#[derive(Clone)]
11578struct ScrollbarLayout {
11579 hitbox: Hitbox,
11580 visible_range: Range<ScrollOffset>,
11581 text_unit_size: Pixels,
11582 thumb_bounds: Option<Bounds<Pixels>>,
11583 thumb_state: ScrollbarThumbState,
11584}
11585
11586impl ScrollbarLayout {
11587 const BORDER_WIDTH: Pixels = px(1.0);
11588 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11589 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11590 const MIN_THUMB_SIZE: Pixels = px(25.0);
11591
11592 fn new(
11593 scrollbar_track_hitbox: Hitbox,
11594 viewport_size: Pixels,
11595 scroll_range: Pixels,
11596 glyph_space: Pixels,
11597 content_offset: Pixels,
11598 scroll_position: ScrollOffset,
11599 show_thumb: bool,
11600 axis: ScrollbarAxis,
11601 ) -> Self {
11602 let track_bounds = scrollbar_track_hitbox.bounds;
11603 // The length of the track available to the scrollbar thumb. We deliberately
11604 // exclude the content size here so that the thumb aligns with the content.
11605 let track_length = track_bounds.size.along(axis) - content_offset;
11606
11607 Self::new_with_hitbox_and_track_length(
11608 scrollbar_track_hitbox,
11609 track_length,
11610 viewport_size,
11611 scroll_range.into(),
11612 glyph_space,
11613 content_offset.into(),
11614 scroll_position,
11615 show_thumb,
11616 axis,
11617 )
11618 }
11619
11620 fn for_minimap(
11621 minimap_track_hitbox: Hitbox,
11622 visible_lines: f64,
11623 total_editor_lines: f64,
11624 minimap_line_height: Pixels,
11625 scroll_position: ScrollOffset,
11626 minimap_scroll_top: ScrollOffset,
11627 show_thumb: bool,
11628 ) -> Self {
11629 // The scrollbar thumb size is calculated as
11630 // (visible_content/total_content) Γ scrollbar_track_length.
11631 //
11632 // For the minimap's thumb layout, we leverage this by setting the
11633 // scrollbar track length to the entire document size (using minimap line
11634 // height). This creates a thumb that exactly represents the editor
11635 // viewport scaled to minimap proportions.
11636 //
11637 // We adjust the thumb position relative to `minimap_scroll_top` to
11638 // accommodate for the deliberately oversized track.
11639 //
11640 // This approach ensures that the minimap thumb accurately reflects the
11641 // editor's current scroll position whilst nicely synchronizing the minimap
11642 // thumb and scrollbar thumb.
11643 let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11644 let viewport_size = visible_lines * f64::from(minimap_line_height);
11645
11646 let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11647
11648 Self::new_with_hitbox_and_track_length(
11649 minimap_track_hitbox,
11650 Pixels::from(scroll_range),
11651 Pixels::from(viewport_size),
11652 scroll_range,
11653 minimap_line_height,
11654 track_top_offset,
11655 scroll_position,
11656 show_thumb,
11657 ScrollbarAxis::Vertical,
11658 )
11659 }
11660
11661 fn new_with_hitbox_and_track_length(
11662 scrollbar_track_hitbox: Hitbox,
11663 track_length: Pixels,
11664 viewport_size: Pixels,
11665 scroll_range: f64,
11666 glyph_space: Pixels,
11667 content_offset: ScrollOffset,
11668 scroll_position: ScrollOffset,
11669 show_thumb: bool,
11670 axis: ScrollbarAxis,
11671 ) -> Self {
11672 let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11673 let visible_range = scroll_position..scroll_position + text_units_per_page;
11674 let total_text_units = scroll_range / glyph_space.to_f64();
11675
11676 let thumb_percentage = text_units_per_page / total_text_units;
11677 let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11678 .max(ScrollbarLayout::MIN_THUMB_SIZE)
11679 .min(track_length);
11680
11681 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11682
11683 let content_larger_than_viewport = text_unit_divisor > 0.;
11684
11685 let text_unit_size = if content_larger_than_viewport {
11686 Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11687 } else {
11688 glyph_space
11689 };
11690
11691 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11692 Self::thumb_bounds(
11693 &scrollbar_track_hitbox,
11694 content_offset,
11695 visible_range.start,
11696 text_unit_size,
11697 thumb_size,
11698 axis,
11699 )
11700 });
11701
11702 ScrollbarLayout {
11703 hitbox: scrollbar_track_hitbox,
11704 visible_range,
11705 text_unit_size,
11706 thumb_bounds,
11707 thumb_state: Default::default(),
11708 }
11709 }
11710
11711 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11712 if let Some(thumb_state) = thumb_state {
11713 Self {
11714 thumb_state,
11715 ..self
11716 }
11717 } else {
11718 self
11719 }
11720 }
11721
11722 fn thumb_bounds(
11723 scrollbar_track: &Hitbox,
11724 content_offset: f64,
11725 visible_range_start: f64,
11726 text_unit_size: Pixels,
11727 thumb_size: Pixels,
11728 axis: ScrollbarAxis,
11729 ) -> Bounds<Pixels> {
11730 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11731 origin
11732 + Pixels::from(
11733 content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11734 )
11735 });
11736 Bounds::new(
11737 thumb_origin,
11738 scrollbar_track.size.apply_along(axis, |_| thumb_size),
11739 )
11740 }
11741
11742 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11743 self.thumb_bounds
11744 .is_some_and(|bounds| bounds.contains(position))
11745 }
11746
11747 fn marker_quads_for_ranges(
11748 &self,
11749 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11750 column: Option<usize>,
11751 ) -> Vec<PaintQuad> {
11752 struct MinMax {
11753 min: Pixels,
11754 max: Pixels,
11755 }
11756 let (x_range, height_limit) = if let Some(column) = column {
11757 let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11758 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11759 let end = start + column_width;
11760 (
11761 Range { start, end },
11762 MinMax {
11763 min: Self::MIN_MARKER_HEIGHT,
11764 max: px(f32::MAX),
11765 },
11766 )
11767 } else {
11768 (
11769 Range {
11770 start: Self::BORDER_WIDTH,
11771 end: self.hitbox.size.width,
11772 },
11773 MinMax {
11774 min: Self::LINE_MARKER_HEIGHT,
11775 max: Self::LINE_MARKER_HEIGHT,
11776 },
11777 )
11778 };
11779
11780 let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11781 let mut pixel_ranges = row_ranges
11782 .into_iter()
11783 .map(|range| {
11784 let start_y = row_to_y(range.start);
11785 let end_y = row_to_y(range.end)
11786 + self
11787 .text_unit_size
11788 .max(height_limit.min)
11789 .min(height_limit.max);
11790 ColoredRange {
11791 start: start_y,
11792 end: end_y,
11793 color: range.color,
11794 }
11795 })
11796 .peekable();
11797
11798 let mut quads = Vec::new();
11799 while let Some(mut pixel_range) = pixel_ranges.next() {
11800 while let Some(next_pixel_range) = pixel_ranges.peek() {
11801 if pixel_range.end >= next_pixel_range.start - px(1.0)
11802 && pixel_range.color == next_pixel_range.color
11803 {
11804 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11805 pixel_ranges.next();
11806 } else {
11807 break;
11808 }
11809 }
11810
11811 let bounds = Bounds::from_corners(
11812 point(x_range.start, pixel_range.start),
11813 point(x_range.end, pixel_range.end),
11814 );
11815 quads.push(quad(
11816 bounds,
11817 Corners::default(),
11818 pixel_range.color,
11819 Edges::default(),
11820 Hsla::transparent_black(),
11821 BorderStyle::default(),
11822 ));
11823 }
11824
11825 quads
11826 }
11827}
11828
11829struct MinimapLayout {
11830 pub minimap: AnyElement,
11831 pub thumb_layout: ScrollbarLayout,
11832 pub minimap_scroll_top: ScrollOffset,
11833 pub minimap_line_height: Pixels,
11834 pub thumb_border_style: MinimapThumbBorder,
11835 pub max_scroll_top: ScrollOffset,
11836}
11837
11838impl MinimapLayout {
11839 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11840 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11841 /// The minimap width as a percentage of the editor width.
11842 const MINIMAP_WIDTH_PCT: f32 = 0.15;
11843 /// Calculates the scroll top offset the minimap editor has to have based on the
11844 /// current scroll progress.
11845 fn calculate_minimap_top_offset(
11846 document_lines: f64,
11847 visible_editor_lines: f64,
11848 visible_minimap_lines: f64,
11849 scroll_position: f64,
11850 ) -> ScrollOffset {
11851 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11852 if non_visible_document_lines == 0. {
11853 0.
11854 } else {
11855 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11856 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11857 }
11858 }
11859}
11860
11861struct CreaseTrailerLayout {
11862 element: AnyElement,
11863 bounds: Bounds<Pixels>,
11864}
11865
11866pub(crate) struct PositionMap {
11867 pub size: Size<Pixels>,
11868 pub line_height: Pixels,
11869 pub scroll_position: gpui::Point<ScrollOffset>,
11870 pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11871 pub scroll_max: gpui::Point<ScrollOffset>,
11872 pub em_width: Pixels,
11873 pub em_advance: Pixels,
11874 pub em_layout_width: Pixels,
11875 pub visible_row_range: Range<DisplayRow>,
11876 pub line_layouts: Vec<LineWithInvisibles>,
11877 pub snapshot: EditorSnapshot,
11878 pub text_align: TextAlign,
11879 pub content_width: Pixels,
11880 pub text_hitbox: Hitbox,
11881 pub gutter_hitbox: Hitbox,
11882 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11883 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11884 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11885}
11886
11887#[derive(Debug, Copy, Clone)]
11888pub struct PointForPosition {
11889 pub previous_valid: DisplayPoint,
11890 pub next_valid: DisplayPoint,
11891 pub exact_unclipped: DisplayPoint,
11892 pub column_overshoot_after_line_end: u32,
11893}
11894
11895impl PointForPosition {
11896 pub fn as_valid(&self) -> Option<DisplayPoint> {
11897 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11898 Some(self.previous_valid)
11899 } else {
11900 None
11901 }
11902 }
11903
11904 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11905 let Some(valid_point) = self.as_valid() else {
11906 return false;
11907 };
11908 let range = selection.range();
11909
11910 let candidate_row = valid_point.row();
11911 let candidate_col = valid_point.column();
11912
11913 let start_row = range.start.row();
11914 let start_col = range.start.column();
11915 let end_row = range.end.row();
11916 let end_col = range.end.column();
11917
11918 if candidate_row < start_row || candidate_row > end_row {
11919 false
11920 } else if start_row == end_row {
11921 candidate_col >= start_col && candidate_col < end_col
11922 } else if candidate_row == start_row {
11923 candidate_col >= start_col
11924 } else if candidate_row == end_row {
11925 candidate_col < end_col
11926 } else {
11927 true
11928 }
11929 }
11930}
11931
11932impl PositionMap {
11933 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11934 let text_bounds = self.text_hitbox.bounds;
11935 let scroll_position = self.snapshot.scroll_position();
11936 let position = position - text_bounds.origin;
11937 let y = position.y.max(px(0.)).min(self.size.height);
11938 let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11939 let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11940
11941 let (column, x_overshoot_after_line_end) = if let Some(line) = self
11942 .line_layouts
11943 .get(row as usize - scroll_position.y as usize)
11944 {
11945 let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11946 let x_relative_to_text = x - alignment_offset;
11947 if let Some(ix) = line.index_for_x(x_relative_to_text) {
11948 (ix as u32, px(0.))
11949 } else {
11950 (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11951 }
11952 } else {
11953 (0, x)
11954 };
11955
11956 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11957 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11958 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11959
11960 let column_overshoot_after_line_end =
11961 (x_overshoot_after_line_end / self.em_layout_width) as u32;
11962 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11963 PointForPosition {
11964 previous_valid,
11965 next_valid,
11966 exact_unclipped,
11967 column_overshoot_after_line_end,
11968 }
11969 }
11970
11971 fn point_for_position_on_line(
11972 &self,
11973 position: gpui::Point<Pixels>,
11974 row: DisplayRow,
11975 line: &LineWithInvisibles,
11976 ) -> PointForPosition {
11977 let text_bounds = self.text_hitbox.bounds;
11978 let scroll_position = self.snapshot.scroll_position();
11979 let position = position - text_bounds.origin;
11980 let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11981
11982 let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11983 let x_relative_to_text = x - alignment_offset;
11984 let (column, x_overshoot_after_line_end) =
11985 if let Some(ix) = line.index_for_x(x_relative_to_text) {
11986 (ix as u32, px(0.))
11987 } else {
11988 (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11989 };
11990
11991 let mut exact_unclipped = DisplayPoint::new(row, column);
11992 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11993 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11994
11995 let column_overshoot_after_line_end =
11996 (x_overshoot_after_line_end / self.em_layout_width) as u32;
11997 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11998 PointForPosition {
11999 previous_valid,
12000 next_valid,
12001 exact_unclipped,
12002 column_overshoot_after_line_end,
12003 }
12004 }
12005}
12006
12007pub(crate) struct BlockLayout {
12008 pub(crate) id: BlockId,
12009 pub(crate) x_offset: Pixels,
12010 pub(crate) row: Option<DisplayRow>,
12011 pub(crate) element: AnyElement,
12012 pub(crate) available_space: Size<AvailableSpace>,
12013 pub(crate) style: BlockStyle,
12014 pub(crate) overlaps_gutter: bool,
12015 pub(crate) is_buffer_header: bool,
12016}
12017
12018pub fn layout_line(
12019 row: DisplayRow,
12020 snapshot: &EditorSnapshot,
12021 style: &EditorStyle,
12022 text_width: Pixels,
12023 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
12024 window: &mut Window,
12025 cx: &mut App,
12026) -> LineWithInvisibles {
12027 let use_tree_sitter =
12028 !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
12029 let language_aware = LanguageAwareStyling {
12030 tree_sitter: use_tree_sitter,
12031 diagnostics: true,
12032 };
12033 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), language_aware, style);
12034 LineWithInvisibles::from_chunks(
12035 chunks,
12036 style,
12037 MAX_LINE_LEN,
12038 1,
12039 &snapshot.mode,
12040 text_width,
12041 is_row_soft_wrapped,
12042 &[],
12043 window,
12044 cx,
12045 )
12046 .pop()
12047 .unwrap()
12048}
12049
12050#[derive(Debug, Clone)]
12051pub struct IndentGuideLayout {
12052 origin: gpui::Point<Pixels>,
12053 length: Pixels,
12054 single_indent_width: Pixels,
12055 display_row_range: Range<DisplayRow>,
12056 depth: u32,
12057 active: bool,
12058 settings: IndentGuideSettings,
12059}
12060
12061pub struct CursorLayout {
12062 origin: gpui::Point<Pixels>,
12063 block_width: Pixels,
12064 line_height: Pixels,
12065 color: Hsla,
12066 shape: CursorShape,
12067 block_text: Option<ShapedLine>,
12068 cursor_name: Option<AnyElement>,
12069}
12070
12071#[derive(Debug)]
12072pub struct CursorName {
12073 string: SharedString,
12074 color: Hsla,
12075 is_top_row: bool,
12076}
12077
12078impl CursorLayout {
12079 pub fn new(
12080 origin: gpui::Point<Pixels>,
12081 block_width: Pixels,
12082 line_height: Pixels,
12083 color: Hsla,
12084 shape: CursorShape,
12085 block_text: Option<ShapedLine>,
12086 ) -> CursorLayout {
12087 CursorLayout {
12088 origin,
12089 block_width,
12090 line_height,
12091 color,
12092 shape,
12093 block_text,
12094 cursor_name: None,
12095 }
12096 }
12097
12098 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12099 Bounds {
12100 origin: self.origin + origin,
12101 size: size(self.block_width, self.line_height),
12102 }
12103 }
12104
12105 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12106 match self.shape {
12107 CursorShape::Bar => Bounds {
12108 origin: self.origin + origin,
12109 size: size(px(2.0), self.line_height),
12110 },
12111 CursorShape::Block | CursorShape::Hollow => Bounds {
12112 origin: self.origin + origin,
12113 size: size(self.block_width, self.line_height),
12114 },
12115 CursorShape::Underline => Bounds {
12116 origin: self.origin
12117 + origin
12118 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
12119 size: size(self.block_width, px(2.0)),
12120 },
12121 }
12122 }
12123
12124 pub fn layout(
12125 &mut self,
12126 origin: gpui::Point<Pixels>,
12127 cursor_name: Option<CursorName>,
12128 window: &mut Window,
12129 cx: &mut App,
12130 ) {
12131 if let Some(cursor_name) = cursor_name {
12132 let bounds = self.bounds(origin);
12133 let text_size = self.line_height / 1.5;
12134
12135 let name_origin = if cursor_name.is_top_row {
12136 point(bounds.right() - px(1.), bounds.top())
12137 } else {
12138 match self.shape {
12139 CursorShape::Bar => point(
12140 bounds.right() - px(2.),
12141 bounds.top() - text_size / 2. - px(1.),
12142 ),
12143 _ => point(
12144 bounds.right() - px(1.),
12145 bounds.top() - text_size / 2. - px(1.),
12146 ),
12147 }
12148 };
12149 let mut name_element = div()
12150 .bg(self.color)
12151 .text_size(text_size)
12152 .px_0p5()
12153 .line_height(text_size + px(2.))
12154 .text_color(cursor_name.color)
12155 .child(cursor_name.string)
12156 .into_any_element();
12157
12158 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
12159
12160 self.cursor_name = Some(name_element);
12161 }
12162 }
12163
12164 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
12165 let bounds = self.bounds(origin);
12166
12167 //Draw background or border quad
12168 let cursor = if matches!(self.shape, CursorShape::Hollow) {
12169 outline(bounds, self.color, BorderStyle::Solid)
12170 } else {
12171 fill(bounds, self.color)
12172 };
12173
12174 if let Some(name) = &mut self.cursor_name {
12175 name.paint(window, cx);
12176 }
12177
12178 window.paint_quad(cursor);
12179
12180 if let Some(block_text) = &self.block_text {
12181 block_text
12182 .paint(
12183 self.origin + origin,
12184 self.line_height,
12185 TextAlign::Left,
12186 None,
12187 window,
12188 cx,
12189 )
12190 .log_err();
12191 }
12192 }
12193
12194 pub fn shape(&self) -> CursorShape {
12195 self.shape
12196 }
12197}
12198
12199#[derive(Debug)]
12200pub struct HighlightedRange {
12201 pub start_y: Pixels,
12202 pub line_height: Pixels,
12203 pub lines: Vec<HighlightedRangeLine>,
12204 pub color: Hsla,
12205 pub corner_radius: Pixels,
12206}
12207
12208#[derive(Debug)]
12209pub struct HighlightedRangeLine {
12210 pub start_x: Pixels,
12211 pub end_x: Pixels,
12212}
12213
12214impl HighlightedRange {
12215 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
12216 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
12217 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
12218 self.paint_lines(
12219 self.start_y + self.line_height,
12220 &self.lines[1..],
12221 fill,
12222 bounds,
12223 window,
12224 );
12225 } else {
12226 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
12227 }
12228 }
12229
12230 fn paint_lines(
12231 &self,
12232 start_y: Pixels,
12233 lines: &[HighlightedRangeLine],
12234 fill: bool,
12235 _bounds: Bounds<Pixels>,
12236 window: &mut Window,
12237 ) {
12238 if lines.is_empty() {
12239 return;
12240 }
12241
12242 let first_line = lines.first().unwrap();
12243 let last_line = lines.last().unwrap();
12244
12245 let first_top_left = point(first_line.start_x, start_y);
12246 let first_top_right = point(first_line.end_x, start_y);
12247
12248 let curve_height = point(Pixels::ZERO, self.corner_radius);
12249 let curve_width = |start_x: Pixels, end_x: Pixels| {
12250 let max = (end_x - start_x) / 2.;
12251 let width = if max < self.corner_radius {
12252 max
12253 } else {
12254 self.corner_radius
12255 };
12256
12257 point(width, Pixels::ZERO)
12258 };
12259
12260 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12261 let mut builder = if fill {
12262 gpui::PathBuilder::fill()
12263 } else {
12264 gpui::PathBuilder::stroke(px(1.))
12265 };
12266 builder.move_to(first_top_right - top_curve_width);
12267 builder.curve_to(first_top_right + curve_height, first_top_right);
12268
12269 let mut iter = lines.iter().enumerate().peekable();
12270 while let Some((ix, line)) = iter.next() {
12271 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12272
12273 if let Some((_, next_line)) = iter.peek() {
12274 let next_top_right = point(next_line.end_x, bottom_right.y);
12275
12276 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12277 Ordering::Equal => {
12278 builder.line_to(bottom_right);
12279 }
12280 Ordering::Less => {
12281 let curve_width = curve_width(next_top_right.x, bottom_right.x);
12282 builder.line_to(bottom_right - curve_height);
12283 if self.corner_radius > Pixels::ZERO {
12284 builder.curve_to(bottom_right - curve_width, bottom_right);
12285 }
12286 builder.line_to(next_top_right + curve_width);
12287 if self.corner_radius > Pixels::ZERO {
12288 builder.curve_to(next_top_right + curve_height, next_top_right);
12289 }
12290 }
12291 Ordering::Greater => {
12292 let curve_width = curve_width(bottom_right.x, next_top_right.x);
12293 builder.line_to(bottom_right - curve_height);
12294 if self.corner_radius > Pixels::ZERO {
12295 builder.curve_to(bottom_right + curve_width, bottom_right);
12296 }
12297 builder.line_to(next_top_right - curve_width);
12298 if self.corner_radius > Pixels::ZERO {
12299 builder.curve_to(next_top_right + curve_height, next_top_right);
12300 }
12301 }
12302 }
12303 } else {
12304 let curve_width = curve_width(line.start_x, line.end_x);
12305 builder.line_to(bottom_right - curve_height);
12306 if self.corner_radius > Pixels::ZERO {
12307 builder.curve_to(bottom_right - curve_width, bottom_right);
12308 }
12309
12310 let bottom_left = point(line.start_x, bottom_right.y);
12311 builder.line_to(bottom_left + curve_width);
12312 if self.corner_radius > Pixels::ZERO {
12313 builder.curve_to(bottom_left - curve_height, bottom_left);
12314 }
12315 }
12316 }
12317
12318 if first_line.start_x > last_line.start_x {
12319 let curve_width = curve_width(last_line.start_x, first_line.start_x);
12320 let second_top_left = point(last_line.start_x, start_y + self.line_height);
12321 builder.line_to(second_top_left + curve_height);
12322 if self.corner_radius > Pixels::ZERO {
12323 builder.curve_to(second_top_left + curve_width, second_top_left);
12324 }
12325 let first_bottom_left = point(first_line.start_x, second_top_left.y);
12326 builder.line_to(first_bottom_left - curve_width);
12327 if self.corner_radius > Pixels::ZERO {
12328 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12329 }
12330 }
12331
12332 builder.line_to(first_top_left + curve_height);
12333 if self.corner_radius > Pixels::ZERO {
12334 builder.curve_to(first_top_left + top_curve_width, first_top_left);
12335 }
12336 builder.line_to(first_top_right - top_curve_width);
12337
12338 if let Ok(path) = builder.build() {
12339 window.paint_path(path, self.color);
12340 }
12341 }
12342}
12343
12344pub(crate) struct StickyHeader {
12345 pub sticky_row: DisplayRow,
12346 pub start_point: Point,
12347 pub offset: ScrollOffset,
12348}
12349
12350enum CursorPopoverType {
12351 CodeContextMenu,
12352 EditPrediction,
12353}
12354
12355pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12356 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12357}
12358
12359fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12360 (delta.pow(1.2) / 300.0).into()
12361}
12362
12363pub fn register_action<T: Action>(
12364 editor: &Entity<Editor>,
12365 window: &mut Window,
12366 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12367) {
12368 let editor = editor.clone();
12369 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12370 let action = action.downcast_ref().unwrap();
12371 if phase == DispatchPhase::Bubble {
12372 editor.update(cx, |editor, cx| {
12373 listener(editor, action, window, cx);
12374 })
12375 }
12376 })
12377}
12378
12379/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12380/// both full and auto-height editors compute wrap widths consistently.
12381fn calculate_wrap_width(
12382 soft_wrap: SoftWrap,
12383 editor_width: Pixels,
12384 em_width: Pixels,
12385) -> Option<Pixels> {
12386 let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12387
12388 match soft_wrap {
12389 SoftWrap::GitDiff => None,
12390 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12391 SoftWrap::EditorWidth => Some(editor_width),
12392 SoftWrap::Column(column) => Some(wrap_width_for(column)),
12393 SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12394 }
12395}
12396
12397fn compute_auto_height_layout(
12398 editor: &mut Editor,
12399 min_lines: usize,
12400 max_lines: Option<usize>,
12401 known_dimensions: Size<Option<Pixels>>,
12402 available_width: AvailableSpace,
12403 window: &mut Window,
12404 cx: &mut Context<Editor>,
12405) -> Option<Size<Pixels>> {
12406 let width = known_dimensions.width.or({
12407 if let AvailableSpace::Definite(available_width) = available_width {
12408 Some(available_width)
12409 } else {
12410 None
12411 }
12412 })?;
12413 if let Some(height) = known_dimensions.height {
12414 return Some(size(width, height));
12415 }
12416
12417 let style = editor.style.as_ref().unwrap();
12418 let font_id = window.text_system().resolve_font(&style.text.font());
12419 let font_size = style.text.font_size.to_pixels(window.rem_size());
12420 let line_height = style.text.line_height_in_pixels(window.rem_size());
12421 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12422
12423 let mut snapshot = editor.snapshot(window, cx);
12424 let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12425
12426 editor.gutter_dimensions = gutter_dimensions;
12427 let text_width = width - gutter_dimensions.width;
12428 let overscroll = size(em_width, px(0.));
12429
12430 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12431 let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width);
12432 if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12433 snapshot = editor.snapshot(window, cx);
12434 }
12435
12436 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12437
12438 let min_height = line_height * min_lines as f32;
12439 let content_height = scroll_height.max(min_height);
12440
12441 let final_height = if let Some(max_lines) = max_lines {
12442 let max_height = line_height * max_lines as f32;
12443 content_height.min(max_height)
12444 } else {
12445 content_height
12446 };
12447
12448 Some(size(width, final_height))
12449}
12450
12451#[cfg(test)]
12452mod tests {
12453 use super::*;
12454 use crate::{
12455 Editor, MultiBuffer, SelectionEffects,
12456 display_map::{BlockPlacement, BlockProperties},
12457 editor_tests::{init_test, update_test_language_settings},
12458 };
12459 use gpui::{TestAppContext, VisualTestContext};
12460 use language::{Buffer, language_settings, tree_sitter_python};
12461 use log::info;
12462 use rand::{RngCore, rngs::StdRng};
12463 use std::num::NonZeroU32;
12464 use util::test::sample_text;
12465
12466 #[gpui::test]
12467 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12468 init_test(cx, |_| {});
12469 let window = cx.add_window(|window, cx| {
12470 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12471 let mut editor = Editor::new(
12472 EditorMode::AutoHeight {
12473 min_lines: 1,
12474 max_lines: None,
12475 },
12476 buffer,
12477 None,
12478 window,
12479 cx,
12480 );
12481 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12482 editor
12483 });
12484 let cx = &mut VisualTestContext::from_window(*window, cx);
12485 let editor = window.root(cx).unwrap();
12486 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12487
12488 for x in 1..=100 {
12489 let (_, state) = cx.draw(
12490 Default::default(),
12491 size(px(200. + 0.13 * x as f32), px(500.)),
12492 |_, _| EditorElement::new(&editor, style.clone()),
12493 );
12494
12495 assert!(
12496 state.position_map.scroll_max.x == 0.,
12497 "Soft wrapped editor should have no horizontal scrolling!"
12498 );
12499 }
12500 }
12501
12502 #[gpui::test]
12503 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12504 init_test(cx, |_| {});
12505 let window = cx.add_window(|window, cx| {
12506 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12507 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12508 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12509 editor
12510 });
12511 let cx = &mut VisualTestContext::from_window(*window, cx);
12512 let editor = window.root(cx).unwrap();
12513 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12514
12515 for x in 1..=100 {
12516 let (_, state) = cx.draw(
12517 Default::default(),
12518 size(px(200. + 0.13 * x as f32), px(500.)),
12519 |_, _| EditorElement::new(&editor, style.clone()),
12520 );
12521
12522 assert!(
12523 state.position_map.scroll_max.x == 0.,
12524 "Soft wrapped editor should have no horizontal scrolling!"
12525 );
12526 }
12527 }
12528
12529 #[gpui::test]
12530 fn test_layout_line_numbers(cx: &mut TestAppContext) {
12531 init_test(cx, |_| {});
12532 let window = cx.add_window(|window, cx| {
12533 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12534 Editor::new(EditorMode::full(), buffer, None, window, cx)
12535 });
12536
12537 let editor = window.root(cx).unwrap();
12538 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12539 let line_height = window
12540 .update(cx, |_, window, _| {
12541 style.text.line_height_in_pixels(window.rem_size())
12542 })
12543 .unwrap();
12544 let element = EditorElement::new(&editor, style);
12545 let snapshot = window
12546 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12547 .unwrap();
12548
12549 let layouts = cx
12550 .update_window(*window, |_, window, cx| {
12551 element.layout_line_numbers(
12552 None,
12553 GutterDimensions {
12554 left_padding: Pixels::ZERO,
12555 right_padding: Pixels::ZERO,
12556 width: px(30.0),
12557 margin: Pixels::ZERO,
12558 git_blame_entries_width: None,
12559 },
12560 line_height,
12561 gpui::Point::default(),
12562 DisplayRow(0)..DisplayRow(6),
12563 &(0..6)
12564 .map(|row| RowInfo {
12565 buffer_row: Some(row),
12566 ..Default::default()
12567 })
12568 .collect::<Vec<_>>(),
12569 &BTreeMap::default(),
12570 Some(DisplayRow(0)),
12571 &snapshot,
12572 window,
12573 cx,
12574 )
12575 })
12576 .unwrap();
12577 assert_eq!(layouts.len(), 6);
12578
12579 let relative_rows = window
12580 .update(cx, |editor, window, cx| {
12581 let snapshot = editor.snapshot(window, cx);
12582 snapshot.calculate_relative_line_numbers(
12583 &(DisplayRow(0)..DisplayRow(6)),
12584 DisplayRow(3),
12585 false,
12586 )
12587 })
12588 .unwrap();
12589 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12590 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12591 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12592 // current line has no relative number
12593 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12594 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12595 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12596
12597 // works if cursor is before screen
12598 let relative_rows = window
12599 .update(cx, |editor, window, cx| {
12600 let snapshot = editor.snapshot(window, cx);
12601 snapshot.calculate_relative_line_numbers(
12602 &(DisplayRow(3)..DisplayRow(6)),
12603 DisplayRow(1),
12604 false,
12605 )
12606 })
12607 .unwrap();
12608 assert_eq!(relative_rows.len(), 3);
12609 assert_eq!(relative_rows[&DisplayRow(3)], 2);
12610 assert_eq!(relative_rows[&DisplayRow(4)], 3);
12611 assert_eq!(relative_rows[&DisplayRow(5)], 4);
12612
12613 // works if cursor is after screen
12614 let relative_rows = window
12615 .update(cx, |editor, window, cx| {
12616 let snapshot = editor.snapshot(window, cx);
12617 snapshot.calculate_relative_line_numbers(
12618 &(DisplayRow(0)..DisplayRow(3)),
12619 DisplayRow(6),
12620 false,
12621 )
12622 })
12623 .unwrap();
12624 assert_eq!(relative_rows.len(), 3);
12625 assert_eq!(relative_rows[&DisplayRow(0)], 5);
12626 assert_eq!(relative_rows[&DisplayRow(1)], 4);
12627 assert_eq!(relative_rows[&DisplayRow(2)], 3);
12628
12629 const DELETED_LINE: u32 = 3;
12630 let layouts = cx
12631 .update_window(*window, |_, window, cx| {
12632 element.layout_line_numbers(
12633 None,
12634 GutterDimensions {
12635 left_padding: Pixels::ZERO,
12636 right_padding: Pixels::ZERO,
12637 width: px(30.0),
12638 margin: Pixels::ZERO,
12639 git_blame_entries_width: None,
12640 },
12641 line_height,
12642 gpui::Point::default(),
12643 DisplayRow(0)..DisplayRow(6),
12644 &(0..6)
12645 .map(|row| RowInfo {
12646 buffer_row: Some(row),
12647 diff_status: (row == DELETED_LINE).then(|| {
12648 DiffHunkStatus::deleted(
12649 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12650 )
12651 }),
12652 ..Default::default()
12653 })
12654 .collect::<Vec<_>>(),
12655 &BTreeMap::default(),
12656 Some(DisplayRow(0)),
12657 &snapshot,
12658 window,
12659 cx,
12660 )
12661 })
12662 .unwrap();
12663 assert_eq!(layouts.len(), 5,);
12664 assert!(
12665 layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12666 "Deleted line should not have a line number"
12667 );
12668 }
12669
12670 #[gpui::test]
12671 async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12672 init_test(cx, |_| {});
12673
12674 let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12675
12676 let window = cx.add_window(|window, cx| {
12677 let buffer = cx.new(|cx| {
12678 Buffer::local(
12679 indoc::indoc! {"
12680 fn test() -> int {
12681 return 2;
12682 }
12683
12684 fn another_test() -> int {
12685 # This is a very peculiar method that is hard to grasp.
12686 return 4;
12687 }
12688 "},
12689 cx,
12690 )
12691 .with_language(python_lang, cx)
12692 });
12693
12694 let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12695 Editor::new(EditorMode::full(), buffer, None, window, cx)
12696 });
12697
12698 let editor = window.root(cx).unwrap();
12699 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12700 let line_height = window
12701 .update(cx, |_, window, _| {
12702 style.text.line_height_in_pixels(window.rem_size())
12703 })
12704 .unwrap();
12705 let element = EditorElement::new(&editor, style);
12706 let snapshot = window
12707 .update(cx, |editor, window, cx| {
12708 editor.fold_at(MultiBufferRow(0), window, cx);
12709 editor.snapshot(window, cx)
12710 })
12711 .unwrap();
12712
12713 let layouts = cx
12714 .update_window(*window, |_, window, cx| {
12715 element.layout_line_numbers(
12716 None,
12717 GutterDimensions {
12718 left_padding: Pixels::ZERO,
12719 right_padding: Pixels::ZERO,
12720 width: px(30.0),
12721 margin: Pixels::ZERO,
12722 git_blame_entries_width: None,
12723 },
12724 line_height,
12725 gpui::Point::default(),
12726 DisplayRow(0)..DisplayRow(6),
12727 &(0..6)
12728 .map(|row| RowInfo {
12729 buffer_row: Some(row),
12730 ..Default::default()
12731 })
12732 .collect::<Vec<_>>(),
12733 &BTreeMap::default(),
12734 Some(DisplayRow(3)),
12735 &snapshot,
12736 window,
12737 cx,
12738 )
12739 })
12740 .unwrap();
12741 assert_eq!(layouts.len(), 6);
12742
12743 let relative_rows = window
12744 .update(cx, |editor, window, cx| {
12745 let snapshot = editor.snapshot(window, cx);
12746 snapshot.calculate_relative_line_numbers(
12747 &(DisplayRow(0)..DisplayRow(6)),
12748 DisplayRow(3),
12749 false,
12750 )
12751 })
12752 .unwrap();
12753 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12754 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12755 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12756 // current line has no relative number
12757 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12758 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12759 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12760 }
12761
12762 #[gpui::test]
12763 fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12764 init_test(cx, |_| {});
12765 let window = cx.add_window(|window, cx| {
12766 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12767 Editor::new(EditorMode::full(), buffer, None, window, cx)
12768 });
12769
12770 update_test_language_settings(cx, &|s| {
12771 s.defaults.preferred_line_length = Some(5_u32);
12772 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12773 });
12774
12775 let editor = window.root(cx).unwrap();
12776 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12777 let line_height = window
12778 .update(cx, |_, window, _| {
12779 style.text.line_height_in_pixels(window.rem_size())
12780 })
12781 .unwrap();
12782 let element = EditorElement::new(&editor, style);
12783 let snapshot = window
12784 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12785 .unwrap();
12786
12787 let layouts = cx
12788 .update_window(*window, |_, window, cx| {
12789 element.layout_line_numbers(
12790 None,
12791 GutterDimensions {
12792 left_padding: Pixels::ZERO,
12793 right_padding: Pixels::ZERO,
12794 width: px(30.0),
12795 margin: Pixels::ZERO,
12796 git_blame_entries_width: None,
12797 },
12798 line_height,
12799 gpui::Point::default(),
12800 DisplayRow(0)..DisplayRow(6),
12801 &(0..6)
12802 .map(|row| RowInfo {
12803 buffer_row: Some(row),
12804 ..Default::default()
12805 })
12806 .collect::<Vec<_>>(),
12807 &BTreeMap::default(),
12808 Some(DisplayRow(0)),
12809 &snapshot,
12810 window,
12811 cx,
12812 )
12813 })
12814 .unwrap();
12815 assert_eq!(layouts.len(), 3);
12816
12817 let relative_rows = window
12818 .update(cx, |editor, window, cx| {
12819 let snapshot = editor.snapshot(window, cx);
12820 snapshot.calculate_relative_line_numbers(
12821 &(DisplayRow(0)..DisplayRow(6)),
12822 DisplayRow(3),
12823 true,
12824 )
12825 })
12826 .unwrap();
12827
12828 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12829 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12830 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12831 // current line has no relative number
12832 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12833 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12834 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12835
12836 let layouts = cx
12837 .update_window(*window, |_, window, cx| {
12838 element.layout_line_numbers(
12839 None,
12840 GutterDimensions {
12841 left_padding: Pixels::ZERO,
12842 right_padding: Pixels::ZERO,
12843 width: px(30.0),
12844 margin: Pixels::ZERO,
12845 git_blame_entries_width: None,
12846 },
12847 line_height,
12848 gpui::Point::default(),
12849 DisplayRow(0)..DisplayRow(6),
12850 &(0..6)
12851 .map(|row| RowInfo {
12852 buffer_row: Some(row),
12853 diff_status: Some(DiffHunkStatus::deleted(
12854 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12855 )),
12856 ..Default::default()
12857 })
12858 .collect::<Vec<_>>(),
12859 &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12860 Some(DisplayRow(0)),
12861 &snapshot,
12862 window,
12863 cx,
12864 )
12865 })
12866 .unwrap();
12867 assert!(
12868 layouts.is_empty(),
12869 "Deleted lines should have no line number"
12870 );
12871
12872 let relative_rows = window
12873 .update(cx, |editor, window, cx| {
12874 let snapshot = editor.snapshot(window, cx);
12875 snapshot.calculate_relative_line_numbers(
12876 &(DisplayRow(0)..DisplayRow(6)),
12877 DisplayRow(3),
12878 true,
12879 )
12880 })
12881 .unwrap();
12882
12883 // Deleted lines should still have relative numbers
12884 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12885 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12886 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12887 // current line, even if deleted, has no relative number
12888 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12889 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12890 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12891 }
12892
12893 #[gpui::test]
12894 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12895 init_test(cx, |_| {});
12896
12897 let window = cx.add_window(|window, cx| {
12898 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12899 Editor::new(EditorMode::full(), buffer, None, window, cx)
12900 });
12901 let cx = &mut VisualTestContext::from_window(*window, cx);
12902 let editor = window.root(cx).unwrap();
12903 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12904
12905 window
12906 .update(cx, |editor, window, cx| {
12907 editor.cursor_offset_on_selection = true;
12908 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12909 s.select_ranges([
12910 Point::new(0, 0)..Point::new(1, 0),
12911 Point::new(3, 2)..Point::new(3, 3),
12912 Point::new(5, 6)..Point::new(6, 0),
12913 ]);
12914 });
12915 })
12916 .unwrap();
12917
12918 let (_, state) = cx.draw(
12919 point(px(500.), px(500.)),
12920 size(px(500.), px(500.)),
12921 |_, _| EditorElement::new(&editor, style),
12922 );
12923
12924 assert_eq!(state.selections.len(), 1);
12925 let local_selections = &state.selections[0].1;
12926 assert_eq!(local_selections.len(), 3);
12927 // moves cursor back one line
12928 assert_eq!(
12929 local_selections[0].head,
12930 DisplayPoint::new(DisplayRow(0), 6)
12931 );
12932 assert_eq!(
12933 local_selections[0].range,
12934 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12935 );
12936
12937 // moves cursor back one column
12938 assert_eq!(
12939 local_selections[1].range,
12940 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12941 );
12942 assert_eq!(
12943 local_selections[1].head,
12944 DisplayPoint::new(DisplayRow(3), 2)
12945 );
12946
12947 // leaves cursor on the max point
12948 assert_eq!(
12949 local_selections[2].range,
12950 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12951 );
12952 assert_eq!(
12953 local_selections[2].head,
12954 DisplayPoint::new(DisplayRow(6), 0)
12955 );
12956
12957 // active lines does not include 1 (even though the range of the selection does)
12958 assert_eq!(
12959 state.active_rows.keys().cloned().collect::<Vec<_>>(),
12960 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12961 );
12962 }
12963
12964 #[gpui::test]
12965 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12966 init_test(cx, |_| {});
12967
12968 let window = cx.add_window(|window, cx| {
12969 let buffer = MultiBuffer::build_simple("", cx);
12970 Editor::new(EditorMode::full(), buffer, None, window, cx)
12971 });
12972 let cx = &mut VisualTestContext::from_window(*window, cx);
12973 let editor = window.root(cx).unwrap();
12974 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12975 window
12976 .update(cx, |editor, window, cx| {
12977 editor.set_placeholder_text("hello", window, cx);
12978 editor.insert_blocks(
12979 [BlockProperties {
12980 style: BlockStyle::Fixed,
12981 placement: BlockPlacement::Above(Anchor::Min),
12982 height: Some(3),
12983 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12984 priority: 0,
12985 }],
12986 None,
12987 cx,
12988 );
12989
12990 // Blur the editor so that it displays placeholder text.
12991 window.blur();
12992 })
12993 .unwrap();
12994
12995 let (_, state) = cx.draw(
12996 point(px(500.), px(500.)),
12997 size(px(500.), px(500.)),
12998 |_, _| EditorElement::new(&editor, style),
12999 );
13000 assert_eq!(state.position_map.line_layouts.len(), 4);
13001 assert_eq!(state.line_numbers.len(), 1);
13002 assert_eq!(
13003 state
13004 .line_numbers
13005 .get(&MultiBufferRow(0))
13006 .map(|line_number| line_number
13007 .segments
13008 .first()
13009 .unwrap()
13010 .shaped_line
13011 .text
13012 .as_ref()),
13013 Some("1")
13014 );
13015 }
13016
13017 #[gpui::test]
13018 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
13019 const TAB_SIZE: u32 = 4;
13020
13021 let input_text = "\t \t|\t| a b";
13022 let expected_invisibles = vec![
13023 Invisible::Tab {
13024 line_start_offset: 0,
13025 line_end_offset: TAB_SIZE as usize,
13026 },
13027 Invisible::Whitespace {
13028 line_offset: TAB_SIZE as usize,
13029 },
13030 Invisible::Tab {
13031 line_start_offset: TAB_SIZE as usize + 1,
13032 line_end_offset: TAB_SIZE as usize * 2,
13033 },
13034 Invisible::Tab {
13035 line_start_offset: TAB_SIZE as usize * 2 + 1,
13036 line_end_offset: TAB_SIZE as usize * 3,
13037 },
13038 Invisible::Whitespace {
13039 line_offset: TAB_SIZE as usize * 3 + 1,
13040 },
13041 Invisible::Whitespace {
13042 line_offset: TAB_SIZE as usize * 3 + 3,
13043 },
13044 ];
13045 assert_eq!(
13046 expected_invisibles.len(),
13047 input_text
13048 .chars()
13049 .filter(|initial_char| initial_char.is_whitespace())
13050 .count(),
13051 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13052 );
13053
13054 for show_line_numbers in [true, false] {
13055 init_test(cx, |s| {
13056 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13057 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
13058 });
13059
13060 let actual_invisibles = collect_invisibles_from_new_editor(
13061 cx,
13062 EditorMode::full(),
13063 input_text,
13064 px(500.0),
13065 show_line_numbers,
13066 );
13067
13068 assert_eq!(expected_invisibles, actual_invisibles);
13069 }
13070 }
13071
13072 #[gpui::test]
13073 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
13074 init_test(cx, |s| {
13075 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13076 s.defaults.tab_size = NonZeroU32::new(4);
13077 });
13078
13079 for editor_mode_without_invisibles in [
13080 EditorMode::SingleLine,
13081 EditorMode::AutoHeight {
13082 min_lines: 1,
13083 max_lines: Some(100),
13084 },
13085 ] {
13086 for show_line_numbers in [true, false] {
13087 let invisibles = collect_invisibles_from_new_editor(
13088 cx,
13089 editor_mode_without_invisibles.clone(),
13090 "\t\t\t| | a b",
13091 px(500.0),
13092 show_line_numbers,
13093 );
13094 assert!(
13095 invisibles.is_empty(),
13096 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
13097 );
13098 }
13099 }
13100 }
13101
13102 #[gpui::test]
13103 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
13104 let tab_size = 4;
13105 let input_text = "a\tbcd ".repeat(9);
13106 let repeated_invisibles = [
13107 Invisible::Tab {
13108 line_start_offset: 1,
13109 line_end_offset: tab_size as usize,
13110 },
13111 Invisible::Whitespace {
13112 line_offset: tab_size as usize + 3,
13113 },
13114 Invisible::Whitespace {
13115 line_offset: tab_size as usize + 4,
13116 },
13117 Invisible::Whitespace {
13118 line_offset: tab_size as usize + 5,
13119 },
13120 Invisible::Whitespace {
13121 line_offset: tab_size as usize + 6,
13122 },
13123 Invisible::Whitespace {
13124 line_offset: tab_size as usize + 7,
13125 },
13126 ];
13127 let expected_invisibles = std::iter::once(repeated_invisibles)
13128 .cycle()
13129 .take(9)
13130 .flatten()
13131 .collect::<Vec<_>>();
13132 assert_eq!(
13133 expected_invisibles.len(),
13134 input_text
13135 .chars()
13136 .filter(|initial_char| initial_char.is_whitespace())
13137 .count(),
13138 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13139 );
13140 info!("Expected invisibles: {expected_invisibles:?}");
13141
13142 init_test(cx, |_| {});
13143
13144 // Put the same string with repeating whitespace pattern into editors of various size,
13145 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
13146 let resize_step = 10.0;
13147 let mut editor_width = 200.0;
13148 while editor_width <= 1000.0 {
13149 for show_line_numbers in [true, false] {
13150 update_test_language_settings(cx, &|s| {
13151 s.defaults.tab_size = NonZeroU32::new(tab_size);
13152 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13153 s.defaults.preferred_line_length = Some(editor_width as u32);
13154 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
13155 });
13156
13157 let actual_invisibles = collect_invisibles_from_new_editor(
13158 cx,
13159 EditorMode::full(),
13160 &input_text,
13161 px(editor_width),
13162 show_line_numbers,
13163 );
13164
13165 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
13166 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
13167 let mut i = 0;
13168 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
13169 i = actual_index;
13170 match expected_invisibles.get(i) {
13171 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
13172 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
13173 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
13174 _ => {
13175 panic!(
13176 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
13177 )
13178 }
13179 },
13180 None => {
13181 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
13182 }
13183 }
13184 }
13185 let missing_expected_invisibles = &expected_invisibles[i + 1..];
13186 assert!(
13187 missing_expected_invisibles.is_empty(),
13188 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
13189 );
13190
13191 editor_width += resize_step;
13192 }
13193 }
13194 }
13195
13196 fn collect_invisibles_from_new_editor(
13197 cx: &mut TestAppContext,
13198 editor_mode: EditorMode,
13199 input_text: &str,
13200 editor_width: Pixels,
13201 show_line_numbers: bool,
13202 ) -> Vec<Invisible> {
13203 info!(
13204 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
13205 f32::from(editor_width)
13206 );
13207 let window = cx.add_window(|window, cx| {
13208 let buffer = MultiBuffer::build_simple(input_text, cx);
13209 Editor::new(editor_mode, buffer, None, window, cx)
13210 });
13211 let cx = &mut VisualTestContext::from_window(*window, cx);
13212 let editor = window.root(cx).unwrap();
13213
13214 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13215 window
13216 .update(cx, |editor, _, cx| {
13217 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
13218 editor.set_wrap_width(Some(editor_width), cx);
13219 editor.set_show_line_numbers(show_line_numbers, cx);
13220 })
13221 .unwrap();
13222 let (_, state) = cx.draw(
13223 point(px(500.), px(500.)),
13224 size(px(500.), px(500.)),
13225 |_, _| EditorElement::new(&editor, style),
13226 );
13227 state
13228 .position_map
13229 .line_layouts
13230 .iter()
13231 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13232 .cloned()
13233 .collect()
13234 }
13235
13236 #[gpui::test]
13237 fn test_merge_overlapping_ranges() {
13238 let base_bg = Hsla::white();
13239 let color1 = Hsla {
13240 h: 0.0,
13241 s: 0.5,
13242 l: 0.5,
13243 a: 0.5,
13244 };
13245 let color2 = Hsla {
13246 h: 120.0,
13247 s: 0.5,
13248 l: 0.5,
13249 a: 0.5,
13250 };
13251
13252 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13253 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13254 v.iter()
13255 .map(|(r, _)| (r.start.column(), r.end.column()))
13256 .collect()
13257 };
13258
13259 // Test overlapping ranges blend colors
13260 let overlapping = vec![
13261 (display_point(5)..display_point(15), color1),
13262 (display_point(10)..display_point(20), color2),
13263 ];
13264 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13265 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13266
13267 // Test middle segment should have blended color
13268 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13269 assert_eq!(result[1].1, blended);
13270
13271 // Test adjacent same-color ranges merge
13272 let adjacent_same = vec![
13273 (display_point(5)..display_point(10), color1),
13274 (display_point(10)..display_point(15), color1),
13275 ];
13276 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13277 assert_eq!(cols(&result), vec![(5, 15)]);
13278
13279 // Test contained range splits
13280 let contained = vec![
13281 (display_point(5)..display_point(20), color1),
13282 (display_point(10)..display_point(15), color2),
13283 ];
13284 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13285 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13286
13287 // Test multiple overlaps split at every boundary
13288 let color3 = Hsla {
13289 h: 240.0,
13290 s: 0.5,
13291 l: 0.5,
13292 a: 0.5,
13293 };
13294 let complex = vec![
13295 (display_point(5)..display_point(12), color1),
13296 (display_point(8)..display_point(16), color2),
13297 (display_point(10)..display_point(14), color3),
13298 ];
13299 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13300 assert_eq!(
13301 cols(&result),
13302 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13303 );
13304 }
13305
13306 #[gpui::test]
13307 fn test_bg_segments_per_row() {
13308 let base_bg = Hsla::white();
13309
13310 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13311 {
13312 let selection_color = Hsla {
13313 h: 200.0,
13314 s: 0.5,
13315 l: 0.5,
13316 a: 0.5,
13317 };
13318 let player_color = PlayerColor {
13319 cursor: selection_color,
13320 background: selection_color,
13321 selection: selection_color,
13322 };
13323
13324 let spanning_selection = SelectionLayout {
13325 head: DisplayPoint::new(DisplayRow(3), 7),
13326 cursor_shape: CursorShape::Bar,
13327 is_newest: true,
13328 is_local: true,
13329 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13330 active_rows: DisplayRow(1)..DisplayRow(4),
13331 user_name: None,
13332 };
13333
13334 let selections = vec![(player_color, vec![spanning_selection])];
13335 let result = EditorElement::bg_segments_per_row(
13336 DisplayRow(0)..DisplayRow(5),
13337 &selections,
13338 &[],
13339 base_bg,
13340 );
13341
13342 assert_eq!(result.len(), 5);
13343 assert!(result[0].is_empty());
13344 assert_eq!(result[1].len(), 1);
13345 assert_eq!(result[2].len(), 1);
13346 assert_eq!(result[3].len(), 1);
13347 assert!(result[4].is_empty());
13348
13349 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13350 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13351 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13352 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13353 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13354 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13355 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13356 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13357 }
13358
13359 // Case B: selection ends exactly at the start of row 3, excluding row 3
13360 {
13361 let selection_color = Hsla {
13362 h: 120.0,
13363 s: 0.5,
13364 l: 0.5,
13365 a: 0.5,
13366 };
13367 let player_color = PlayerColor {
13368 cursor: selection_color,
13369 background: selection_color,
13370 selection: selection_color,
13371 };
13372
13373 let selection = SelectionLayout {
13374 head: DisplayPoint::new(DisplayRow(2), 0),
13375 cursor_shape: CursorShape::Bar,
13376 is_newest: true,
13377 is_local: true,
13378 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13379 active_rows: DisplayRow(1)..DisplayRow(3),
13380 user_name: None,
13381 };
13382
13383 let selections = vec![(player_color, vec![selection])];
13384 let result = EditorElement::bg_segments_per_row(
13385 DisplayRow(0)..DisplayRow(4),
13386 &selections,
13387 &[],
13388 base_bg,
13389 );
13390
13391 assert_eq!(result.len(), 4);
13392 assert!(result[0].is_empty());
13393 assert_eq!(result[1].len(), 1);
13394 assert_eq!(result[2].len(), 1);
13395 assert!(result[3].is_empty());
13396
13397 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13398 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13399 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13400 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13401 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13402 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13403 }
13404 }
13405
13406 #[cfg(test)]
13407 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13408 TextRun {
13409 len,
13410 color,
13411 ..Default::default()
13412 }
13413 }
13414
13415 #[gpui::test]
13416 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13417 init_test(cx, |_| {});
13418
13419 let dx = |start: u32, end: u32| {
13420 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13421 };
13422
13423 let text_color = Hsla {
13424 h: 210.0,
13425 s: 0.1,
13426 l: 0.4,
13427 a: 1.0,
13428 };
13429 let bg_1 = Hsla {
13430 h: 30.0,
13431 s: 0.6,
13432 l: 0.8,
13433 a: 1.0,
13434 };
13435 let bg_2 = Hsla {
13436 h: 200.0,
13437 s: 0.6,
13438 l: 0.2,
13439 a: 1.0,
13440 };
13441 let min_contrast = 45.0;
13442 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13443 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13444
13445 // Case A: single run; disjoint segments inside the run
13446 {
13447 let runs = vec![generate_test_run(20, text_color)];
13448 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13449 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13450 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13451 assert_eq!(
13452 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13453 vec![5, 5, 2, 4, 4]
13454 );
13455 assert_eq!(out[0].color, text_color);
13456 assert_eq!(out[1].color, adjusted_bg1);
13457 assert_eq!(out[2].color, text_color);
13458 assert_eq!(out[3].color, adjusted_bg2);
13459 assert_eq!(out[4].color, text_color);
13460 }
13461
13462 // Case B: multiple runs; segment extends to end of line (u32::MAX)
13463 {
13464 let runs = vec![
13465 generate_test_run(8, text_color),
13466 generate_test_run(7, text_color),
13467 ];
13468 let segs = vec![(dx(6, u32::MAX), bg_1)];
13469 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13470 // Expected slices across runs: [0,6) [6,8) | [0,7)
13471 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13472 assert_eq!(out[0].color, text_color);
13473 assert_eq!(out[1].color, adjusted_bg1);
13474 assert_eq!(out[2].color, adjusted_bg1);
13475 }
13476
13477 // Case C: multi-byte characters
13478 {
13479 // for text: "Hello π δΈη!"
13480 let runs = vec![
13481 generate_test_run(5, text_color), // "Hello"
13482 generate_test_run(6, text_color), // " π "
13483 generate_test_run(6, text_color), // "δΈη"
13484 generate_test_run(1, text_color), // "!"
13485 ];
13486 // selecting "π δΈ"
13487 let segs = vec![(dx(6, 14), bg_1)];
13488 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13489 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
13490 assert_eq!(
13491 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13492 vec![5, 1, 5, 3, 3, 1]
13493 );
13494 assert_eq!(out[0].color, text_color); // "Hello"
13495 assert_eq!(out[2].color, adjusted_bg1); // "π "
13496 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
13497 assert_eq!(out[4].color, text_color); // "η"
13498 assert_eq!(out[5].color, text_color); // "!"
13499 }
13500
13501 // Case D: split multiple consecutive text runs with segments
13502 {
13503 let segs = vec![
13504 (dx(2, 4), bg_1), // selecting "cd"
13505 (dx(4, 8), bg_2), // selecting "efgh"
13506 (dx(9, 11), bg_1), // selecting "jk"
13507 (dx(12, 16), bg_2), // selecting "mnop"
13508 (dx(18, 19), bg_1), // selecting "s"
13509 ];
13510
13511 // for text: "abcdef"
13512 let runs = vec![
13513 generate_test_run(2, text_color), // ab
13514 generate_test_run(4, text_color), // cdef
13515 ];
13516 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13517 // new splits "ab", "cd", "ef"
13518 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13519 assert_eq!(out[0].color, text_color);
13520 assert_eq!(out[1].color, adjusted_bg1);
13521 assert_eq!(out[2].color, adjusted_bg2);
13522
13523 // for text: "ghijklmn"
13524 let runs = vec![
13525 generate_test_run(3, text_color), // ghi
13526 generate_test_run(2, text_color), // jk
13527 generate_test_run(3, text_color), // lmn
13528 ];
13529 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13530 // new splits "gh", "i", "jk", "l", "mn"
13531 assert_eq!(
13532 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13533 vec![2, 1, 2, 1, 2]
13534 );
13535 assert_eq!(out[0].color, adjusted_bg2);
13536 assert_eq!(out[1].color, text_color);
13537 assert_eq!(out[2].color, adjusted_bg1);
13538 assert_eq!(out[3].color, text_color);
13539 assert_eq!(out[4].color, adjusted_bg2);
13540
13541 // for text: "opqrs"
13542 let runs = vec![
13543 generate_test_run(1, text_color), // o
13544 generate_test_run(4, text_color), // pqrs
13545 ];
13546 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13547 // new splits "o", "p", "qr", "s"
13548 assert_eq!(
13549 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13550 vec![1, 1, 2, 1]
13551 );
13552 assert_eq!(out[0].color, adjusted_bg2);
13553 assert_eq!(out[1].color, adjusted_bg2);
13554 assert_eq!(out[2].color, text_color);
13555 assert_eq!(out[3].color, adjusted_bg1);
13556 }
13557 }
13558
13559 #[test]
13560 fn test_spacer_pattern_period() {
13561 // line height is smaller than target height, so we just return half the line height
13562 assert_eq!(EditorElement::spacer_pattern_period(10.0, 20.0), 5.0);
13563
13564 // line height is exactly half the target height, perfect match
13565 assert_eq!(EditorElement::spacer_pattern_period(20.0, 10.0), 10.0);
13566
13567 // line height is close to half the target height
13568 assert_eq!(EditorElement::spacer_pattern_period(20.0, 9.0), 10.0);
13569
13570 // line height is close to 1/4 the target height
13571 assert_eq!(EditorElement::spacer_pattern_period(20.0, 4.8), 5.0);
13572 }
13573
13574 #[gpui::test(iterations = 100)]
13575 fn test_random_spacer_pattern_period(mut rng: StdRng) {
13576 let line_height = rng.next_u32() as f32;
13577 let target_height = rng.next_u32() as f32;
13578
13579 let result = EditorElement::spacer_pattern_period(line_height, target_height);
13580
13581 let k = line_height / result;
13582 assert!(k - k.round() < 0.0000001); // approximately integer
13583 assert!((k.round() as u32).is_multiple_of(2));
13584 }
13585
13586 #[test]
13587 fn test_calculate_wrap_width() {
13588 let editor_width = px(800.0);
13589 let em_width = px(8.0);
13590
13591 assert_eq!(
13592 calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13593 None,
13594 );
13595
13596 assert_eq!(
13597 calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13598 Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13599 );
13600
13601 assert_eq!(
13602 calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13603 Some(px(800.0)),
13604 );
13605
13606 assert_eq!(
13607 calculate_wrap_width(SoftWrap::Column(72), editor_width, em_width),
13608 Some(px((72.0 * 8.0_f32).ceil())),
13609 );
13610
13611 assert_eq!(
13612 calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13613 Some(px((72.0 * 8.0_f32).ceil())),
13614 );
13615 assert_eq!(
13616 calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13617 Some(px(400.0)),
13618 );
13619 }
13620}