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