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