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