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