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