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