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