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