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