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