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