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