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