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 scroll_beyond_last_line = self.editor.read(cx).scroll_beyond_last_line(cx);
9776 let max_scroll_top = match scroll_beyond_last_line {
9777 ScrollBeyondLastLine::OnePage => max_row,
9778 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
9779 ScrollBeyondLastLine::VerticalScrollMargin => {
9780 let settings = EditorSettings::get_global(cx);
9781 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
9782 .max(0.)
9783 }
9784 };
9785
9786 let (
9787 autoscroll_request,
9788 autoscroll_containing_element,
9789 needs_horizontal_autoscroll,
9790 ) = self.editor.update(cx, |editor, cx| {
9791 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
9792
9793 let autoscroll_containing_element =
9794 autoscroll_request.is_some() || editor.has_pending_selection();
9795
9796 let (needs_horizontal_autoscroll, was_scrolled) = editor
9797 .autoscroll_vertically(
9798 bounds,
9799 line_height,
9800 max_scroll_top,
9801 autoscroll_request,
9802 window,
9803 cx,
9804 );
9805 if was_scrolled.0 {
9806 snapshot = editor.snapshot(window, cx);
9807 }
9808 (
9809 autoscroll_request,
9810 autoscroll_containing_element,
9811 needs_horizontal_autoscroll,
9812 )
9813 });
9814
9815 let mut scroll_position = snapshot.scroll_position();
9816 // The scroll position is a fractional point, the whole number of which represents
9817 // the top of the window in terms of display rows.
9818 // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
9819 // but we don't modify scroll_position itself since the parent handles positioning.
9820 let max_row = snapshot.max_point().row();
9821 let start_row = cmp::min(
9822 DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
9823 max_row,
9824 );
9825 let end_row = cmp::min(
9826 (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
9827 as u32,
9828 max_row.next_row().0,
9829 );
9830 let end_row = DisplayRow(end_row);
9831
9832 let row_infos = snapshot // note we only get the visual range
9833 .row_infos(start_row)
9834 .take((start_row..end_row).len())
9835 .collect::<Vec<RowInfo>>();
9836 let is_row_soft_wrapped = |row: usize| {
9837 row_infos
9838 .get(row)
9839 .is_none_or(|info| info.buffer_row.is_none())
9840 };
9841
9842 let start_anchor = if start_row == Default::default() {
9843 Anchor::min()
9844 } else {
9845 snapshot.buffer_snapshot().anchor_before(
9846 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
9847 )
9848 };
9849 let end_anchor = if end_row > max_row {
9850 Anchor::max()
9851 } else {
9852 snapshot.buffer_snapshot().anchor_before(
9853 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
9854 )
9855 };
9856
9857 let mut highlighted_rows = self
9858 .editor
9859 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
9860
9861 let is_light = cx.theme().appearance().is_light();
9862
9863 let mut highlighted_ranges = self
9864 .editor_with_selections(cx)
9865 .map(|editor| {
9866 if editor == self.editor {
9867 editor.read(cx).background_highlights_in_range(
9868 start_anchor..end_anchor,
9869 &snapshot.display_snapshot,
9870 cx.theme(),
9871 )
9872 } else {
9873 editor.update(cx, |editor, cx| {
9874 let snapshot = editor.snapshot(window, cx);
9875 let start_anchor = if start_row == Default::default() {
9876 Anchor::min()
9877 } else {
9878 snapshot.buffer_snapshot().anchor_before(
9879 DisplayPoint::new(start_row, 0)
9880 .to_offset(&snapshot, Bias::Left),
9881 )
9882 };
9883 let end_anchor = if end_row > max_row {
9884 Anchor::max()
9885 } else {
9886 snapshot.buffer_snapshot().anchor_before(
9887 DisplayPoint::new(end_row, 0)
9888 .to_offset(&snapshot, Bias::Right),
9889 )
9890 };
9891
9892 editor.background_highlights_in_range(
9893 start_anchor..end_anchor,
9894 &snapshot.display_snapshot,
9895 cx.theme(),
9896 )
9897 })
9898 }
9899 })
9900 .unwrap_or_default();
9901
9902 for (ix, row_info) in row_infos.iter().enumerate() {
9903 let Some(diff_status) = row_info.diff_status else {
9904 continue;
9905 };
9906
9907 let background_color = match diff_status.kind {
9908 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
9909 DiffHunkStatusKind::Deleted => {
9910 cx.theme().colors().version_control_deleted
9911 }
9912 DiffHunkStatusKind::Modified => {
9913 debug_panic!("modified diff status for row info");
9914 continue;
9915 }
9916 };
9917
9918 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
9919
9920 let hollow_highlight = LineHighlight {
9921 background: (background_color.opacity(if is_light {
9922 0.08
9923 } else {
9924 0.06
9925 }))
9926 .into(),
9927 border: Some(if is_light {
9928 background_color.opacity(0.48)
9929 } else {
9930 background_color.opacity(0.36)
9931 }),
9932 include_gutter: true,
9933 type_id: None,
9934 };
9935
9936 let filled_highlight = LineHighlight {
9937 background: solid_background(background_color.opacity(hunk_opacity)),
9938 border: None,
9939 include_gutter: true,
9940 type_id: None,
9941 };
9942
9943 let background = if Self::diff_hunk_hollow(diff_status, cx) {
9944 hollow_highlight
9945 } else {
9946 filled_highlight
9947 };
9948
9949 let base_display_point =
9950 DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
9951
9952 highlighted_rows
9953 .entry(base_display_point.row())
9954 .or_insert(background);
9955 }
9956
9957 // Add diff review drag selection highlight to text area
9958 if let Some(drag_state) = &self.editor.read(cx).diff_review_drag_state {
9959 let range = drag_state.row_range(&snapshot.display_snapshot);
9960 let start_row = range.start().0;
9961 let end_row = range.end().0;
9962 let drag_highlight_color =
9963 cx.theme().colors().editor_active_line_background;
9964 let drag_highlight = LineHighlight {
9965 background: solid_background(drag_highlight_color),
9966 border: Some(cx.theme().colors().border_focused),
9967 include_gutter: true,
9968 type_id: None,
9969 };
9970 for row_num in start_row..=end_row {
9971 highlighted_rows
9972 .entry(DisplayRow(row_num))
9973 .or_insert(drag_highlight);
9974 }
9975 }
9976
9977 let highlighted_gutter_ranges =
9978 self.editor.read(cx).gutter_highlights_in_range(
9979 start_anchor..end_anchor,
9980 &snapshot.display_snapshot,
9981 cx,
9982 );
9983
9984 let document_colors = self
9985 .editor
9986 .read(cx)
9987 .colors
9988 .as_ref()
9989 .map(|colors| colors.editor_display_highlights(&snapshot));
9990 let redacted_ranges = self.editor.read(cx).redacted_ranges(
9991 start_anchor..end_anchor,
9992 &snapshot.display_snapshot,
9993 cx,
9994 );
9995
9996 let (local_selections, selected_buffer_ids, latest_selection_anchors): (
9997 Vec<Selection<Point>>,
9998 Vec<BufferId>,
9999 HashMap<BufferId, Anchor>,
10000 ) = self
10001 .editor_with_selections(cx)
10002 .map(|editor| {
10003 editor.update(cx, |editor, cx| {
10004 let all_selections =
10005 editor.selections.all::<Point>(&snapshot.display_snapshot);
10006 let all_anchor_selections =
10007 editor.selections.all_anchors(&snapshot.display_snapshot);
10008 let selected_buffer_ids =
10009 if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
10010 Vec::new()
10011 } else {
10012 let mut selected_buffer_ids =
10013 Vec::with_capacity(all_selections.len());
10014
10015 for selection in all_selections {
10016 for buffer_id in snapshot
10017 .buffer_snapshot()
10018 .buffer_ids_for_range(selection.range())
10019 {
10020 if selected_buffer_ids.last() != Some(&buffer_id) {
10021 selected_buffer_ids.push(buffer_id);
10022 }
10023 }
10024 }
10025
10026 selected_buffer_ids
10027 };
10028
10029 let mut selections = editor.selections.disjoint_in_range(
10030 start_anchor..end_anchor,
10031 &snapshot.display_snapshot,
10032 );
10033 selections
10034 .extend(editor.selections.pending(&snapshot.display_snapshot));
10035
10036 let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
10037 HashMap::default();
10038 for selection in all_anchor_selections.iter() {
10039 let head = selection.head();
10040 if let Some(buffer_id) = head.text_anchor.buffer_id {
10041 anchors_by_buffer
10042 .entry(buffer_id)
10043 .and_modify(|(latest_id, latest_anchor)| {
10044 if selection.id > *latest_id {
10045 *latest_id = selection.id;
10046 *latest_anchor = head;
10047 }
10048 })
10049 .or_insert((selection.id, head));
10050 }
10051 }
10052 let latest_selection_anchors = anchors_by_buffer
10053 .into_iter()
10054 .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
10055 .collect();
10056
10057 (selections, selected_buffer_ids, latest_selection_anchors)
10058 })
10059 })
10060 .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
10061
10062 let (selections, mut active_rows, newest_selection_head) = self
10063 .layout_selections(
10064 start_anchor,
10065 end_anchor,
10066 &local_selections,
10067 &snapshot,
10068 start_row,
10069 end_row,
10070 window,
10071 cx,
10072 );
10073
10074 // relative rows are based on newest selection, even outside the visible area
10075 let current_selection_head = self.editor.update(cx, |editor, cx| {
10076 (editor.selections.count() != 0).then(|| {
10077 let newest = editor
10078 .selections
10079 .newest::<Point>(&editor.display_snapshot(cx));
10080
10081 SelectionLayout::new(
10082 newest,
10083 editor.selections.line_mode(),
10084 editor.cursor_offset_on_selection,
10085 editor.cursor_shape,
10086 &snapshot,
10087 true,
10088 true,
10089 None,
10090 )
10091 .head
10092 .row()
10093 })
10094 });
10095
10096 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
10097 editor.active_breakpoints(start_row..end_row, window, cx)
10098 });
10099 for (display_row, (_, bp, state)) in &breakpoint_rows {
10100 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
10101 active_rows.entry(*display_row).or_default().breakpoint = true;
10102 }
10103 }
10104
10105 let line_numbers = self.layout_line_numbers(
10106 Some(&gutter_hitbox),
10107 gutter_dimensions,
10108 line_height,
10109 scroll_position,
10110 start_row..end_row,
10111 &row_infos,
10112 &active_rows,
10113 current_selection_head,
10114 &snapshot,
10115 window,
10116 cx,
10117 );
10118
10119 // We add the gutter breakpoint indicator to breakpoint_rows after painting
10120 // line numbers so we don't paint a line number debug accent color if a user
10121 // has their mouse over that line when a breakpoint isn't there
10122 self.editor.update(cx, |editor, _| {
10123 if let Some(phantom_breakpoint) = &mut editor
10124 .gutter_breakpoint_indicator
10125 .0
10126 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
10127 {
10128 // Is there a non-phantom breakpoint on this line?
10129 phantom_breakpoint.collides_with_existing_breakpoint = true;
10130 breakpoint_rows
10131 .entry(phantom_breakpoint.display_row)
10132 .or_insert_with(|| {
10133 let position = snapshot.display_point_to_anchor(
10134 DisplayPoint::new(phantom_breakpoint.display_row, 0),
10135 Bias::Right,
10136 );
10137 let breakpoint = Breakpoint::new_standard();
10138 phantom_breakpoint.collides_with_existing_breakpoint = false;
10139 (position, breakpoint, None)
10140 });
10141 }
10142 });
10143
10144 let mut expand_toggles =
10145 window.with_element_namespace("expand_toggles", |window| {
10146 self.layout_expand_toggles(
10147 &gutter_hitbox,
10148 gutter_dimensions,
10149 em_width,
10150 line_height,
10151 scroll_position,
10152 &row_infos,
10153 window,
10154 cx,
10155 )
10156 });
10157
10158 let mut crease_toggles =
10159 window.with_element_namespace("crease_toggles", |window| {
10160 self.layout_crease_toggles(
10161 start_row..end_row,
10162 &row_infos,
10163 &active_rows,
10164 &snapshot,
10165 window,
10166 cx,
10167 )
10168 });
10169 let crease_trailers =
10170 window.with_element_namespace("crease_trailers", |window| {
10171 self.layout_crease_trailers(
10172 row_infos.iter().cloned(),
10173 &snapshot,
10174 window,
10175 cx,
10176 )
10177 });
10178
10179 let display_hunks = self.layout_gutter_diff_hunks(
10180 line_height,
10181 &gutter_hitbox,
10182 start_row..end_row,
10183 &snapshot,
10184 window,
10185 cx,
10186 );
10187
10188 Self::layout_word_diff_highlights(
10189 &display_hunks,
10190 &row_infos,
10191 start_row,
10192 &snapshot,
10193 &mut highlighted_ranges,
10194 cx,
10195 );
10196
10197 let merged_highlighted_ranges =
10198 if let Some((_, colors)) = document_colors.as_ref() {
10199 &highlighted_ranges
10200 .clone()
10201 .into_iter()
10202 .chain(colors.clone())
10203 .collect()
10204 } else {
10205 &highlighted_ranges
10206 };
10207 let bg_segments_per_row = Self::bg_segments_per_row(
10208 start_row..end_row,
10209 &selections,
10210 &merged_highlighted_ranges,
10211 self.style.background,
10212 );
10213
10214 let mut line_layouts = Self::layout_lines(
10215 start_row..end_row,
10216 &snapshot,
10217 &self.style,
10218 editor_width,
10219 is_row_soft_wrapped,
10220 &bg_segments_per_row,
10221 window,
10222 cx,
10223 );
10224 let new_renderer_widths = (!is_minimap).then(|| {
10225 line_layouts
10226 .iter()
10227 .flat_map(|layout| &layout.fragments)
10228 .filter_map(|fragment| {
10229 if let LineFragment::Element { id, size, .. } = fragment {
10230 Some((*id, size.width))
10231 } else {
10232 None
10233 }
10234 })
10235 });
10236 let renderer_widths_changed = request_layout.has_remaining_prepaint_depth()
10237 && new_renderer_widths.is_some_and(|new_renderer_widths| {
10238 self.editor.update(cx, |editor, cx| {
10239 editor.update_renderer_widths(new_renderer_widths, cx)
10240 })
10241 });
10242 if renderer_widths_changed {
10243 return self.prepaint(
10244 None,
10245 _inspector_id,
10246 bounds,
10247 request_layout,
10248 window,
10249 cx,
10250 );
10251 }
10252
10253 let longest_line_blame_width = self
10254 .editor
10255 .update(cx, |editor, cx| {
10256 if !editor.show_git_blame_inline {
10257 return None;
10258 }
10259 let blame = editor.blame.as_ref()?;
10260 let (_, blame_entry) = blame
10261 .update(cx, |blame, cx| {
10262 let row_infos =
10263 snapshot.row_infos(snapshot.longest_row()).next()?;
10264 blame.blame_for_rows(&[row_infos], cx).next()
10265 })
10266 .flatten()?;
10267 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
10268 let inline_blame_padding =
10269 ProjectSettings::get_global(cx).git.inline_blame.padding as f32
10270 * em_advance;
10271 Some(
10272 element
10273 .layout_as_root(AvailableSpace::min_size(), window, cx)
10274 .width
10275 + inline_blame_padding,
10276 )
10277 })
10278 .unwrap_or(Pixels::ZERO);
10279
10280 let longest_line_width = layout_line(
10281 snapshot.longest_row(),
10282 &snapshot,
10283 style,
10284 editor_width,
10285 is_row_soft_wrapped,
10286 window,
10287 cx,
10288 )
10289 .width;
10290
10291 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
10292 text_hitbox.bounds,
10293 glyph_grid_cell,
10294 size(
10295 longest_line_width,
10296 Pixels::from(max_row.as_f64() * f64::from(line_height)),
10297 ),
10298 longest_line_blame_width,
10299 EditorSettings::get_global(cx),
10300 scroll_beyond_last_line,
10301 );
10302
10303 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
10304
10305 let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
10306 snapshot.sticky_header_excerpt(scroll_position.y)
10307 } else {
10308 None
10309 };
10310 let sticky_header_excerpt_id =
10311 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
10312
10313 let buffer = snapshot.buffer_snapshot();
10314 let start_buffer_row = MultiBufferRow(start_anchor.to_point(&buffer).row);
10315 let end_buffer_row = MultiBufferRow(end_anchor.to_point(&buffer).row);
10316
10317 let preliminary_scroll_pixel_position = point(
10318 scroll_position.x * f64::from(em_layout_width),
10319 scroll_position.y * f64::from(line_height),
10320 );
10321 let indent_guides = self.layout_indent_guides(
10322 content_origin,
10323 text_hitbox.origin,
10324 start_buffer_row..end_buffer_row,
10325 preliminary_scroll_pixel_position,
10326 line_height,
10327 &snapshot,
10328 window,
10329 cx,
10330 );
10331 let indent_guides_for_spacers = indent_guides.clone();
10332
10333 let blocks = (!is_minimap)
10334 .then(|| {
10335 window.with_element_namespace("blocks", |window| {
10336 self.render_blocks(
10337 start_row..end_row,
10338 &snapshot,
10339 &hitbox,
10340 &text_hitbox,
10341 editor_width,
10342 &mut scroll_width,
10343 &editor_margins,
10344 em_width,
10345 gutter_dimensions.full_width(),
10346 line_height,
10347 &mut line_layouts,
10348 &local_selections,
10349 &selected_buffer_ids,
10350 &latest_selection_anchors,
10351 is_row_soft_wrapped,
10352 sticky_header_excerpt_id,
10353 &indent_guides_for_spacers,
10354 window,
10355 cx,
10356 )
10357 })
10358 })
10359 .unwrap_or_default();
10360 let RenderBlocksOutput {
10361 non_spacer_blocks: mut blocks,
10362 mut spacer_blocks,
10363 row_block_types,
10364 resized_blocks,
10365 } = blocks;
10366 if let Some(resized_blocks) = resized_blocks {
10367 if request_layout.has_remaining_prepaint_depth() {
10368 self.editor.update(cx, |editor, cx| {
10369 editor.resize_blocks(
10370 resized_blocks,
10371 autoscroll_request.map(|(autoscroll, _)| autoscroll),
10372 cx,
10373 )
10374 });
10375 return self.prepaint(
10376 None,
10377 _inspector_id,
10378 bounds,
10379 request_layout,
10380 window,
10381 cx,
10382 );
10383 } else {
10384 debug_panic!(
10385 "dropping block resize because prepaint depth \
10386 limit was reached"
10387 );
10388 }
10389 }
10390
10391 let sticky_buffer_header = if self.should_show_buffer_headers() {
10392 sticky_header_excerpt.map(|sticky_header_excerpt| {
10393 window.with_element_namespace("blocks", |window| {
10394 self.layout_sticky_buffer_header(
10395 sticky_header_excerpt,
10396 scroll_position,
10397 line_height,
10398 right_margin,
10399 &snapshot,
10400 &hitbox,
10401 &selected_buffer_ids,
10402 &blocks,
10403 &latest_selection_anchors,
10404 window,
10405 cx,
10406 )
10407 })
10408 })
10409 } else {
10410 None
10411 };
10412
10413 let scroll_max: gpui::Point<ScrollPixelOffset> = point(
10414 ScrollPixelOffset::from(
10415 ((scroll_width - editor_width) / em_layout_width).max(0.0),
10416 ),
10417 max_scroll_top,
10418 );
10419
10420 self.editor.update(cx, |editor, cx| {
10421 if editor.scroll_manager.clamp_scroll_left(scroll_max.x, cx) {
10422 scroll_position.x = scroll_max.x.min(scroll_position.x);
10423 }
10424
10425 if needs_horizontal_autoscroll.0
10426 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
10427 start_row,
10428 editor_width,
10429 scroll_width,
10430 em_advance,
10431 &line_layouts,
10432 autoscroll_request,
10433 window,
10434 cx,
10435 )
10436 {
10437 scroll_position = new_scroll_position;
10438 }
10439 });
10440
10441 let scroll_pixel_position = point(
10442 scroll_position.x * f64::from(em_layout_width),
10443 scroll_position.y * f64::from(line_height),
10444 );
10445 let sticky_headers = if !is_minimap
10446 && is_singleton
10447 && EditorSettings::get_global(cx).sticky_scroll.enabled
10448 {
10449 let relative = self.editor.read(cx).relative_line_numbers(cx);
10450 self.layout_sticky_headers(
10451 &snapshot,
10452 editor_width,
10453 is_row_soft_wrapped,
10454 line_height,
10455 scroll_pixel_position,
10456 content_origin,
10457 &gutter_dimensions,
10458 &gutter_hitbox,
10459 &text_hitbox,
10460 relative,
10461 current_selection_head,
10462 window,
10463 cx,
10464 )
10465 } else {
10466 None
10467 };
10468 self.editor.update(cx, |editor, _| {
10469 editor.scroll_manager.set_sticky_header_line_count(
10470 sticky_headers.as_ref().map_or(0, |h| h.lines.len()),
10471 );
10472 });
10473 let indent_guides =
10474 if scroll_pixel_position != preliminary_scroll_pixel_position {
10475 self.layout_indent_guides(
10476 content_origin,
10477 text_hitbox.origin,
10478 start_buffer_row..end_buffer_row,
10479 scroll_pixel_position,
10480 line_height,
10481 &snapshot,
10482 window,
10483 cx,
10484 )
10485 } else {
10486 indent_guides
10487 };
10488
10489 let crease_trailers =
10490 window.with_element_namespace("crease_trailers", |window| {
10491 self.prepaint_crease_trailers(
10492 crease_trailers,
10493 &line_layouts,
10494 line_height,
10495 content_origin,
10496 scroll_pixel_position,
10497 em_width,
10498 window,
10499 cx,
10500 )
10501 });
10502
10503 let (edit_prediction_popover, edit_prediction_popover_origin) = self
10504 .editor
10505 .update(cx, |editor, cx| {
10506 editor.render_edit_prediction_popover(
10507 &text_hitbox.bounds,
10508 content_origin,
10509 right_margin,
10510 &snapshot,
10511 start_row..end_row,
10512 scroll_position.y,
10513 scroll_position.y + height_in_lines,
10514 &line_layouts,
10515 line_height,
10516 scroll_position,
10517 scroll_pixel_position,
10518 newest_selection_head,
10519 editor_width,
10520 style,
10521 window,
10522 cx,
10523 )
10524 })
10525 .unzip();
10526
10527 let mut inline_diagnostics = self.layout_inline_diagnostics(
10528 &line_layouts,
10529 &crease_trailers,
10530 &row_block_types,
10531 content_origin,
10532 scroll_position,
10533 scroll_pixel_position,
10534 edit_prediction_popover_origin,
10535 start_row,
10536 end_row,
10537 line_height,
10538 em_width,
10539 style,
10540 window,
10541 cx,
10542 );
10543
10544 let mut inline_blame_layout = None;
10545 let mut inline_code_actions = None;
10546 if let Some(newest_selection_head) = newest_selection_head {
10547 let display_row = newest_selection_head.row();
10548 if (start_row..end_row).contains(&display_row)
10549 && !row_block_types.contains_key(&display_row)
10550 {
10551 inline_code_actions = self.layout_inline_code_actions(
10552 newest_selection_head,
10553 content_origin,
10554 scroll_position,
10555 scroll_pixel_position,
10556 line_height,
10557 &snapshot,
10558 window,
10559 cx,
10560 );
10561
10562 let line_ix = display_row.minus(start_row) as usize;
10563 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10564 row_infos.get(line_ix),
10565 line_layouts.get(line_ix),
10566 crease_trailers.get(line_ix),
10567 ) {
10568 let crease_trailer_layout = crease_trailer.as_ref();
10569 if let Some(layout) = self.layout_inline_blame(
10570 display_row,
10571 row_info,
10572 line_layout,
10573 crease_trailer_layout,
10574 em_width,
10575 content_origin,
10576 scroll_position,
10577 scroll_pixel_position,
10578 line_height,
10579 window,
10580 cx,
10581 ) {
10582 inline_blame_layout = Some(layout);
10583 // Blame overrides inline diagnostics
10584 inline_diagnostics.remove(&display_row);
10585 }
10586 } else {
10587 log::error!(
10588 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10589 line_layouts.len(): {}, \
10590 crease_trailers.len(): {}",
10591 line_ix,
10592 row_infos.len(),
10593 line_layouts.len(),
10594 crease_trailers.len(),
10595 );
10596 }
10597 }
10598 }
10599
10600 let blamed_display_rows = self.layout_blame_entries(
10601 &row_infos,
10602 em_width,
10603 scroll_position,
10604 line_height,
10605 &gutter_hitbox,
10606 gutter_dimensions.git_blame_entries_width,
10607 window,
10608 cx,
10609 );
10610
10611 let line_elements = self.prepaint_lines(
10612 start_row,
10613 &mut line_layouts,
10614 line_height,
10615 scroll_position,
10616 scroll_pixel_position,
10617 content_origin,
10618 window,
10619 cx,
10620 );
10621
10622 window.with_element_namespace("blocks", |window| {
10623 self.layout_blocks(
10624 &mut blocks,
10625 &hitbox,
10626 &gutter_hitbox,
10627 line_height,
10628 scroll_position,
10629 scroll_pixel_position,
10630 &editor_margins,
10631 window,
10632 cx,
10633 );
10634 self.layout_blocks(
10635 &mut spacer_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 });
10646
10647 let cursors = self.collect_cursors(&snapshot, cx);
10648 let visible_row_range = start_row..end_row;
10649 let non_visible_cursors = cursors
10650 .iter()
10651 .any(|c| !visible_row_range.contains(&c.0.row()));
10652
10653 let visible_cursors = self.layout_visible_cursors(
10654 &snapshot,
10655 &selections,
10656 &row_block_types,
10657 start_row..end_row,
10658 &line_layouts,
10659 &text_hitbox,
10660 content_origin,
10661 scroll_position,
10662 scroll_pixel_position,
10663 line_height,
10664 em_width,
10665 em_advance,
10666 autoscroll_containing_element,
10667 &redacted_ranges,
10668 window,
10669 cx,
10670 );
10671
10672 let scrollbars_layout = self.layout_scrollbars(
10673 &snapshot,
10674 &scrollbar_layout_information,
10675 content_offset,
10676 scroll_position,
10677 non_visible_cursors,
10678 right_margin,
10679 editor_width,
10680 window,
10681 cx,
10682 );
10683
10684 let gutter_settings = EditorSettings::get_global(cx).gutter;
10685
10686 let context_menu_layout =
10687 if let Some(newest_selection_head) = newest_selection_head {
10688 let newest_selection_point =
10689 newest_selection_head.to_point(&snapshot.display_snapshot);
10690 if (start_row..end_row).contains(&newest_selection_head.row()) {
10691 self.layout_cursor_popovers(
10692 line_height,
10693 &text_hitbox,
10694 content_origin,
10695 right_margin,
10696 start_row,
10697 scroll_pixel_position,
10698 &line_layouts,
10699 newest_selection_head,
10700 newest_selection_point,
10701 style,
10702 window,
10703 cx,
10704 )
10705 } else {
10706 None
10707 }
10708 } else {
10709 None
10710 };
10711
10712 self.layout_gutter_menu(
10713 line_height,
10714 &text_hitbox,
10715 content_origin,
10716 right_margin,
10717 scroll_pixel_position,
10718 gutter_dimensions.width - gutter_dimensions.left_padding,
10719 window,
10720 cx,
10721 );
10722
10723 let test_indicators = if gutter_settings.runnables {
10724 self.layout_run_indicators(
10725 line_height,
10726 start_row..end_row,
10727 &row_infos,
10728 scroll_position,
10729 &gutter_dimensions,
10730 &gutter_hitbox,
10731 &snapshot,
10732 &mut breakpoint_rows,
10733 window,
10734 cx,
10735 )
10736 } else {
10737 Vec::new()
10738 };
10739
10740 let show_breakpoints = snapshot
10741 .show_breakpoints
10742 .unwrap_or(gutter_settings.breakpoints);
10743 let breakpoints = if show_breakpoints {
10744 self.layout_breakpoints(
10745 line_height,
10746 start_row..end_row,
10747 scroll_position,
10748 &gutter_dimensions,
10749 &gutter_hitbox,
10750 &snapshot,
10751 breakpoint_rows,
10752 &row_infos,
10753 window,
10754 cx,
10755 )
10756 } else {
10757 Vec::new()
10758 };
10759
10760 let git_gutter_width = Self::gutter_strip_width(line_height)
10761 + gutter_dimensions
10762 .git_blame_entries_width
10763 .unwrap_or_default();
10764 let available_width = gutter_dimensions.left_padding - git_gutter_width;
10765
10766 let max_line_number_length = self
10767 .editor
10768 .read(cx)
10769 .buffer()
10770 .read(cx)
10771 .snapshot(cx)
10772 .widest_line_number()
10773 .ilog10()
10774 + 1;
10775
10776 let diff_review_button = self
10777 .should_render_diff_review_button(
10778 start_row..end_row,
10779 &row_infos,
10780 &snapshot,
10781 cx,
10782 )
10783 .map(|(display_row, buffer_row)| {
10784 let is_wide = max_line_number_length
10785 >= EditorSettings::get_global(cx).gutter.min_line_number_digits
10786 as u32
10787 && buffer_row.is_some_and(|row| {
10788 (row + 1).ilog10() + 1 == max_line_number_length
10789 })
10790 || gutter_dimensions.right_padding == px(0.);
10791
10792 let button_width = if is_wide {
10793 available_width - px(6.)
10794 } else {
10795 available_width + em_width - px(6.)
10796 };
10797
10798 let button = self.editor.update(cx, |editor, cx| {
10799 editor
10800 .render_diff_review_button(display_row, button_width, cx)
10801 .into_any_element()
10802 });
10803 prepaint_gutter_button(
10804 button,
10805 display_row,
10806 line_height,
10807 &gutter_dimensions,
10808 scroll_position,
10809 &gutter_hitbox,
10810 window,
10811 cx,
10812 )
10813 });
10814
10815 self.layout_signature_help(
10816 &hitbox,
10817 content_origin,
10818 scroll_pixel_position,
10819 newest_selection_head,
10820 start_row,
10821 &line_layouts,
10822 line_height,
10823 em_width,
10824 context_menu_layout,
10825 window,
10826 cx,
10827 );
10828
10829 if !cx.has_active_drag() {
10830 self.layout_hover_popovers(
10831 &snapshot,
10832 &hitbox,
10833 start_row..end_row,
10834 content_origin,
10835 scroll_pixel_position,
10836 &line_layouts,
10837 line_height,
10838 em_width,
10839 context_menu_layout,
10840 window,
10841 cx,
10842 );
10843
10844 self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10845 }
10846
10847 let mouse_context_menu = self.layout_mouse_context_menu(
10848 &snapshot,
10849 start_row..end_row,
10850 content_origin,
10851 window,
10852 cx,
10853 );
10854
10855 window.with_element_namespace("crease_toggles", |window| {
10856 self.prepaint_crease_toggles(
10857 &mut crease_toggles,
10858 line_height,
10859 &gutter_dimensions,
10860 gutter_settings,
10861 scroll_pixel_position,
10862 &gutter_hitbox,
10863 window,
10864 cx,
10865 )
10866 });
10867
10868 window.with_element_namespace("expand_toggles", |window| {
10869 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10870 });
10871
10872 let wrap_guides = self.layout_wrap_guides(
10873 em_advance,
10874 scroll_position,
10875 content_origin,
10876 scrollbars_layout.as_ref(),
10877 vertical_scrollbar_width,
10878 &hitbox,
10879 window,
10880 cx,
10881 );
10882
10883 let minimap = window.with_element_namespace("minimap", |window| {
10884 self.layout_minimap(
10885 &snapshot,
10886 minimap_width,
10887 scroll_position,
10888 &scrollbar_layout_information,
10889 scrollbars_layout.as_ref(),
10890 window,
10891 cx,
10892 )
10893 });
10894
10895 let invisible_symbol_font_size = font_size / 2.;
10896 let whitespace_map = &self
10897 .editor
10898 .read(cx)
10899 .buffer
10900 .read(cx)
10901 .language_settings(cx)
10902 .whitespace_map;
10903
10904 let tab_char = whitespace_map.tab.clone();
10905 let tab_len = tab_char.len();
10906 let tab_invisible = window.text_system().shape_line(
10907 tab_char,
10908 invisible_symbol_font_size,
10909 &[TextRun {
10910 len: tab_len,
10911 font: self.style.text.font(),
10912 color: cx.theme().colors().editor_invisible,
10913 ..Default::default()
10914 }],
10915 None,
10916 );
10917
10918 let space_char = whitespace_map.space.clone();
10919 let space_len = space_char.len();
10920 let space_invisible = window.text_system().shape_line(
10921 space_char,
10922 invisible_symbol_font_size,
10923 &[TextRun {
10924 len: space_len,
10925 font: self.style.text.font(),
10926 color: cx.theme().colors().editor_invisible,
10927 ..Default::default()
10928 }],
10929 None,
10930 );
10931
10932 let mode = snapshot.mode.clone();
10933
10934 let sticky_scroll_header_height = sticky_headers
10935 .as_ref()
10936 .and_then(|headers| headers.lines.last())
10937 .map_or(Pixels::ZERO, |last| last.offset + line_height);
10938
10939 let has_sticky_buffer_header =
10940 sticky_buffer_header.is_some() || sticky_header_excerpt_id.is_some();
10941 let sticky_header_height = if has_sticky_buffer_header {
10942 let full_height = FILE_HEADER_HEIGHT as f32 * line_height;
10943 let display_row = blocks
10944 .iter()
10945 .filter(|block| block.is_buffer_header)
10946 .find_map(|block| {
10947 block.row.filter(|row| row.0 > scroll_position.y as u32)
10948 });
10949 let offset = match display_row {
10950 Some(display_row) => {
10951 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
10952 let offset = (scroll_position.y - max_row as f64).max(0.0);
10953 let slide_up =
10954 Pixels::from(offset * ScrollPixelOffset::from(line_height));
10955
10956 (full_height - slide_up).max(Pixels::ZERO)
10957 }
10958 None => full_height,
10959 };
10960 let header_bottom_padding =
10961 BUFFER_HEADER_PADDING.to_pixels(window.rem_size());
10962 sticky_scroll_header_height + offset - header_bottom_padding
10963 } else {
10964 sticky_scroll_header_height
10965 };
10966
10967 let (diff_hunk_controls, diff_hunk_control_bounds) =
10968 if is_read_only && !self.editor.read(cx).delegate_stage_and_restore {
10969 (vec![], vec![])
10970 } else {
10971 self.layout_diff_hunk_controls(
10972 start_row..end_row,
10973 &row_infos,
10974 &text_hitbox,
10975 current_selection_head,
10976 line_height,
10977 right_margin,
10978 scroll_pixel_position,
10979 sticky_header_height,
10980 &display_hunks,
10981 &highlighted_rows,
10982 self.editor.clone(),
10983 window,
10984 cx,
10985 )
10986 };
10987
10988 let position_map = Rc::new(PositionMap {
10989 size: bounds.size,
10990 visible_row_range,
10991 scroll_position,
10992 scroll_pixel_position,
10993 scroll_max,
10994 line_layouts,
10995 line_height,
10996 em_width,
10997 em_advance,
10998 em_layout_width,
10999 snapshot,
11000 text_align: self.style.text.text_align,
11001 content_width: text_hitbox.size.width,
11002 gutter_hitbox: gutter_hitbox.clone(),
11003 text_hitbox: text_hitbox.clone(),
11004 inline_blame_bounds: inline_blame_layout
11005 .as_ref()
11006 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
11007 display_hunks: display_hunks.clone(),
11008 diff_hunk_control_bounds,
11009 });
11010
11011 self.editor.update(cx, |editor, _| {
11012 editor.last_position_map = Some(position_map.clone())
11013 });
11014
11015 EditorLayout {
11016 mode,
11017 position_map,
11018 visible_display_row_range: start_row..end_row,
11019 wrap_guides,
11020 indent_guides,
11021 hitbox,
11022 gutter_hitbox,
11023 display_hunks,
11024 content_origin,
11025 scrollbars_layout,
11026 minimap,
11027 active_rows,
11028 highlighted_rows,
11029 highlighted_ranges,
11030 highlighted_gutter_ranges,
11031 redacted_ranges,
11032 document_colors,
11033 line_elements,
11034 line_numbers,
11035 blamed_display_rows,
11036 inline_diagnostics,
11037 inline_blame_layout,
11038 inline_code_actions,
11039 blocks,
11040 spacer_blocks,
11041 cursors,
11042 visible_cursors,
11043 selections,
11044 edit_prediction_popover,
11045 diff_hunk_controls,
11046 mouse_context_menu,
11047 test_indicators,
11048 breakpoints,
11049 diff_review_button,
11050 crease_toggles,
11051 crease_trailers,
11052 tab_invisible,
11053 space_invisible,
11054 sticky_buffer_header,
11055 sticky_headers,
11056 expand_toggles,
11057 text_align: self.style.text.text_align,
11058 content_width: text_hitbox.size.width,
11059 }
11060 })
11061 })
11062 })
11063 }
11064
11065 fn paint(
11066 &mut self,
11067 _: Option<&GlobalElementId>,
11068 _inspector_id: Option<&gpui::InspectorElementId>,
11069 bounds: Bounds<gpui::Pixels>,
11070 _: &mut Self::RequestLayoutState,
11071 layout: &mut Self::PrepaintState,
11072 window: &mut Window,
11073 cx: &mut App,
11074 ) {
11075 if !layout.mode.is_minimap() {
11076 let focus_handle = self.editor.focus_handle(cx);
11077 let key_context = self
11078 .editor
11079 .update(cx, |editor, cx| editor.key_context(window, cx));
11080
11081 window.set_key_context(key_context);
11082 window.handle_input(
11083 &focus_handle,
11084 ElementInputHandler::new(bounds, self.editor.clone()),
11085 cx,
11086 );
11087 self.register_actions(window, cx);
11088 self.register_key_listeners(window, cx, layout);
11089 }
11090
11091 let text_style = TextStyleRefinement {
11092 font_size: Some(self.style.text.font_size),
11093 line_height: Some(self.style.text.line_height),
11094 ..Default::default()
11095 };
11096 let rem_size = self.rem_size(cx);
11097 window.with_rem_size(rem_size, |window| {
11098 window.with_text_style(Some(text_style), |window| {
11099 window.with_content_mask(Some(ContentMask { bounds }), |window| {
11100 self.paint_mouse_listeners(layout, window, cx);
11101 self.paint_background(layout, window, cx);
11102
11103 self.paint_indent_guides(layout, window, cx);
11104
11105 if layout.gutter_hitbox.size.width > Pixels::ZERO {
11106 self.paint_blamed_display_rows(layout, window, cx);
11107 self.paint_line_numbers(layout, window, cx);
11108 }
11109
11110 self.paint_text(layout, window, cx);
11111
11112 if !layout.spacer_blocks.is_empty() {
11113 window.with_element_namespace("blocks", |window| {
11114 self.paint_spacer_blocks(layout, window, cx);
11115 });
11116 }
11117
11118 if layout.gutter_hitbox.size.width > Pixels::ZERO {
11119 self.paint_gutter_highlights(layout, window, cx);
11120 self.paint_gutter_indicators(layout, window, cx);
11121 }
11122
11123 if !layout.blocks.is_empty() {
11124 window.with_element_namespace("blocks", |window| {
11125 self.paint_non_spacer_blocks(layout, window, cx);
11126 });
11127 }
11128
11129 window.with_element_namespace("blocks", |window| {
11130 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
11131 sticky_header.paint(window, cx)
11132 }
11133 });
11134
11135 self.paint_sticky_headers(layout, window, cx);
11136 self.paint_minimap(layout, window, cx);
11137 self.paint_scrollbars(layout, window, cx);
11138 self.paint_edit_prediction_popover(layout, window, cx);
11139 self.paint_mouse_context_menu(layout, window, cx);
11140 });
11141 })
11142 })
11143 }
11144}
11145
11146pub(super) fn gutter_bounds(
11147 editor_bounds: Bounds<Pixels>,
11148 gutter_dimensions: GutterDimensions,
11149) -> Bounds<Pixels> {
11150 Bounds {
11151 origin: editor_bounds.origin,
11152 size: size(gutter_dimensions.width, editor_bounds.size.height),
11153 }
11154}
11155
11156#[derive(Clone, Copy)]
11157struct ContextMenuLayout {
11158 y_flipped: bool,
11159 bounds: Bounds<Pixels>,
11160}
11161
11162/// Holds information required for layouting the editor scrollbars.
11163struct ScrollbarLayoutInformation {
11164 /// The bounds of the editor area (excluding the content offset).
11165 editor_bounds: Bounds<Pixels>,
11166 /// The available range to scroll within the document.
11167 scroll_range: Size<Pixels>,
11168 /// The space available for one glyph in the editor.
11169 glyph_grid_cell: Size<Pixels>,
11170}
11171
11172impl ScrollbarLayoutInformation {
11173 pub fn new(
11174 editor_bounds: Bounds<Pixels>,
11175 glyph_grid_cell: Size<Pixels>,
11176 document_size: Size<Pixels>,
11177 longest_line_blame_width: Pixels,
11178 settings: &EditorSettings,
11179 scroll_beyond_last_line: ScrollBeyondLastLine,
11180 ) -> Self {
11181 let vertical_overscroll = match scroll_beyond_last_line {
11182 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
11183 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
11184 ScrollBeyondLastLine::VerticalScrollMargin => {
11185 (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
11186 }
11187 };
11188
11189 let overscroll = size(longest_line_blame_width, vertical_overscroll);
11190
11191 ScrollbarLayoutInformation {
11192 editor_bounds,
11193 scroll_range: document_size + overscroll,
11194 glyph_grid_cell,
11195 }
11196 }
11197}
11198
11199impl IntoElement for EditorElement {
11200 type Element = Self;
11201
11202 fn into_element(self) -> Self::Element {
11203 self
11204 }
11205}
11206
11207pub struct EditorLayout {
11208 position_map: Rc<PositionMap>,
11209 hitbox: Hitbox,
11210 gutter_hitbox: Hitbox,
11211 content_origin: gpui::Point<Pixels>,
11212 scrollbars_layout: Option<EditorScrollbars>,
11213 minimap: Option<MinimapLayout>,
11214 mode: EditorMode,
11215 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
11216 indent_guides: Option<Vec<IndentGuideLayout>>,
11217 visible_display_row_range: Range<DisplayRow>,
11218 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
11219 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
11220 line_elements: SmallVec<[AnyElement; 1]>,
11221 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
11222 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11223 blamed_display_rows: Option<Vec<AnyElement>>,
11224 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
11225 inline_blame_layout: Option<InlineBlameLayout>,
11226 inline_code_actions: Option<AnyElement>,
11227 blocks: Vec<BlockLayout>,
11228 spacer_blocks: Vec<BlockLayout>,
11229 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11230 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
11231 redacted_ranges: Vec<Range<DisplayPoint>>,
11232 cursors: Vec<(DisplayPoint, Hsla)>,
11233 visible_cursors: Vec<CursorLayout>,
11234 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
11235 test_indicators: Vec<AnyElement>,
11236 breakpoints: Vec<AnyElement>,
11237 diff_review_button: Option<AnyElement>,
11238 crease_toggles: Vec<Option<AnyElement>>,
11239 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
11240 diff_hunk_controls: Vec<AnyElement>,
11241 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
11242 edit_prediction_popover: Option<AnyElement>,
11243 mouse_context_menu: Option<AnyElement>,
11244 tab_invisible: ShapedLine,
11245 space_invisible: ShapedLine,
11246 sticky_buffer_header: Option<AnyElement>,
11247 sticky_headers: Option<StickyHeaders>,
11248 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
11249 text_align: TextAlign,
11250 content_width: Pixels,
11251}
11252
11253struct StickyHeaders {
11254 lines: Vec<StickyHeaderLine>,
11255 gutter_background: Hsla,
11256 content_background: Hsla,
11257 gutter_right_padding: Pixels,
11258}
11259
11260struct StickyHeaderLine {
11261 row: DisplayRow,
11262 offset: Pixels,
11263 line: Rc<LineWithInvisibles>,
11264 line_number: Option<ShapedLine>,
11265 elements: SmallVec<[AnyElement; 1]>,
11266 available_text_width: Pixels,
11267 hitbox: Hitbox,
11268}
11269
11270impl EditorLayout {
11271 fn line_end_overshoot(&self) -> Pixels {
11272 0.15 * self.position_map.line_height
11273 }
11274}
11275
11276impl StickyHeaders {
11277 fn paint(
11278 &mut self,
11279 layout: &mut EditorLayout,
11280 whitespace_setting: ShowWhitespaceSetting,
11281 window: &mut Window,
11282 cx: &mut App,
11283 ) {
11284 let line_height = layout.position_map.line_height;
11285
11286 for line in self.lines.iter_mut().rev() {
11287 window.paint_layer(
11288 Bounds::new(
11289 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11290 size(line.hitbox.size.width, line_height),
11291 ),
11292 |window| {
11293 let gutter_bounds = Bounds::new(
11294 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
11295 size(layout.gutter_hitbox.size.width, line_height),
11296 );
11297 window.paint_quad(fill(gutter_bounds, self.gutter_background));
11298
11299 let text_bounds = Bounds::new(
11300 layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
11301 size(line.available_text_width, line_height),
11302 );
11303 window.paint_quad(fill(text_bounds, self.content_background));
11304
11305 if line.hitbox.is_hovered(window) {
11306 let hover_overlay = cx.theme().colors().panel_overlay_hover;
11307 window.paint_quad(fill(gutter_bounds, hover_overlay));
11308 window.paint_quad(fill(text_bounds, hover_overlay));
11309 }
11310
11311 line.paint(
11312 layout,
11313 self.gutter_right_padding,
11314 line.available_text_width,
11315 layout.content_origin,
11316 line_height,
11317 whitespace_setting,
11318 window,
11319 cx,
11320 );
11321 },
11322 );
11323
11324 window.set_cursor_style(CursorStyle::IBeam, &line.hitbox);
11325 }
11326 }
11327}
11328
11329impl StickyHeaderLine {
11330 fn new(
11331 row: DisplayRow,
11332 offset: Pixels,
11333 mut line: LineWithInvisibles,
11334 line_number: Option<ShapedLine>,
11335 line_height: Pixels,
11336 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11337 content_origin: gpui::Point<Pixels>,
11338 gutter_hitbox: &Hitbox,
11339 text_hitbox: &Hitbox,
11340 window: &mut Window,
11341 cx: &mut App,
11342 ) -> Self {
11343 let mut elements = SmallVec::<[AnyElement; 1]>::new();
11344 line.prepaint_with_custom_offset(
11345 line_height,
11346 scroll_pixel_position,
11347 content_origin,
11348 offset,
11349 &mut elements,
11350 window,
11351 cx,
11352 );
11353
11354 let hitbox_bounds = Bounds::new(
11355 gutter_hitbox.origin + point(Pixels::ZERO, offset),
11356 size(text_hitbox.right() - gutter_hitbox.left(), line_height),
11357 );
11358 let available_text_width =
11359 (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
11360
11361 Self {
11362 row,
11363 offset,
11364 line: Rc::new(line),
11365 line_number,
11366 elements,
11367 available_text_width,
11368 hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
11369 }
11370 }
11371
11372 fn paint(
11373 &mut self,
11374 layout: &EditorLayout,
11375 gutter_right_padding: Pixels,
11376 available_text_width: Pixels,
11377 content_origin: gpui::Point<Pixels>,
11378 line_height: Pixels,
11379 whitespace_setting: ShowWhitespaceSetting,
11380 window: &mut Window,
11381 cx: &mut App,
11382 ) {
11383 window.with_content_mask(
11384 Some(ContentMask {
11385 bounds: Bounds::new(
11386 layout.position_map.text_hitbox.bounds.origin
11387 + point(Pixels::ZERO, self.offset),
11388 size(available_text_width, line_height),
11389 ),
11390 }),
11391 |window| {
11392 self.line.draw_with_custom_offset(
11393 layout,
11394 self.row,
11395 content_origin,
11396 self.offset,
11397 whitespace_setting,
11398 &[],
11399 window,
11400 cx,
11401 );
11402 for element in &mut self.elements {
11403 element.paint(window, cx);
11404 }
11405 },
11406 );
11407
11408 if let Some(line_number) = &self.line_number {
11409 let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
11410 let gutter_width = layout.gutter_hitbox.size.width;
11411 let origin = point(
11412 gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
11413 gutter_origin.y,
11414 );
11415 line_number
11416 .paint(origin, line_height, TextAlign::Left, None, window, cx)
11417 .log_err();
11418 }
11419 }
11420}
11421
11422#[derive(Debug)]
11423struct LineNumberSegment {
11424 shaped_line: ShapedLine,
11425 hitbox: Option<Hitbox>,
11426}
11427
11428#[derive(Debug)]
11429struct LineNumberLayout {
11430 segments: SmallVec<[LineNumberSegment; 1]>,
11431}
11432
11433struct ColoredRange<T> {
11434 start: T,
11435 end: T,
11436 color: Hsla,
11437}
11438
11439impl Along for ScrollbarAxes {
11440 type Unit = bool;
11441
11442 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
11443 match axis {
11444 ScrollbarAxis::Horizontal => self.horizontal,
11445 ScrollbarAxis::Vertical => self.vertical,
11446 }
11447 }
11448
11449 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
11450 match axis {
11451 ScrollbarAxis::Horizontal => ScrollbarAxes {
11452 horizontal: f(self.horizontal),
11453 vertical: self.vertical,
11454 },
11455 ScrollbarAxis::Vertical => ScrollbarAxes {
11456 horizontal: self.horizontal,
11457 vertical: f(self.vertical),
11458 },
11459 }
11460 }
11461}
11462
11463#[derive(Clone)]
11464struct EditorScrollbars {
11465 pub vertical: Option<ScrollbarLayout>,
11466 pub horizontal: Option<ScrollbarLayout>,
11467 pub visible: bool,
11468}
11469
11470impl EditorScrollbars {
11471 pub fn from_scrollbar_axes(
11472 show_scrollbar: ScrollbarAxes,
11473 layout_information: &ScrollbarLayoutInformation,
11474 content_offset: gpui::Point<Pixels>,
11475 scroll_position: gpui::Point<f64>,
11476 scrollbar_width: Pixels,
11477 right_margin: Pixels,
11478 editor_width: Pixels,
11479 show_scrollbars: bool,
11480 scrollbar_state: Option<&ActiveScrollbarState>,
11481 window: &mut Window,
11482 ) -> Self {
11483 let ScrollbarLayoutInformation {
11484 editor_bounds,
11485 scroll_range,
11486 glyph_grid_cell,
11487 } = layout_information;
11488
11489 let viewport_size = size(editor_width, editor_bounds.size.height);
11490
11491 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
11492 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
11493 Corner::BottomLeft,
11494 editor_bounds.bottom_left(),
11495 size(
11496 // The horizontal viewport size differs from the space available for the
11497 // horizontal scrollbar, so we have to manually stitch it together here.
11498 editor_bounds.size.width - right_margin,
11499 scrollbar_width,
11500 ),
11501 ),
11502 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
11503 Corner::TopRight,
11504 editor_bounds.top_right(),
11505 size(scrollbar_width, viewport_size.height),
11506 ),
11507 };
11508
11509 let mut create_scrollbar_layout = |axis| {
11510 let viewport_size = viewport_size.along(axis);
11511 let scroll_range = scroll_range.along(axis);
11512
11513 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
11514 (show_scrollbar.along(axis)
11515 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
11516 .then(|| {
11517 ScrollbarLayout::new(
11518 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
11519 viewport_size,
11520 scroll_range,
11521 glyph_grid_cell.along(axis),
11522 content_offset.along(axis),
11523 scroll_position.along(axis),
11524 show_scrollbars,
11525 axis,
11526 )
11527 .with_thumb_state(
11528 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
11529 )
11530 })
11531 };
11532
11533 Self {
11534 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
11535 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
11536 visible: show_scrollbars,
11537 }
11538 }
11539
11540 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
11541 [
11542 (&self.vertical, ScrollbarAxis::Vertical),
11543 (&self.horizontal, ScrollbarAxis::Horizontal),
11544 ]
11545 .into_iter()
11546 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
11547 }
11548
11549 /// Returns the currently hovered scrollbar axis, if any.
11550 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
11551 self.iter_scrollbars()
11552 .find(|s| s.0.hitbox.is_hovered(window))
11553 }
11554}
11555
11556#[derive(Clone)]
11557struct ScrollbarLayout {
11558 hitbox: Hitbox,
11559 visible_range: Range<ScrollOffset>,
11560 text_unit_size: Pixels,
11561 thumb_bounds: Option<Bounds<Pixels>>,
11562 thumb_state: ScrollbarThumbState,
11563}
11564
11565impl ScrollbarLayout {
11566 const BORDER_WIDTH: Pixels = px(1.0);
11567 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
11568 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
11569 const MIN_THUMB_SIZE: Pixels = px(25.0);
11570
11571 fn new(
11572 scrollbar_track_hitbox: Hitbox,
11573 viewport_size: Pixels,
11574 scroll_range: Pixels,
11575 glyph_space: Pixels,
11576 content_offset: Pixels,
11577 scroll_position: ScrollOffset,
11578 show_thumb: bool,
11579 axis: ScrollbarAxis,
11580 ) -> Self {
11581 let track_bounds = scrollbar_track_hitbox.bounds;
11582 // The length of the track available to the scrollbar thumb. We deliberately
11583 // exclude the content size here so that the thumb aligns with the content.
11584 let track_length = track_bounds.size.along(axis) - content_offset;
11585
11586 Self::new_with_hitbox_and_track_length(
11587 scrollbar_track_hitbox,
11588 track_length,
11589 viewport_size,
11590 scroll_range.into(),
11591 glyph_space,
11592 content_offset.into(),
11593 scroll_position,
11594 show_thumb,
11595 axis,
11596 )
11597 }
11598
11599 fn for_minimap(
11600 minimap_track_hitbox: Hitbox,
11601 visible_lines: f64,
11602 total_editor_lines: f64,
11603 minimap_line_height: Pixels,
11604 scroll_position: ScrollOffset,
11605 minimap_scroll_top: ScrollOffset,
11606 show_thumb: bool,
11607 ) -> Self {
11608 // The scrollbar thumb size is calculated as
11609 // (visible_content/total_content) Γ scrollbar_track_length.
11610 //
11611 // For the minimap's thumb layout, we leverage this by setting the
11612 // scrollbar track length to the entire document size (using minimap line
11613 // height). This creates a thumb that exactly represents the editor
11614 // viewport scaled to minimap proportions.
11615 //
11616 // We adjust the thumb position relative to `minimap_scroll_top` to
11617 // accommodate for the deliberately oversized track.
11618 //
11619 // This approach ensures that the minimap thumb accurately reflects the
11620 // editor's current scroll position whilst nicely synchronizing the minimap
11621 // thumb and scrollbar thumb.
11622 let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11623 let viewport_size = visible_lines * f64::from(minimap_line_height);
11624
11625 let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11626
11627 Self::new_with_hitbox_and_track_length(
11628 minimap_track_hitbox,
11629 Pixels::from(scroll_range),
11630 Pixels::from(viewport_size),
11631 scroll_range,
11632 minimap_line_height,
11633 track_top_offset,
11634 scroll_position,
11635 show_thumb,
11636 ScrollbarAxis::Vertical,
11637 )
11638 }
11639
11640 fn new_with_hitbox_and_track_length(
11641 scrollbar_track_hitbox: Hitbox,
11642 track_length: Pixels,
11643 viewport_size: Pixels,
11644 scroll_range: f64,
11645 glyph_space: Pixels,
11646 content_offset: ScrollOffset,
11647 scroll_position: ScrollOffset,
11648 show_thumb: bool,
11649 axis: ScrollbarAxis,
11650 ) -> Self {
11651 let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11652 let visible_range = scroll_position..scroll_position + text_units_per_page;
11653 let total_text_units = scroll_range / glyph_space.to_f64();
11654
11655 let thumb_percentage = text_units_per_page / total_text_units;
11656 let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11657 .max(ScrollbarLayout::MIN_THUMB_SIZE)
11658 .min(track_length);
11659
11660 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11661
11662 let content_larger_than_viewport = text_unit_divisor > 0.;
11663
11664 let text_unit_size = if content_larger_than_viewport {
11665 Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11666 } else {
11667 glyph_space
11668 };
11669
11670 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11671 Self::thumb_bounds(
11672 &scrollbar_track_hitbox,
11673 content_offset,
11674 visible_range.start,
11675 text_unit_size,
11676 thumb_size,
11677 axis,
11678 )
11679 });
11680
11681 ScrollbarLayout {
11682 hitbox: scrollbar_track_hitbox,
11683 visible_range,
11684 text_unit_size,
11685 thumb_bounds,
11686 thumb_state: Default::default(),
11687 }
11688 }
11689
11690 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11691 if let Some(thumb_state) = thumb_state {
11692 Self {
11693 thumb_state,
11694 ..self
11695 }
11696 } else {
11697 self
11698 }
11699 }
11700
11701 fn thumb_bounds(
11702 scrollbar_track: &Hitbox,
11703 content_offset: f64,
11704 visible_range_start: f64,
11705 text_unit_size: Pixels,
11706 thumb_size: Pixels,
11707 axis: ScrollbarAxis,
11708 ) -> Bounds<Pixels> {
11709 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11710 origin
11711 + Pixels::from(
11712 content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11713 )
11714 });
11715 Bounds::new(
11716 thumb_origin,
11717 scrollbar_track.size.apply_along(axis, |_| thumb_size),
11718 )
11719 }
11720
11721 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11722 self.thumb_bounds
11723 .is_some_and(|bounds| bounds.contains(position))
11724 }
11725
11726 fn marker_quads_for_ranges(
11727 &self,
11728 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11729 column: Option<usize>,
11730 ) -> Vec<PaintQuad> {
11731 struct MinMax {
11732 min: Pixels,
11733 max: Pixels,
11734 }
11735 let (x_range, height_limit) = if let Some(column) = column {
11736 let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11737 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11738 let end = start + column_width;
11739 (
11740 Range { start, end },
11741 MinMax {
11742 min: Self::MIN_MARKER_HEIGHT,
11743 max: px(f32::MAX),
11744 },
11745 )
11746 } else {
11747 (
11748 Range {
11749 start: Self::BORDER_WIDTH,
11750 end: self.hitbox.size.width,
11751 },
11752 MinMax {
11753 min: Self::LINE_MARKER_HEIGHT,
11754 max: Self::LINE_MARKER_HEIGHT,
11755 },
11756 )
11757 };
11758
11759 let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11760 let mut pixel_ranges = row_ranges
11761 .into_iter()
11762 .map(|range| {
11763 let start_y = row_to_y(range.start);
11764 let end_y = row_to_y(range.end)
11765 + self
11766 .text_unit_size
11767 .max(height_limit.min)
11768 .min(height_limit.max);
11769 ColoredRange {
11770 start: start_y,
11771 end: end_y,
11772 color: range.color,
11773 }
11774 })
11775 .peekable();
11776
11777 let mut quads = Vec::new();
11778 while let Some(mut pixel_range) = pixel_ranges.next() {
11779 while let Some(next_pixel_range) = pixel_ranges.peek() {
11780 if pixel_range.end >= next_pixel_range.start - px(1.0)
11781 && pixel_range.color == next_pixel_range.color
11782 {
11783 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11784 pixel_ranges.next();
11785 } else {
11786 break;
11787 }
11788 }
11789
11790 let bounds = Bounds::from_corners(
11791 point(x_range.start, pixel_range.start),
11792 point(x_range.end, pixel_range.end),
11793 );
11794 quads.push(quad(
11795 bounds,
11796 Corners::default(),
11797 pixel_range.color,
11798 Edges::default(),
11799 Hsla::transparent_black(),
11800 BorderStyle::default(),
11801 ));
11802 }
11803
11804 quads
11805 }
11806}
11807
11808struct MinimapLayout {
11809 pub minimap: AnyElement,
11810 pub thumb_layout: ScrollbarLayout,
11811 pub minimap_scroll_top: ScrollOffset,
11812 pub minimap_line_height: Pixels,
11813 pub thumb_border_style: MinimapThumbBorder,
11814 pub max_scroll_top: ScrollOffset,
11815}
11816
11817impl MinimapLayout {
11818 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11819 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11820 /// The minimap width as a percentage of the editor width.
11821 const MINIMAP_WIDTH_PCT: f32 = 0.15;
11822 /// Calculates the scroll top offset the minimap editor has to have based on the
11823 /// current scroll progress.
11824 fn calculate_minimap_top_offset(
11825 document_lines: f64,
11826 visible_editor_lines: f64,
11827 visible_minimap_lines: f64,
11828 scroll_position: f64,
11829 ) -> ScrollOffset {
11830 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11831 if non_visible_document_lines == 0. {
11832 0.
11833 } else {
11834 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11835 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11836 }
11837 }
11838}
11839
11840struct CreaseTrailerLayout {
11841 element: AnyElement,
11842 bounds: Bounds<Pixels>,
11843}
11844
11845pub(crate) struct PositionMap {
11846 pub size: Size<Pixels>,
11847 pub line_height: Pixels,
11848 pub scroll_position: gpui::Point<ScrollOffset>,
11849 pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11850 pub scroll_max: gpui::Point<ScrollOffset>,
11851 pub em_width: Pixels,
11852 pub em_advance: Pixels,
11853 pub em_layout_width: Pixels,
11854 pub visible_row_range: Range<DisplayRow>,
11855 pub line_layouts: Vec<LineWithInvisibles>,
11856 pub snapshot: EditorSnapshot,
11857 pub text_align: TextAlign,
11858 pub content_width: Pixels,
11859 pub text_hitbox: Hitbox,
11860 pub gutter_hitbox: Hitbox,
11861 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11862 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11863 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11864}
11865
11866#[derive(Debug, Copy, Clone)]
11867pub struct PointForPosition {
11868 pub previous_valid: DisplayPoint,
11869 pub next_valid: DisplayPoint,
11870 pub exact_unclipped: DisplayPoint,
11871 pub column_overshoot_after_line_end: u32,
11872}
11873
11874impl PointForPosition {
11875 pub fn as_valid(&self) -> Option<DisplayPoint> {
11876 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11877 Some(self.previous_valid)
11878 } else {
11879 None
11880 }
11881 }
11882
11883 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11884 let Some(valid_point) = self.as_valid() else {
11885 return false;
11886 };
11887 let range = selection.range();
11888
11889 let candidate_row = valid_point.row();
11890 let candidate_col = valid_point.column();
11891
11892 let start_row = range.start.row();
11893 let start_col = range.start.column();
11894 let end_row = range.end.row();
11895 let end_col = range.end.column();
11896
11897 if candidate_row < start_row || candidate_row > end_row {
11898 false
11899 } else if start_row == end_row {
11900 candidate_col >= start_col && candidate_col < end_col
11901 } else if candidate_row == start_row {
11902 candidate_col >= start_col
11903 } else if candidate_row == end_row {
11904 candidate_col < end_col
11905 } else {
11906 true
11907 }
11908 }
11909}
11910
11911impl PositionMap {
11912 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11913 let text_bounds = self.text_hitbox.bounds;
11914 let scroll_position = self.snapshot.scroll_position();
11915 let position = position - text_bounds.origin;
11916 let y = position.y.max(px(0.)).min(self.size.height);
11917 let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11918 let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11919
11920 let (column, x_overshoot_after_line_end) = if let Some(line) = self
11921 .line_layouts
11922 .get(row as usize - scroll_position.y as usize)
11923 {
11924 let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11925 let x_relative_to_text = x - alignment_offset;
11926 if let Some(ix) = line.index_for_x(x_relative_to_text) {
11927 (ix as u32, px(0.))
11928 } else {
11929 (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11930 }
11931 } else {
11932 (0, x)
11933 };
11934
11935 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11936 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11937 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11938
11939 let column_overshoot_after_line_end =
11940 (x_overshoot_after_line_end / self.em_layout_width) as u32;
11941 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11942 PointForPosition {
11943 previous_valid,
11944 next_valid,
11945 exact_unclipped,
11946 column_overshoot_after_line_end,
11947 }
11948 }
11949
11950 fn point_for_position_on_line(
11951 &self,
11952 position: gpui::Point<Pixels>,
11953 row: DisplayRow,
11954 line: &LineWithInvisibles,
11955 ) -> PointForPosition {
11956 let text_bounds = self.text_hitbox.bounds;
11957 let scroll_position = self.snapshot.scroll_position();
11958 let position = position - text_bounds.origin;
11959 let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
11960
11961 let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11962 let x_relative_to_text = x - alignment_offset;
11963 let (column, x_overshoot_after_line_end) =
11964 if let Some(ix) = line.index_for_x(x_relative_to_text) {
11965 (ix as u32, px(0.))
11966 } else {
11967 (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11968 };
11969
11970 let mut exact_unclipped = DisplayPoint::new(row, column);
11971 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11972 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11973
11974 let column_overshoot_after_line_end =
11975 (x_overshoot_after_line_end / self.em_layout_width) as u32;
11976 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11977 PointForPosition {
11978 previous_valid,
11979 next_valid,
11980 exact_unclipped,
11981 column_overshoot_after_line_end,
11982 }
11983 }
11984}
11985
11986pub(crate) struct BlockLayout {
11987 pub(crate) id: BlockId,
11988 pub(crate) x_offset: Pixels,
11989 pub(crate) row: Option<DisplayRow>,
11990 pub(crate) element: AnyElement,
11991 pub(crate) available_space: Size<AvailableSpace>,
11992 pub(crate) style: BlockStyle,
11993 pub(crate) overlaps_gutter: bool,
11994 pub(crate) is_buffer_header: bool,
11995}
11996
11997pub fn layout_line(
11998 row: DisplayRow,
11999 snapshot: &EditorSnapshot,
12000 style: &EditorStyle,
12001 text_width: Pixels,
12002 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
12003 window: &mut Window,
12004 cx: &mut App,
12005) -> LineWithInvisibles {
12006 let use_tree_sitter =
12007 !snapshot.semantic_tokens_enabled || snapshot.use_tree_sitter_for_syntax(row, cx);
12008 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), use_tree_sitter, style);
12009 LineWithInvisibles::from_chunks(
12010 chunks,
12011 style,
12012 MAX_LINE_LEN,
12013 1,
12014 &snapshot.mode,
12015 text_width,
12016 is_row_soft_wrapped,
12017 &[],
12018 window,
12019 cx,
12020 )
12021 .pop()
12022 .unwrap()
12023}
12024
12025#[derive(Debug, Clone)]
12026pub struct IndentGuideLayout {
12027 origin: gpui::Point<Pixels>,
12028 length: Pixels,
12029 single_indent_width: Pixels,
12030 display_row_range: Range<DisplayRow>,
12031 depth: u32,
12032 active: bool,
12033 settings: IndentGuideSettings,
12034}
12035
12036pub struct CursorLayout {
12037 origin: gpui::Point<Pixels>,
12038 block_width: Pixels,
12039 line_height: Pixels,
12040 color: Hsla,
12041 shape: CursorShape,
12042 block_text: Option<ShapedLine>,
12043 cursor_name: Option<AnyElement>,
12044}
12045
12046#[derive(Debug)]
12047pub struct CursorName {
12048 string: SharedString,
12049 color: Hsla,
12050 is_top_row: bool,
12051}
12052
12053impl CursorLayout {
12054 pub fn new(
12055 origin: gpui::Point<Pixels>,
12056 block_width: Pixels,
12057 line_height: Pixels,
12058 color: Hsla,
12059 shape: CursorShape,
12060 block_text: Option<ShapedLine>,
12061 ) -> CursorLayout {
12062 CursorLayout {
12063 origin,
12064 block_width,
12065 line_height,
12066 color,
12067 shape,
12068 block_text,
12069 cursor_name: None,
12070 }
12071 }
12072
12073 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12074 Bounds {
12075 origin: self.origin + origin,
12076 size: size(self.block_width, self.line_height),
12077 }
12078 }
12079
12080 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
12081 match self.shape {
12082 CursorShape::Bar => Bounds {
12083 origin: self.origin + origin,
12084 size: size(px(2.0), self.line_height),
12085 },
12086 CursorShape::Block | CursorShape::Hollow => Bounds {
12087 origin: self.origin + origin,
12088 size: size(self.block_width, self.line_height),
12089 },
12090 CursorShape::Underline => Bounds {
12091 origin: self.origin
12092 + origin
12093 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
12094 size: size(self.block_width, px(2.0)),
12095 },
12096 }
12097 }
12098
12099 pub fn layout(
12100 &mut self,
12101 origin: gpui::Point<Pixels>,
12102 cursor_name: Option<CursorName>,
12103 window: &mut Window,
12104 cx: &mut App,
12105 ) {
12106 if let Some(cursor_name) = cursor_name {
12107 let bounds = self.bounds(origin);
12108 let text_size = self.line_height / 1.5;
12109
12110 let name_origin = if cursor_name.is_top_row {
12111 point(bounds.right() - px(1.), bounds.top())
12112 } else {
12113 match self.shape {
12114 CursorShape::Bar => point(
12115 bounds.right() - px(2.),
12116 bounds.top() - text_size / 2. - px(1.),
12117 ),
12118 _ => point(
12119 bounds.right() - px(1.),
12120 bounds.top() - text_size / 2. - px(1.),
12121 ),
12122 }
12123 };
12124 let mut name_element = div()
12125 .bg(self.color)
12126 .text_size(text_size)
12127 .px_0p5()
12128 .line_height(text_size + px(2.))
12129 .text_color(cursor_name.color)
12130 .child(cursor_name.string)
12131 .into_any_element();
12132
12133 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
12134
12135 self.cursor_name = Some(name_element);
12136 }
12137 }
12138
12139 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
12140 let bounds = self.bounds(origin);
12141
12142 //Draw background or border quad
12143 let cursor = if matches!(self.shape, CursorShape::Hollow) {
12144 outline(bounds, self.color, BorderStyle::Solid)
12145 } else {
12146 fill(bounds, self.color)
12147 };
12148
12149 if let Some(name) = &mut self.cursor_name {
12150 name.paint(window, cx);
12151 }
12152
12153 window.paint_quad(cursor);
12154
12155 if let Some(block_text) = &self.block_text {
12156 block_text
12157 .paint(
12158 self.origin + origin,
12159 self.line_height,
12160 TextAlign::Left,
12161 None,
12162 window,
12163 cx,
12164 )
12165 .log_err();
12166 }
12167 }
12168
12169 pub fn shape(&self) -> CursorShape {
12170 self.shape
12171 }
12172}
12173
12174#[derive(Debug)]
12175pub struct HighlightedRange {
12176 pub start_y: Pixels,
12177 pub line_height: Pixels,
12178 pub lines: Vec<HighlightedRangeLine>,
12179 pub color: Hsla,
12180 pub corner_radius: Pixels,
12181}
12182
12183#[derive(Debug)]
12184pub struct HighlightedRangeLine {
12185 pub start_x: Pixels,
12186 pub end_x: Pixels,
12187}
12188
12189impl HighlightedRange {
12190 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
12191 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
12192 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
12193 self.paint_lines(
12194 self.start_y + self.line_height,
12195 &self.lines[1..],
12196 fill,
12197 bounds,
12198 window,
12199 );
12200 } else {
12201 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
12202 }
12203 }
12204
12205 fn paint_lines(
12206 &self,
12207 start_y: Pixels,
12208 lines: &[HighlightedRangeLine],
12209 fill: bool,
12210 _bounds: Bounds<Pixels>,
12211 window: &mut Window,
12212 ) {
12213 if lines.is_empty() {
12214 return;
12215 }
12216
12217 let first_line = lines.first().unwrap();
12218 let last_line = lines.last().unwrap();
12219
12220 let first_top_left = point(first_line.start_x, start_y);
12221 let first_top_right = point(first_line.end_x, start_y);
12222
12223 let curve_height = point(Pixels::ZERO, self.corner_radius);
12224 let curve_width = |start_x: Pixels, end_x: Pixels| {
12225 let max = (end_x - start_x) / 2.;
12226 let width = if max < self.corner_radius {
12227 max
12228 } else {
12229 self.corner_radius
12230 };
12231
12232 point(width, Pixels::ZERO)
12233 };
12234
12235 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
12236 let mut builder = if fill {
12237 gpui::PathBuilder::fill()
12238 } else {
12239 gpui::PathBuilder::stroke(px(1.))
12240 };
12241 builder.move_to(first_top_right - top_curve_width);
12242 builder.curve_to(first_top_right + curve_height, first_top_right);
12243
12244 let mut iter = lines.iter().enumerate().peekable();
12245 while let Some((ix, line)) = iter.next() {
12246 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
12247
12248 if let Some((_, next_line)) = iter.peek() {
12249 let next_top_right = point(next_line.end_x, bottom_right.y);
12250
12251 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
12252 Ordering::Equal => {
12253 builder.line_to(bottom_right);
12254 }
12255 Ordering::Less => {
12256 let curve_width = curve_width(next_top_right.x, bottom_right.x);
12257 builder.line_to(bottom_right - curve_height);
12258 if self.corner_radius > Pixels::ZERO {
12259 builder.curve_to(bottom_right - curve_width, bottom_right);
12260 }
12261 builder.line_to(next_top_right + curve_width);
12262 if self.corner_radius > Pixels::ZERO {
12263 builder.curve_to(next_top_right + curve_height, next_top_right);
12264 }
12265 }
12266 Ordering::Greater => {
12267 let curve_width = curve_width(bottom_right.x, next_top_right.x);
12268 builder.line_to(bottom_right - curve_height);
12269 if self.corner_radius > Pixels::ZERO {
12270 builder.curve_to(bottom_right + curve_width, bottom_right);
12271 }
12272 builder.line_to(next_top_right - curve_width);
12273 if self.corner_radius > Pixels::ZERO {
12274 builder.curve_to(next_top_right + curve_height, next_top_right);
12275 }
12276 }
12277 }
12278 } else {
12279 let curve_width = curve_width(line.start_x, line.end_x);
12280 builder.line_to(bottom_right - curve_height);
12281 if self.corner_radius > Pixels::ZERO {
12282 builder.curve_to(bottom_right - curve_width, bottom_right);
12283 }
12284
12285 let bottom_left = point(line.start_x, bottom_right.y);
12286 builder.line_to(bottom_left + curve_width);
12287 if self.corner_radius > Pixels::ZERO {
12288 builder.curve_to(bottom_left - curve_height, bottom_left);
12289 }
12290 }
12291 }
12292
12293 if first_line.start_x > last_line.start_x {
12294 let curve_width = curve_width(last_line.start_x, first_line.start_x);
12295 let second_top_left = point(last_line.start_x, start_y + self.line_height);
12296 builder.line_to(second_top_left + curve_height);
12297 if self.corner_radius > Pixels::ZERO {
12298 builder.curve_to(second_top_left + curve_width, second_top_left);
12299 }
12300 let first_bottom_left = point(first_line.start_x, second_top_left.y);
12301 builder.line_to(first_bottom_left - curve_width);
12302 if self.corner_radius > Pixels::ZERO {
12303 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
12304 }
12305 }
12306
12307 builder.line_to(first_top_left + curve_height);
12308 if self.corner_radius > Pixels::ZERO {
12309 builder.curve_to(first_top_left + top_curve_width, first_top_left);
12310 }
12311 builder.line_to(first_top_right - top_curve_width);
12312
12313 if let Ok(path) = builder.build() {
12314 window.paint_path(path, self.color);
12315 }
12316 }
12317}
12318
12319pub(crate) struct StickyHeader {
12320 pub sticky_row: DisplayRow,
12321 pub start_point: Point,
12322 pub offset: ScrollOffset,
12323}
12324
12325enum CursorPopoverType {
12326 CodeContextMenu,
12327 EditPrediction,
12328}
12329
12330pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12331 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
12332}
12333
12334fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
12335 (delta.pow(1.2) / 300.0).into()
12336}
12337
12338pub fn register_action<T: Action>(
12339 editor: &Entity<Editor>,
12340 window: &mut Window,
12341 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
12342) {
12343 let editor = editor.clone();
12344 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
12345 let action = action.downcast_ref().unwrap();
12346 if phase == DispatchPhase::Bubble {
12347 editor.update(cx, |editor, cx| {
12348 listener(editor, action, window, cx);
12349 })
12350 }
12351 })
12352}
12353
12354/// Shared between `prepaint` and `compute_auto_height_layout` to ensure
12355/// both full and auto-height editors compute wrap widths consistently.
12356fn calculate_wrap_width(
12357 soft_wrap: SoftWrap,
12358 editor_width: Pixels,
12359 em_width: Pixels,
12360) -> Option<Pixels> {
12361 let wrap_width_for = |column: u32| (column as f32 * em_width).ceil();
12362
12363 match soft_wrap {
12364 SoftWrap::GitDiff => None,
12365 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
12366 SoftWrap::EditorWidth => Some(editor_width),
12367 SoftWrap::Column(column) => Some(wrap_width_for(column)),
12368 SoftWrap::Bounded(column) => Some(editor_width.min(wrap_width_for(column))),
12369 }
12370}
12371
12372fn compute_auto_height_layout(
12373 editor: &mut Editor,
12374 min_lines: usize,
12375 max_lines: Option<usize>,
12376 known_dimensions: Size<Option<Pixels>>,
12377 available_width: AvailableSpace,
12378 window: &mut Window,
12379 cx: &mut Context<Editor>,
12380) -> Option<Size<Pixels>> {
12381 let width = known_dimensions.width.or({
12382 if let AvailableSpace::Definite(available_width) = available_width {
12383 Some(available_width)
12384 } else {
12385 None
12386 }
12387 })?;
12388 if let Some(height) = known_dimensions.height {
12389 return Some(size(width, height));
12390 }
12391
12392 let style = editor.style.as_ref().unwrap();
12393 let font_id = window.text_system().resolve_font(&style.text.font());
12394 let font_size = style.text.font_size.to_pixels(window.rem_size());
12395 let line_height = style.text.line_height_in_pixels(window.rem_size());
12396 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
12397
12398 let mut snapshot = editor.snapshot(window, cx);
12399 let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
12400
12401 editor.gutter_dimensions = gutter_dimensions;
12402 let text_width = width - gutter_dimensions.width;
12403 let overscroll = size(em_width, px(0.));
12404
12405 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
12406 let wrap_width = calculate_wrap_width(editor.soft_wrap_mode(cx), editor_width, em_width);
12407 if wrap_width.is_some() && editor.set_wrap_width(wrap_width, cx) {
12408 snapshot = editor.snapshot(window, cx);
12409 }
12410
12411 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
12412
12413 let min_height = line_height * min_lines as f32;
12414 let content_height = scroll_height.max(min_height);
12415
12416 let final_height = if let Some(max_lines) = max_lines {
12417 let max_height = line_height * max_lines as f32;
12418 content_height.min(max_height)
12419 } else {
12420 content_height
12421 };
12422
12423 Some(size(width, final_height))
12424}
12425
12426#[cfg(test)]
12427mod tests {
12428 use super::*;
12429 use crate::{
12430 Editor, MultiBuffer, SelectionEffects,
12431 display_map::{BlockPlacement, BlockProperties},
12432 editor_tests::{init_test, update_test_language_settings},
12433 };
12434 use gpui::{TestAppContext, VisualTestContext};
12435 use language::{Buffer, language_settings, tree_sitter_python};
12436 use log::info;
12437 use rand::{RngCore, rngs::StdRng};
12438 use std::num::NonZeroU32;
12439 use util::test::sample_text;
12440
12441 #[gpui::test]
12442 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
12443 init_test(cx, |_| {});
12444 let window = cx.add_window(|window, cx| {
12445 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12446 let mut editor = Editor::new(
12447 EditorMode::AutoHeight {
12448 min_lines: 1,
12449 max_lines: None,
12450 },
12451 buffer,
12452 None,
12453 window,
12454 cx,
12455 );
12456 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12457 editor
12458 });
12459 let cx = &mut VisualTestContext::from_window(*window, cx);
12460 let editor = window.root(cx).unwrap();
12461 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12462
12463 for x in 1..=100 {
12464 let (_, state) = cx.draw(
12465 Default::default(),
12466 size(px(200. + 0.13 * x as f32), px(500.)),
12467 |_, _| EditorElement::new(&editor, style.clone()),
12468 );
12469
12470 assert!(
12471 state.position_map.scroll_max.x == 0.,
12472 "Soft wrapped editor should have no horizontal scrolling!"
12473 );
12474 }
12475 }
12476
12477 #[gpui::test]
12478 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
12479 init_test(cx, |_| {});
12480 let window = cx.add_window(|window, cx| {
12481 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
12482 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
12483 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12484 editor
12485 });
12486 let cx = &mut VisualTestContext::from_window(*window, cx);
12487 let editor = window.root(cx).unwrap();
12488 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12489
12490 for x in 1..=100 {
12491 let (_, state) = cx.draw(
12492 Default::default(),
12493 size(px(200. + 0.13 * x as f32), px(500.)),
12494 |_, _| EditorElement::new(&editor, style.clone()),
12495 );
12496
12497 assert!(
12498 state.position_map.scroll_max.x == 0.,
12499 "Soft wrapped editor should have no horizontal scrolling!"
12500 );
12501 }
12502 }
12503
12504 #[gpui::test]
12505 fn test_layout_line_numbers(cx: &mut TestAppContext) {
12506 init_test(cx, |_| {});
12507 let window = cx.add_window(|window, cx| {
12508 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12509 Editor::new(EditorMode::full(), buffer, None, window, cx)
12510 });
12511
12512 let editor = window.root(cx).unwrap();
12513 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12514 let line_height = window
12515 .update(cx, |_, window, _| {
12516 style.text.line_height_in_pixels(window.rem_size())
12517 })
12518 .unwrap();
12519 let element = EditorElement::new(&editor, style);
12520 let snapshot = window
12521 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12522 .unwrap();
12523
12524 let layouts = cx
12525 .update_window(*window, |_, window, cx| {
12526 element.layout_line_numbers(
12527 None,
12528 GutterDimensions {
12529 left_padding: Pixels::ZERO,
12530 right_padding: Pixels::ZERO,
12531 width: px(30.0),
12532 margin: Pixels::ZERO,
12533 git_blame_entries_width: None,
12534 },
12535 line_height,
12536 gpui::Point::default(),
12537 DisplayRow(0)..DisplayRow(6),
12538 &(0..6)
12539 .map(|row| RowInfo {
12540 buffer_row: Some(row),
12541 ..Default::default()
12542 })
12543 .collect::<Vec<_>>(),
12544 &BTreeMap::default(),
12545 Some(DisplayRow(0)),
12546 &snapshot,
12547 window,
12548 cx,
12549 )
12550 })
12551 .unwrap();
12552 assert_eq!(layouts.len(), 6);
12553
12554 let relative_rows = window
12555 .update(cx, |editor, window, cx| {
12556 let snapshot = editor.snapshot(window, cx);
12557 snapshot.calculate_relative_line_numbers(
12558 &(DisplayRow(0)..DisplayRow(6)),
12559 DisplayRow(3),
12560 false,
12561 )
12562 })
12563 .unwrap();
12564 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12565 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12566 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12567 // current line has no relative number
12568 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12569 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12570 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12571
12572 // works if cursor is before screen
12573 let relative_rows = window
12574 .update(cx, |editor, window, cx| {
12575 let snapshot = editor.snapshot(window, cx);
12576 snapshot.calculate_relative_line_numbers(
12577 &(DisplayRow(3)..DisplayRow(6)),
12578 DisplayRow(1),
12579 false,
12580 )
12581 })
12582 .unwrap();
12583 assert_eq!(relative_rows.len(), 3);
12584 assert_eq!(relative_rows[&DisplayRow(3)], 2);
12585 assert_eq!(relative_rows[&DisplayRow(4)], 3);
12586 assert_eq!(relative_rows[&DisplayRow(5)], 4);
12587
12588 // works if cursor is after screen
12589 let relative_rows = window
12590 .update(cx, |editor, window, cx| {
12591 let snapshot = editor.snapshot(window, cx);
12592 snapshot.calculate_relative_line_numbers(
12593 &(DisplayRow(0)..DisplayRow(3)),
12594 DisplayRow(6),
12595 false,
12596 )
12597 })
12598 .unwrap();
12599 assert_eq!(relative_rows.len(), 3);
12600 assert_eq!(relative_rows[&DisplayRow(0)], 5);
12601 assert_eq!(relative_rows[&DisplayRow(1)], 4);
12602 assert_eq!(relative_rows[&DisplayRow(2)], 3);
12603
12604 const DELETED_LINE: u32 = 3;
12605 let layouts = cx
12606 .update_window(*window, |_, window, cx| {
12607 element.layout_line_numbers(
12608 None,
12609 GutterDimensions {
12610 left_padding: Pixels::ZERO,
12611 right_padding: Pixels::ZERO,
12612 width: px(30.0),
12613 margin: Pixels::ZERO,
12614 git_blame_entries_width: None,
12615 },
12616 line_height,
12617 gpui::Point::default(),
12618 DisplayRow(0)..DisplayRow(6),
12619 &(0..6)
12620 .map(|row| RowInfo {
12621 buffer_row: Some(row),
12622 diff_status: (row == DELETED_LINE).then(|| {
12623 DiffHunkStatus::deleted(
12624 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12625 )
12626 }),
12627 ..Default::default()
12628 })
12629 .collect::<Vec<_>>(),
12630 &BTreeMap::default(),
12631 Some(DisplayRow(0)),
12632 &snapshot,
12633 window,
12634 cx,
12635 )
12636 })
12637 .unwrap();
12638 assert_eq!(layouts.len(), 5,);
12639 assert!(
12640 layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
12641 "Deleted line should not have a line number"
12642 );
12643 }
12644
12645 #[gpui::test]
12646 async fn test_layout_line_numbers_with_folded_lines(cx: &mut TestAppContext) {
12647 init_test(cx, |_| {});
12648
12649 let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
12650
12651 let window = cx.add_window(|window, cx| {
12652 let buffer = cx.new(|cx| {
12653 Buffer::local(
12654 indoc::indoc! {"
12655 fn test() -> int {
12656 return 2;
12657 }
12658
12659 fn another_test() -> int {
12660 # This is a very peculiar method that is hard to grasp.
12661 return 4;
12662 }
12663 "},
12664 cx,
12665 )
12666 .with_language(python_lang, cx)
12667 });
12668
12669 let buffer = MultiBuffer::build_from_buffer(buffer, cx);
12670 Editor::new(EditorMode::full(), buffer, None, window, cx)
12671 });
12672
12673 let editor = window.root(cx).unwrap();
12674 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12675 let line_height = window
12676 .update(cx, |_, window, _| {
12677 style.text.line_height_in_pixels(window.rem_size())
12678 })
12679 .unwrap();
12680 let element = EditorElement::new(&editor, style);
12681 let snapshot = window
12682 .update(cx, |editor, window, cx| {
12683 editor.fold_at(MultiBufferRow(0), window, cx);
12684 editor.snapshot(window, cx)
12685 })
12686 .unwrap();
12687
12688 let layouts = cx
12689 .update_window(*window, |_, window, cx| {
12690 element.layout_line_numbers(
12691 None,
12692 GutterDimensions {
12693 left_padding: Pixels::ZERO,
12694 right_padding: Pixels::ZERO,
12695 width: px(30.0),
12696 margin: Pixels::ZERO,
12697 git_blame_entries_width: None,
12698 },
12699 line_height,
12700 gpui::Point::default(),
12701 DisplayRow(0)..DisplayRow(6),
12702 &(0..6)
12703 .map(|row| RowInfo {
12704 buffer_row: Some(row),
12705 ..Default::default()
12706 })
12707 .collect::<Vec<_>>(),
12708 &BTreeMap::default(),
12709 Some(DisplayRow(3)),
12710 &snapshot,
12711 window,
12712 cx,
12713 )
12714 })
12715 .unwrap();
12716 assert_eq!(layouts.len(), 6);
12717
12718 let relative_rows = window
12719 .update(cx, |editor, window, cx| {
12720 let snapshot = editor.snapshot(window, cx);
12721 snapshot.calculate_relative_line_numbers(
12722 &(DisplayRow(0)..DisplayRow(6)),
12723 DisplayRow(3),
12724 false,
12725 )
12726 })
12727 .unwrap();
12728 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12729 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12730 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12731 // current line has no relative number
12732 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12733 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12734 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12735 }
12736
12737 #[gpui::test]
12738 fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
12739 init_test(cx, |_| {});
12740 let window = cx.add_window(|window, cx| {
12741 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
12742 Editor::new(EditorMode::full(), buffer, None, window, cx)
12743 });
12744
12745 update_test_language_settings(cx, &|s| {
12746 s.defaults.preferred_line_length = Some(5_u32);
12747 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12748 });
12749
12750 let editor = window.root(cx).unwrap();
12751 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12752 let line_height = window
12753 .update(cx, |_, window, _| {
12754 style.text.line_height_in_pixels(window.rem_size())
12755 })
12756 .unwrap();
12757 let element = EditorElement::new(&editor, style);
12758 let snapshot = window
12759 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12760 .unwrap();
12761
12762 let layouts = cx
12763 .update_window(*window, |_, window, cx| {
12764 element.layout_line_numbers(
12765 None,
12766 GutterDimensions {
12767 left_padding: Pixels::ZERO,
12768 right_padding: Pixels::ZERO,
12769 width: px(30.0),
12770 margin: Pixels::ZERO,
12771 git_blame_entries_width: None,
12772 },
12773 line_height,
12774 gpui::Point::default(),
12775 DisplayRow(0)..DisplayRow(6),
12776 &(0..6)
12777 .map(|row| RowInfo {
12778 buffer_row: Some(row),
12779 ..Default::default()
12780 })
12781 .collect::<Vec<_>>(),
12782 &BTreeMap::default(),
12783 Some(DisplayRow(0)),
12784 &snapshot,
12785 window,
12786 cx,
12787 )
12788 })
12789 .unwrap();
12790 assert_eq!(layouts.len(), 3);
12791
12792 let relative_rows = window
12793 .update(cx, |editor, window, cx| {
12794 let snapshot = editor.snapshot(window, cx);
12795 snapshot.calculate_relative_line_numbers(
12796 &(DisplayRow(0)..DisplayRow(6)),
12797 DisplayRow(3),
12798 true,
12799 )
12800 })
12801 .unwrap();
12802
12803 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12804 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12805 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12806 // current line has no relative number
12807 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12808 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12809 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12810
12811 let layouts = cx
12812 .update_window(*window, |_, window, cx| {
12813 element.layout_line_numbers(
12814 None,
12815 GutterDimensions {
12816 left_padding: Pixels::ZERO,
12817 right_padding: Pixels::ZERO,
12818 width: px(30.0),
12819 margin: Pixels::ZERO,
12820 git_blame_entries_width: None,
12821 },
12822 line_height,
12823 gpui::Point::default(),
12824 DisplayRow(0)..DisplayRow(6),
12825 &(0..6)
12826 .map(|row| RowInfo {
12827 buffer_row: Some(row),
12828 diff_status: Some(DiffHunkStatus::deleted(
12829 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12830 )),
12831 ..Default::default()
12832 })
12833 .collect::<Vec<_>>(),
12834 &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12835 Some(DisplayRow(0)),
12836 &snapshot,
12837 window,
12838 cx,
12839 )
12840 })
12841 .unwrap();
12842 assert!(
12843 layouts.is_empty(),
12844 "Deleted lines should have no line number"
12845 );
12846
12847 let relative_rows = window
12848 .update(cx, |editor, window, cx| {
12849 let snapshot = editor.snapshot(window, cx);
12850 snapshot.calculate_relative_line_numbers(
12851 &(DisplayRow(0)..DisplayRow(6)),
12852 DisplayRow(3),
12853 true,
12854 )
12855 })
12856 .unwrap();
12857
12858 // Deleted lines should still have relative numbers
12859 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12860 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12861 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12862 // current line, even if deleted, has no relative number
12863 assert!(!relative_rows.contains_key(&DisplayRow(3)));
12864 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12865 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12866 }
12867
12868 #[gpui::test]
12869 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12870 init_test(cx, |_| {});
12871
12872 let window = cx.add_window(|window, cx| {
12873 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12874 Editor::new(EditorMode::full(), buffer, None, window, cx)
12875 });
12876 let cx = &mut VisualTestContext::from_window(*window, cx);
12877 let editor = window.root(cx).unwrap();
12878 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12879
12880 window
12881 .update(cx, |editor, window, cx| {
12882 editor.cursor_offset_on_selection = true;
12883 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12884 s.select_ranges([
12885 Point::new(0, 0)..Point::new(1, 0),
12886 Point::new(3, 2)..Point::new(3, 3),
12887 Point::new(5, 6)..Point::new(6, 0),
12888 ]);
12889 });
12890 })
12891 .unwrap();
12892
12893 let (_, state) = cx.draw(
12894 point(px(500.), px(500.)),
12895 size(px(500.), px(500.)),
12896 |_, _| EditorElement::new(&editor, style),
12897 );
12898
12899 assert_eq!(state.selections.len(), 1);
12900 let local_selections = &state.selections[0].1;
12901 assert_eq!(local_selections.len(), 3);
12902 // moves cursor back one line
12903 assert_eq!(
12904 local_selections[0].head,
12905 DisplayPoint::new(DisplayRow(0), 6)
12906 );
12907 assert_eq!(
12908 local_selections[0].range,
12909 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12910 );
12911
12912 // moves cursor back one column
12913 assert_eq!(
12914 local_selections[1].range,
12915 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12916 );
12917 assert_eq!(
12918 local_selections[1].head,
12919 DisplayPoint::new(DisplayRow(3), 2)
12920 );
12921
12922 // leaves cursor on the max point
12923 assert_eq!(
12924 local_selections[2].range,
12925 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12926 );
12927 assert_eq!(
12928 local_selections[2].head,
12929 DisplayPoint::new(DisplayRow(6), 0)
12930 );
12931
12932 // active lines does not include 1 (even though the range of the selection does)
12933 assert_eq!(
12934 state.active_rows.keys().cloned().collect::<Vec<_>>(),
12935 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12936 );
12937 }
12938
12939 #[gpui::test]
12940 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12941 init_test(cx, |_| {});
12942
12943 let window = cx.add_window(|window, cx| {
12944 let buffer = MultiBuffer::build_simple("", cx);
12945 Editor::new(EditorMode::full(), buffer, None, window, cx)
12946 });
12947 let cx = &mut VisualTestContext::from_window(*window, cx);
12948 let editor = window.root(cx).unwrap();
12949 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12950 window
12951 .update(cx, |editor, window, cx| {
12952 editor.set_placeholder_text("hello", window, cx);
12953 editor.insert_blocks(
12954 [BlockProperties {
12955 style: BlockStyle::Fixed,
12956 placement: BlockPlacement::Above(Anchor::min()),
12957 height: Some(3),
12958 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12959 priority: 0,
12960 }],
12961 None,
12962 cx,
12963 );
12964
12965 // Blur the editor so that it displays placeholder text.
12966 window.blur();
12967 })
12968 .unwrap();
12969
12970 let (_, state) = cx.draw(
12971 point(px(500.), px(500.)),
12972 size(px(500.), px(500.)),
12973 |_, _| EditorElement::new(&editor, style),
12974 );
12975 assert_eq!(state.position_map.line_layouts.len(), 4);
12976 assert_eq!(state.line_numbers.len(), 1);
12977 assert_eq!(
12978 state
12979 .line_numbers
12980 .get(&MultiBufferRow(0))
12981 .map(|line_number| line_number
12982 .segments
12983 .first()
12984 .unwrap()
12985 .shaped_line
12986 .text
12987 .as_ref()),
12988 Some("1")
12989 );
12990 }
12991
12992 #[gpui::test]
12993 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12994 const TAB_SIZE: u32 = 4;
12995
12996 let input_text = "\t \t|\t| a b";
12997 let expected_invisibles = vec![
12998 Invisible::Tab {
12999 line_start_offset: 0,
13000 line_end_offset: TAB_SIZE as usize,
13001 },
13002 Invisible::Whitespace {
13003 line_offset: TAB_SIZE as usize,
13004 },
13005 Invisible::Tab {
13006 line_start_offset: TAB_SIZE as usize + 1,
13007 line_end_offset: TAB_SIZE as usize * 2,
13008 },
13009 Invisible::Tab {
13010 line_start_offset: TAB_SIZE as usize * 2 + 1,
13011 line_end_offset: TAB_SIZE as usize * 3,
13012 },
13013 Invisible::Whitespace {
13014 line_offset: TAB_SIZE as usize * 3 + 1,
13015 },
13016 Invisible::Whitespace {
13017 line_offset: TAB_SIZE as usize * 3 + 3,
13018 },
13019 ];
13020 assert_eq!(
13021 expected_invisibles.len(),
13022 input_text
13023 .chars()
13024 .filter(|initial_char| initial_char.is_whitespace())
13025 .count(),
13026 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13027 );
13028
13029 for show_line_numbers in [true, false] {
13030 init_test(cx, |s| {
13031 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13032 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
13033 });
13034
13035 let actual_invisibles = collect_invisibles_from_new_editor(
13036 cx,
13037 EditorMode::full(),
13038 input_text,
13039 px(500.0),
13040 show_line_numbers,
13041 );
13042
13043 assert_eq!(expected_invisibles, actual_invisibles);
13044 }
13045 }
13046
13047 #[gpui::test]
13048 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
13049 init_test(cx, |s| {
13050 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13051 s.defaults.tab_size = NonZeroU32::new(4);
13052 });
13053
13054 for editor_mode_without_invisibles in [
13055 EditorMode::SingleLine,
13056 EditorMode::AutoHeight {
13057 min_lines: 1,
13058 max_lines: Some(100),
13059 },
13060 ] {
13061 for show_line_numbers in [true, false] {
13062 let invisibles = collect_invisibles_from_new_editor(
13063 cx,
13064 editor_mode_without_invisibles.clone(),
13065 "\t\t\t| | a b",
13066 px(500.0),
13067 show_line_numbers,
13068 );
13069 assert!(
13070 invisibles.is_empty(),
13071 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
13072 );
13073 }
13074 }
13075 }
13076
13077 #[gpui::test]
13078 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
13079 let tab_size = 4;
13080 let input_text = "a\tbcd ".repeat(9);
13081 let repeated_invisibles = [
13082 Invisible::Tab {
13083 line_start_offset: 1,
13084 line_end_offset: tab_size as usize,
13085 },
13086 Invisible::Whitespace {
13087 line_offset: tab_size as usize + 3,
13088 },
13089 Invisible::Whitespace {
13090 line_offset: tab_size as usize + 4,
13091 },
13092 Invisible::Whitespace {
13093 line_offset: tab_size as usize + 5,
13094 },
13095 Invisible::Whitespace {
13096 line_offset: tab_size as usize + 6,
13097 },
13098 Invisible::Whitespace {
13099 line_offset: tab_size as usize + 7,
13100 },
13101 ];
13102 let expected_invisibles = std::iter::once(repeated_invisibles)
13103 .cycle()
13104 .take(9)
13105 .flatten()
13106 .collect::<Vec<_>>();
13107 assert_eq!(
13108 expected_invisibles.len(),
13109 input_text
13110 .chars()
13111 .filter(|initial_char| initial_char.is_whitespace())
13112 .count(),
13113 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
13114 );
13115 info!("Expected invisibles: {expected_invisibles:?}");
13116
13117 init_test(cx, |_| {});
13118
13119 // Put the same string with repeating whitespace pattern into editors of various size,
13120 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
13121 let resize_step = 10.0;
13122 let mut editor_width = 200.0;
13123 while editor_width <= 1000.0 {
13124 for show_line_numbers in [true, false] {
13125 update_test_language_settings(cx, &|s| {
13126 s.defaults.tab_size = NonZeroU32::new(tab_size);
13127 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
13128 s.defaults.preferred_line_length = Some(editor_width as u32);
13129 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
13130 });
13131
13132 let actual_invisibles = collect_invisibles_from_new_editor(
13133 cx,
13134 EditorMode::full(),
13135 &input_text,
13136 px(editor_width),
13137 show_line_numbers,
13138 );
13139
13140 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
13141 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
13142 let mut i = 0;
13143 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
13144 i = actual_index;
13145 match expected_invisibles.get(i) {
13146 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
13147 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
13148 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
13149 _ => {
13150 panic!(
13151 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
13152 )
13153 }
13154 },
13155 None => {
13156 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
13157 }
13158 }
13159 }
13160 let missing_expected_invisibles = &expected_invisibles[i + 1..];
13161 assert!(
13162 missing_expected_invisibles.is_empty(),
13163 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
13164 );
13165
13166 editor_width += resize_step;
13167 }
13168 }
13169 }
13170
13171 fn collect_invisibles_from_new_editor(
13172 cx: &mut TestAppContext,
13173 editor_mode: EditorMode,
13174 input_text: &str,
13175 editor_width: Pixels,
13176 show_line_numbers: bool,
13177 ) -> Vec<Invisible> {
13178 info!(
13179 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
13180 f32::from(editor_width)
13181 );
13182 let window = cx.add_window(|window, cx| {
13183 let buffer = MultiBuffer::build_simple(input_text, cx);
13184 Editor::new(editor_mode, buffer, None, window, cx)
13185 });
13186 let cx = &mut VisualTestContext::from_window(*window, cx);
13187 let editor = window.root(cx).unwrap();
13188
13189 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
13190 window
13191 .update(cx, |editor, _, cx| {
13192 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
13193 editor.set_wrap_width(Some(editor_width), cx);
13194 editor.set_show_line_numbers(show_line_numbers, cx);
13195 })
13196 .unwrap();
13197 let (_, state) = cx.draw(
13198 point(px(500.), px(500.)),
13199 size(px(500.), px(500.)),
13200 |_, _| EditorElement::new(&editor, style),
13201 );
13202 state
13203 .position_map
13204 .line_layouts
13205 .iter()
13206 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
13207 .cloned()
13208 .collect()
13209 }
13210
13211 #[gpui::test]
13212 fn test_merge_overlapping_ranges() {
13213 let base_bg = Hsla::white();
13214 let color1 = Hsla {
13215 h: 0.0,
13216 s: 0.5,
13217 l: 0.5,
13218 a: 0.5,
13219 };
13220 let color2 = Hsla {
13221 h: 120.0,
13222 s: 0.5,
13223 l: 0.5,
13224 a: 0.5,
13225 };
13226
13227 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
13228 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
13229 v.iter()
13230 .map(|(r, _)| (r.start.column(), r.end.column()))
13231 .collect()
13232 };
13233
13234 // Test overlapping ranges blend colors
13235 let overlapping = vec![
13236 (display_point(5)..display_point(15), color1),
13237 (display_point(10)..display_point(20), color2),
13238 ];
13239 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
13240 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13241
13242 // Test middle segment should have blended color
13243 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
13244 assert_eq!(result[1].1, blended);
13245
13246 // Test adjacent same-color ranges merge
13247 let adjacent_same = vec![
13248 (display_point(5)..display_point(10), color1),
13249 (display_point(10)..display_point(15), color1),
13250 ];
13251 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
13252 assert_eq!(cols(&result), vec![(5, 15)]);
13253
13254 // Test contained range splits
13255 let contained = vec![
13256 (display_point(5)..display_point(20), color1),
13257 (display_point(10)..display_point(15), color2),
13258 ];
13259 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
13260 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
13261
13262 // Test multiple overlaps split at every boundary
13263 let color3 = Hsla {
13264 h: 240.0,
13265 s: 0.5,
13266 l: 0.5,
13267 a: 0.5,
13268 };
13269 let complex = vec![
13270 (display_point(5)..display_point(12), color1),
13271 (display_point(8)..display_point(16), color2),
13272 (display_point(10)..display_point(14), color3),
13273 ];
13274 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
13275 assert_eq!(
13276 cols(&result),
13277 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
13278 );
13279 }
13280
13281 #[gpui::test]
13282 fn test_bg_segments_per_row() {
13283 let base_bg = Hsla::white();
13284
13285 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
13286 {
13287 let selection_color = Hsla {
13288 h: 200.0,
13289 s: 0.5,
13290 l: 0.5,
13291 a: 0.5,
13292 };
13293 let player_color = PlayerColor {
13294 cursor: selection_color,
13295 background: selection_color,
13296 selection: selection_color,
13297 };
13298
13299 let spanning_selection = SelectionLayout {
13300 head: DisplayPoint::new(DisplayRow(3), 7),
13301 cursor_shape: CursorShape::Bar,
13302 is_newest: true,
13303 is_local: true,
13304 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
13305 active_rows: DisplayRow(1)..DisplayRow(4),
13306 user_name: None,
13307 };
13308
13309 let selections = vec![(player_color, vec![spanning_selection])];
13310 let result = EditorElement::bg_segments_per_row(
13311 DisplayRow(0)..DisplayRow(5),
13312 &selections,
13313 &[],
13314 base_bg,
13315 );
13316
13317 assert_eq!(result.len(), 5);
13318 assert!(result[0].is_empty());
13319 assert_eq!(result[1].len(), 1);
13320 assert_eq!(result[2].len(), 1);
13321 assert_eq!(result[3].len(), 1);
13322 assert!(result[4].is_empty());
13323
13324 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13325 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13326 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13327 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13328 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13329 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13330 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
13331 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
13332 }
13333
13334 // Case B: selection ends exactly at the start of row 3, excluding row 3
13335 {
13336 let selection_color = Hsla {
13337 h: 120.0,
13338 s: 0.5,
13339 l: 0.5,
13340 a: 0.5,
13341 };
13342 let player_color = PlayerColor {
13343 cursor: selection_color,
13344 background: selection_color,
13345 selection: selection_color,
13346 };
13347
13348 let selection = SelectionLayout {
13349 head: DisplayPoint::new(DisplayRow(2), 0),
13350 cursor_shape: CursorShape::Bar,
13351 is_newest: true,
13352 is_local: true,
13353 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
13354 active_rows: DisplayRow(1)..DisplayRow(3),
13355 user_name: None,
13356 };
13357
13358 let selections = vec![(player_color, vec![selection])];
13359 let result = EditorElement::bg_segments_per_row(
13360 DisplayRow(0)..DisplayRow(4),
13361 &selections,
13362 &[],
13363 base_bg,
13364 );
13365
13366 assert_eq!(result.len(), 4);
13367 assert!(result[0].is_empty());
13368 assert_eq!(result[1].len(), 1);
13369 assert_eq!(result[2].len(), 1);
13370 assert!(result[3].is_empty());
13371
13372 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
13373 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
13374 assert_eq!(result[1][0].0.end.column(), u32::MAX);
13375 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
13376 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
13377 assert_eq!(result[2][0].0.end.column(), u32::MAX);
13378 }
13379 }
13380
13381 #[cfg(test)]
13382 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
13383 TextRun {
13384 len,
13385 color,
13386 ..Default::default()
13387 }
13388 }
13389
13390 #[gpui::test]
13391 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
13392 init_test(cx, |_| {});
13393
13394 let dx = |start: u32, end: u32| {
13395 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
13396 };
13397
13398 let text_color = Hsla {
13399 h: 210.0,
13400 s: 0.1,
13401 l: 0.4,
13402 a: 1.0,
13403 };
13404 let bg_1 = Hsla {
13405 h: 30.0,
13406 s: 0.6,
13407 l: 0.8,
13408 a: 1.0,
13409 };
13410 let bg_2 = Hsla {
13411 h: 200.0,
13412 s: 0.6,
13413 l: 0.2,
13414 a: 1.0,
13415 };
13416 let min_contrast = 45.0;
13417 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
13418 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
13419
13420 // Case A: single run; disjoint segments inside the run
13421 {
13422 let runs = vec![generate_test_run(20, text_color)];
13423 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
13424 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13425 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
13426 assert_eq!(
13427 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13428 vec![5, 5, 2, 4, 4]
13429 );
13430 assert_eq!(out[0].color, text_color);
13431 assert_eq!(out[1].color, adjusted_bg1);
13432 assert_eq!(out[2].color, text_color);
13433 assert_eq!(out[3].color, adjusted_bg2);
13434 assert_eq!(out[4].color, text_color);
13435 }
13436
13437 // Case B: multiple runs; segment extends to end of line (u32::MAX)
13438 {
13439 let runs = vec![
13440 generate_test_run(8, text_color),
13441 generate_test_run(7, text_color),
13442 ];
13443 let segs = vec![(dx(6, u32::MAX), bg_1)];
13444 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13445 // Expected slices across runs: [0,6) [6,8) | [0,7)
13446 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
13447 assert_eq!(out[0].color, text_color);
13448 assert_eq!(out[1].color, adjusted_bg1);
13449 assert_eq!(out[2].color, adjusted_bg1);
13450 }
13451
13452 // Case C: multi-byte characters
13453 {
13454 // for text: "Hello π δΈη!"
13455 let runs = vec![
13456 generate_test_run(5, text_color), // "Hello"
13457 generate_test_run(6, text_color), // " π "
13458 generate_test_run(6, text_color), // "δΈη"
13459 generate_test_run(1, text_color), // "!"
13460 ];
13461 // selecting "π δΈ"
13462 let segs = vec![(dx(6, 14), bg_1)];
13463 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13464 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
13465 assert_eq!(
13466 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13467 vec![5, 1, 5, 3, 3, 1]
13468 );
13469 assert_eq!(out[0].color, text_color); // "Hello"
13470 assert_eq!(out[2].color, adjusted_bg1); // "π "
13471 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
13472 assert_eq!(out[4].color, text_color); // "η"
13473 assert_eq!(out[5].color, text_color); // "!"
13474 }
13475
13476 // Case D: split multiple consecutive text runs with segments
13477 {
13478 let segs = vec![
13479 (dx(2, 4), bg_1), // selecting "cd"
13480 (dx(4, 8), bg_2), // selecting "efgh"
13481 (dx(9, 11), bg_1), // selecting "jk"
13482 (dx(12, 16), bg_2), // selecting "mnop"
13483 (dx(18, 19), bg_1), // selecting "s"
13484 ];
13485
13486 // for text: "abcdef"
13487 let runs = vec![
13488 generate_test_run(2, text_color), // ab
13489 generate_test_run(4, text_color), // cdef
13490 ];
13491 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
13492 // new splits "ab", "cd", "ef"
13493 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
13494 assert_eq!(out[0].color, text_color);
13495 assert_eq!(out[1].color, adjusted_bg1);
13496 assert_eq!(out[2].color, adjusted_bg2);
13497
13498 // for text: "ghijklmn"
13499 let runs = vec![
13500 generate_test_run(3, text_color), // ghi
13501 generate_test_run(2, text_color), // jk
13502 generate_test_run(3, text_color), // lmn
13503 ];
13504 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
13505 // new splits "gh", "i", "jk", "l", "mn"
13506 assert_eq!(
13507 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13508 vec![2, 1, 2, 1, 2]
13509 );
13510 assert_eq!(out[0].color, adjusted_bg2);
13511 assert_eq!(out[1].color, text_color);
13512 assert_eq!(out[2].color, adjusted_bg1);
13513 assert_eq!(out[3].color, text_color);
13514 assert_eq!(out[4].color, adjusted_bg2);
13515
13516 // for text: "opqrs"
13517 let runs = vec![
13518 generate_test_run(1, text_color), // o
13519 generate_test_run(4, text_color), // pqrs
13520 ];
13521 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
13522 // new splits "o", "p", "qr", "s"
13523 assert_eq!(
13524 out.iter().map(|r| r.len).collect::<Vec<_>>(),
13525 vec![1, 1, 2, 1]
13526 );
13527 assert_eq!(out[0].color, adjusted_bg2);
13528 assert_eq!(out[1].color, adjusted_bg2);
13529 assert_eq!(out[2].color, text_color);
13530 assert_eq!(out[3].color, adjusted_bg1);
13531 }
13532 }
13533
13534 #[test]
13535 fn test_spacer_pattern_period() {
13536 // line height is smaller than target height, so we just return half the line height
13537 assert_eq!(EditorElement::spacer_pattern_period(10.0, 20.0), 5.0);
13538
13539 // line height is exactly half the target height, perfect match
13540 assert_eq!(EditorElement::spacer_pattern_period(20.0, 10.0), 10.0);
13541
13542 // line height is close to half the target height
13543 assert_eq!(EditorElement::spacer_pattern_period(20.0, 9.0), 10.0);
13544
13545 // line height is close to 1/4 the target height
13546 assert_eq!(EditorElement::spacer_pattern_period(20.0, 4.8), 5.0);
13547 }
13548
13549 #[gpui::test(iterations = 100)]
13550 fn test_random_spacer_pattern_period(mut rng: StdRng) {
13551 let line_height = rng.next_u32() as f32;
13552 let target_height = rng.next_u32() as f32;
13553
13554 let result = EditorElement::spacer_pattern_period(line_height, target_height);
13555
13556 let k = line_height / result;
13557 assert!(k - k.round() < 0.0000001); // approximately integer
13558 assert!((k.round() as u32).is_multiple_of(2));
13559 }
13560
13561 #[test]
13562 fn test_calculate_wrap_width() {
13563 let editor_width = px(800.0);
13564 let em_width = px(8.0);
13565
13566 assert_eq!(
13567 calculate_wrap_width(SoftWrap::GitDiff, editor_width, em_width),
13568 None,
13569 );
13570
13571 assert_eq!(
13572 calculate_wrap_width(SoftWrap::None, editor_width, em_width),
13573 Some(px((MAX_LINE_LEN as f32 / 2.0 * 8.0).ceil())),
13574 );
13575
13576 assert_eq!(
13577 calculate_wrap_width(SoftWrap::EditorWidth, editor_width, em_width),
13578 Some(px(800.0)),
13579 );
13580
13581 assert_eq!(
13582 calculate_wrap_width(SoftWrap::Column(72), editor_width, em_width),
13583 Some(px((72.0 * 8.0_f32).ceil())),
13584 );
13585
13586 assert_eq!(
13587 calculate_wrap_width(SoftWrap::Bounded(72), editor_width, em_width),
13588 Some(px((72.0 * 8.0_f32).ceil())),
13589 );
13590 assert_eq!(
13591 calculate_wrap_width(SoftWrap::Bounded(200), px(400.0), em_width),
13592 Some(px(400.0)),
13593 );
13594 }
13595}