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