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