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