1use crate::{
2 code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
3 commit_tooltip::{blame_entry_relative_timestamp, CommitTooltip, ParsedCommitMessage},
4 display_map::{
5 Block, BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint,
6 },
7 editor_settings::{
8 CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ScrollBeyondLastLine,
9 ScrollbarDiagnostics, ShowScrollbar,
10 },
11 git::blame::GitBlame,
12 hover_popover::{
13 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
14 },
15 items::BufferSearchHighlights,
16 mouse_context_menu::{self, MenuPosition, MouseContextMenu},
17 scroll::{axis_pair, scroll_amount::ScrollAmount, AxisPair},
18 AcceptEditPrediction, BlockId, ChunkReplacement, CursorShape, CustomBlockId, DisplayPoint,
19 DisplayRow, DocumentHighlightRead, DocumentHighlightWrite, EditDisplayMode, Editor, EditorMode,
20 EditorSettings, EditorSnapshot, EditorStyle, ExpandExcerpts, FocusedBlock, GoToHunk,
21 GoToPrevHunk, GutterDimensions, HalfPageDown, HalfPageUp, HandleInput, HoveredCursor,
22 InlineCompletion, JumpData, LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point,
23 RevertSelectedHunks, RowExt, RowRangeExt, SelectPhase, Selection, SoftWrap,
24 StickyHeaderExcerpt, ToPoint, ToggleFold, CURSORS_VISIBLE_FOR,
25 EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT, FILE_HEADER_HEIGHT,
26 GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED, MAX_LINE_LEN, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
27};
28use buffer_diff::{DiffHunkSecondaryStatus, DiffHunkStatus};
29use client::ParticipantIndex;
30use collections::{BTreeMap, HashMap, HashSet};
31use file_icons::FileIcons;
32use git::{blame::BlameEntry, Oid};
33use gpui::{
34 anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline, pattern_slash,
35 point, px, quad, relative, size, svg, transparent_black, Action, AnyElement, App,
36 AvailableSpace, Axis, Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners,
37 CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable as _,
38 FontId, GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement,
39 KeyBindingContextPredicate, Keystroke, Length, ModifiersChangedEvent, MouseButton,
40 MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, ParentElement, Pixels, ScrollDelta,
41 ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveElement, Style, Styled,
42 Subscription, TextRun, TextStyleRefinement, WeakEntity, Window,
43};
44use itertools::Itertools;
45use language::{
46 language_settings::{
47 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings,
48 ShowWhitespaceSetting,
49 },
50 ChunkRendererContext,
51};
52use lsp::DiagnosticSeverity;
53use multi_buffer::{
54 Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow,
55 RowInfo, ToOffset,
56};
57use project::project_settings::{GitGutterSetting, ProjectSettings};
58use settings::{KeyBindingValidator, KeyBindingValidatorRegistration, Settings};
59use smallvec::{smallvec, SmallVec};
60use std::{
61 any::TypeId,
62 borrow::Cow,
63 cmp::{self, Ordering},
64 fmt::{self, Write},
65 iter, mem,
66 ops::{Deref, Range},
67 rc::Rc,
68 sync::Arc,
69};
70use sum_tree::Bias;
71use text::BufferId;
72use theme::{ActiveTheme, Appearance, PlayerColor};
73use ui::{
74 h_flex, prelude::*, ButtonLike, ButtonStyle, ContextMenu, IconButtonShape, KeyBinding, Tooltip,
75 POPOVER_Y_PADDING,
76};
77use unicode_segmentation::UnicodeSegmentation;
78use util::{markdown::MarkdownString, RangeExt, ResultExt};
79use workspace::{item::Item, notifications::NotifyTaskExt, Workspace};
80
81const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 7.;
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84enum DisplayDiffHunk {
85 Folded {
86 display_row: DisplayRow,
87 },
88 Unfolded {
89 diff_base_byte_range: Range<usize>,
90 display_row_range: Range<DisplayRow>,
91 multi_buffer_range: Range<Anchor>,
92 status: DiffHunkStatus,
93 },
94}
95
96struct SelectionLayout {
97 head: DisplayPoint,
98 cursor_shape: CursorShape,
99 is_newest: bool,
100 is_local: bool,
101 range: Range<DisplayPoint>,
102 active_rows: Range<DisplayRow>,
103 user_name: Option<SharedString>,
104}
105
106impl SelectionLayout {
107 fn new<T: ToPoint + ToDisplayPoint + Clone>(
108 selection: Selection<T>,
109 line_mode: bool,
110 cursor_shape: CursorShape,
111 map: &DisplaySnapshot,
112 is_newest: bool,
113 is_local: bool,
114 user_name: Option<SharedString>,
115 ) -> Self {
116 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
117 let display_selection = point_selection.map(|p| p.to_display_point(map));
118 let mut range = display_selection.range();
119 let mut head = display_selection.head();
120 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
121 ..map.next_line_boundary(point_selection.end).1.row();
122
123 // vim visual line mode
124 if line_mode {
125 let point_range = map.expand_to_line(point_selection.range());
126 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
127 }
128
129 // any vim visual mode (including line mode)
130 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
131 && !range.is_empty()
132 && !selection.reversed
133 {
134 if head.column() > 0 {
135 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
136 } else if head.row().0 > 0 && head != map.max_point() {
137 head = map.clip_point(
138 DisplayPoint::new(
139 head.row().previous_row(),
140 map.line_len(head.row().previous_row()),
141 ),
142 Bias::Left,
143 );
144 // updating range.end is a no-op unless you're cursor is
145 // on the newline containing a multi-buffer divider
146 // in which case the clip_point may have moved the head up
147 // an additional row.
148 range.end = DisplayPoint::new(head.row().next_row(), 0);
149 active_rows.end = head.row();
150 }
151 }
152
153 Self {
154 head,
155 cursor_shape,
156 is_newest,
157 is_local,
158 range,
159 active_rows,
160 user_name,
161 }
162 }
163}
164
165pub struct EditorElement {
166 editor: Entity<Editor>,
167 style: EditorStyle,
168}
169
170type DisplayRowDelta = u32;
171
172impl EditorElement {
173 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
174
175 pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
176 Self {
177 editor: editor.clone(),
178 style,
179 }
180 }
181
182 fn register_actions(&self, window: &mut Window, cx: &mut App) {
183 let editor = &self.editor;
184 editor.update(cx, |editor, cx| {
185 for action in editor.editor_actions.borrow().values() {
186 (action)(window, cx)
187 }
188 });
189
190 crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
191 crate::clangd_ext::apply_related_actions(editor, window, cx);
192 register_action(editor, window, Editor::open_context_menu);
193 register_action(editor, window, Editor::move_left);
194 register_action(editor, window, Editor::move_right);
195 register_action(editor, window, Editor::move_down);
196 register_action(editor, window, Editor::move_down_by_lines);
197 register_action(editor, window, Editor::select_down_by_lines);
198 register_action(editor, window, Editor::move_up);
199 register_action(editor, window, Editor::move_up_by_lines);
200 register_action(editor, window, Editor::select_up_by_lines);
201 register_action(editor, window, Editor::select_page_down);
202 register_action(editor, window, Editor::select_page_up);
203 register_action(editor, window, Editor::cancel);
204 register_action(editor, window, Editor::newline);
205 register_action(editor, window, Editor::newline_above);
206 register_action(editor, window, Editor::newline_below);
207 register_action(editor, window, Editor::backspace);
208 register_action(editor, window, Editor::delete);
209 register_action(editor, window, Editor::tab);
210 register_action(editor, window, Editor::tab_prev);
211 register_action(editor, window, Editor::indent);
212 register_action(editor, window, Editor::outdent);
213 register_action(editor, window, Editor::autoindent);
214 register_action(editor, window, Editor::delete_line);
215 register_action(editor, window, Editor::join_lines);
216 register_action(editor, window, Editor::sort_lines_case_sensitive);
217 register_action(editor, window, Editor::sort_lines_case_insensitive);
218 register_action(editor, window, Editor::reverse_lines);
219 register_action(editor, window, Editor::shuffle_lines);
220 register_action(editor, window, Editor::convert_to_upper_case);
221 register_action(editor, window, Editor::convert_to_lower_case);
222 register_action(editor, window, Editor::convert_to_title_case);
223 register_action(editor, window, Editor::convert_to_snake_case);
224 register_action(editor, window, Editor::convert_to_kebab_case);
225 register_action(editor, window, Editor::convert_to_upper_camel_case);
226 register_action(editor, window, Editor::convert_to_lower_camel_case);
227 register_action(editor, window, Editor::convert_to_opposite_case);
228 register_action(editor, window, Editor::delete_to_previous_word_start);
229 register_action(editor, window, Editor::delete_to_previous_subword_start);
230 register_action(editor, window, Editor::delete_to_next_word_end);
231 register_action(editor, window, Editor::delete_to_next_subword_end);
232 register_action(editor, window, Editor::delete_to_beginning_of_line);
233 register_action(editor, window, Editor::delete_to_end_of_line);
234 register_action(editor, window, Editor::cut_to_end_of_line);
235 register_action(editor, window, Editor::duplicate_line_up);
236 register_action(editor, window, Editor::duplicate_line_down);
237 register_action(editor, window, Editor::duplicate_selection);
238 register_action(editor, window, Editor::move_line_up);
239 register_action(editor, window, Editor::move_line_down);
240 register_action(editor, window, Editor::transpose);
241 register_action(editor, window, Editor::rewrap);
242 register_action(editor, window, Editor::cut);
243 register_action(editor, window, Editor::kill_ring_cut);
244 register_action(editor, window, Editor::kill_ring_yank);
245 register_action(editor, window, Editor::copy);
246 register_action(editor, window, Editor::paste);
247 register_action(editor, window, Editor::undo);
248 register_action(editor, window, Editor::redo);
249 register_action(editor, window, Editor::move_page_up);
250 register_action(editor, window, Editor::move_page_down);
251 register_action(editor, window, Editor::next_screen);
252 register_action(editor, window, Editor::scroll_cursor_top);
253 register_action(editor, window, Editor::scroll_cursor_center);
254 register_action(editor, window, Editor::scroll_cursor_bottom);
255 register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
256 register_action(editor, window, |editor, _: &LineDown, window, cx| {
257 editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
258 });
259 register_action(editor, window, |editor, _: &LineUp, window, cx| {
260 editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
261 });
262 register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
263 editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
264 });
265 register_action(
266 editor,
267 window,
268 |editor, HandleInput(text): &HandleInput, window, cx| {
269 if text.is_empty() {
270 return;
271 }
272 editor.handle_input(text, window, cx);
273 },
274 );
275 register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
276 editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
277 });
278 register_action(editor, window, |editor, _: &PageDown, window, cx| {
279 editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
280 });
281 register_action(editor, window, |editor, _: &PageUp, window, cx| {
282 editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
283 });
284 register_action(editor, window, Editor::move_to_previous_word_start);
285 register_action(editor, window, Editor::move_to_previous_subword_start);
286 register_action(editor, window, Editor::move_to_next_word_end);
287 register_action(editor, window, Editor::move_to_next_subword_end);
288 register_action(editor, window, Editor::move_to_beginning_of_line);
289 register_action(editor, window, Editor::move_to_end_of_line);
290 register_action(editor, window, Editor::move_to_start_of_paragraph);
291 register_action(editor, window, Editor::move_to_end_of_paragraph);
292 register_action(editor, window, Editor::move_to_beginning);
293 register_action(editor, window, Editor::move_to_end);
294 register_action(editor, window, Editor::select_up);
295 register_action(editor, window, Editor::select_down);
296 register_action(editor, window, Editor::select_left);
297 register_action(editor, window, Editor::select_right);
298 register_action(editor, window, Editor::select_to_previous_word_start);
299 register_action(editor, window, Editor::select_to_previous_subword_start);
300 register_action(editor, window, Editor::select_to_next_word_end);
301 register_action(editor, window, Editor::select_to_next_subword_end);
302 register_action(editor, window, Editor::select_to_beginning_of_line);
303 register_action(editor, window, Editor::select_to_end_of_line);
304 register_action(editor, window, Editor::select_to_start_of_paragraph);
305 register_action(editor, window, Editor::select_to_end_of_paragraph);
306 register_action(editor, window, Editor::select_to_beginning);
307 register_action(editor, window, Editor::select_to_end);
308 register_action(editor, window, Editor::select_all);
309 register_action(editor, window, |editor, action, window, cx| {
310 editor.select_all_matches(action, window, cx).log_err();
311 });
312 register_action(editor, window, Editor::select_line);
313 register_action(editor, window, Editor::split_selection_into_lines);
314 register_action(editor, window, Editor::add_selection_above);
315 register_action(editor, window, Editor::add_selection_below);
316 register_action(editor, window, |editor, action, window, cx| {
317 editor.select_next(action, window, cx).log_err();
318 });
319 register_action(editor, window, |editor, action, window, cx| {
320 editor.select_previous(action, window, cx).log_err();
321 });
322 register_action(editor, window, Editor::toggle_comments);
323 register_action(editor, window, Editor::select_larger_syntax_node);
324 register_action(editor, window, Editor::select_smaller_syntax_node);
325 register_action(editor, window, Editor::select_enclosing_symbol);
326 register_action(editor, window, Editor::move_to_enclosing_bracket);
327 register_action(editor, window, Editor::undo_selection);
328 register_action(editor, window, Editor::redo_selection);
329 if !editor.read(cx).is_singleton(cx) {
330 register_action(editor, window, Editor::expand_excerpts);
331 register_action(editor, window, Editor::expand_excerpts_up);
332 register_action(editor, window, Editor::expand_excerpts_down);
333 }
334 register_action(editor, window, Editor::go_to_diagnostic);
335 register_action(editor, window, Editor::go_to_prev_diagnostic);
336 register_action(editor, window, Editor::go_to_next_hunk);
337 register_action(editor, window, Editor::go_to_prev_hunk);
338 register_action(editor, window, |editor, action, window, cx| {
339 editor
340 .go_to_definition(action, window, cx)
341 .detach_and_log_err(cx);
342 });
343 register_action(editor, window, |editor, action, window, cx| {
344 editor
345 .go_to_definition_split(action, window, cx)
346 .detach_and_log_err(cx);
347 });
348 register_action(editor, window, |editor, action, window, cx| {
349 editor
350 .go_to_declaration(action, window, cx)
351 .detach_and_log_err(cx);
352 });
353 register_action(editor, window, |editor, action, window, cx| {
354 editor
355 .go_to_declaration_split(action, window, cx)
356 .detach_and_log_err(cx);
357 });
358 register_action(editor, window, |editor, action, window, cx| {
359 editor
360 .go_to_implementation(action, window, cx)
361 .detach_and_log_err(cx);
362 });
363 register_action(editor, window, |editor, action, window, cx| {
364 editor
365 .go_to_implementation_split(action, window, cx)
366 .detach_and_log_err(cx);
367 });
368 register_action(editor, window, |editor, action, window, cx| {
369 editor
370 .go_to_type_definition(action, window, cx)
371 .detach_and_log_err(cx);
372 });
373 register_action(editor, window, |editor, action, window, cx| {
374 editor
375 .go_to_type_definition_split(action, window, cx)
376 .detach_and_log_err(cx);
377 });
378 register_action(editor, window, Editor::open_url);
379 register_action(editor, window, Editor::open_selected_filename);
380 register_action(editor, window, Editor::fold);
381 register_action(editor, window, Editor::fold_at_level);
382 register_action(editor, window, Editor::fold_all);
383 register_action(editor, window, Editor::fold_function_bodies);
384 register_action(editor, window, Editor::fold_at);
385 register_action(editor, window, Editor::fold_recursive);
386 register_action(editor, window, Editor::toggle_fold);
387 register_action(editor, window, Editor::toggle_fold_recursive);
388 register_action(editor, window, Editor::unfold_lines);
389 register_action(editor, window, Editor::unfold_recursive);
390 register_action(editor, window, Editor::unfold_all);
391 register_action(editor, window, Editor::unfold_at);
392 register_action(editor, window, Editor::fold_selected_ranges);
393 register_action(editor, window, Editor::set_mark);
394 register_action(editor, window, Editor::swap_selection_ends);
395 register_action(editor, window, Editor::show_completions);
396 register_action(editor, window, Editor::toggle_code_actions);
397 register_action(editor, window, Editor::open_excerpts);
398 register_action(editor, window, Editor::open_excerpts_in_split);
399 register_action(editor, window, Editor::open_proposed_changes_editor);
400 register_action(editor, window, Editor::toggle_soft_wrap);
401 register_action(editor, window, Editor::toggle_tab_bar);
402 register_action(editor, window, Editor::toggle_line_numbers);
403 register_action(editor, window, Editor::toggle_relative_line_numbers);
404 register_action(editor, window, Editor::toggle_indent_guides);
405 register_action(editor, window, Editor::toggle_inlay_hints);
406 register_action(editor, window, Editor::toggle_inline_completions);
407 register_action(editor, window, hover_popover::hover);
408 register_action(editor, window, Editor::reveal_in_finder);
409 register_action(editor, window, Editor::copy_path);
410 register_action(editor, window, Editor::copy_relative_path);
411 register_action(editor, window, Editor::copy_file_name);
412 register_action(editor, window, Editor::copy_file_name_without_extension);
413 register_action(editor, window, Editor::copy_highlight_json);
414 register_action(editor, window, Editor::copy_permalink_to_line);
415 register_action(editor, window, Editor::open_permalink_to_line);
416 register_action(editor, window, Editor::copy_file_location);
417 register_action(editor, window, Editor::toggle_git_blame);
418 register_action(editor, window, Editor::toggle_git_blame_inline);
419 register_action(editor, window, Editor::toggle_selected_diff_hunks);
420 register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
421 register_action(editor, window, Editor::expand_all_diff_hunks);
422
423 register_action(editor, window, |editor, action, window, cx| {
424 if let Some(task) = editor.format(action, window, cx) {
425 task.detach_and_notify_err(window, cx);
426 } else {
427 cx.propagate();
428 }
429 });
430 register_action(editor, window, |editor, action, window, cx| {
431 if let Some(task) = editor.format_selections(action, window, cx) {
432 task.detach_and_notify_err(window, cx);
433 } else {
434 cx.propagate();
435 }
436 });
437 register_action(editor, window, Editor::restart_language_server);
438 register_action(editor, window, Editor::show_character_palette);
439 register_action(editor, window, |editor, action, window, cx| {
440 if let Some(task) = editor.confirm_completion(action, window, cx) {
441 task.detach_and_notify_err(window, cx);
442 } else {
443 cx.propagate();
444 }
445 });
446 register_action(editor, window, |editor, action, window, cx| {
447 if let Some(task) = editor.compose_completion(action, window, cx) {
448 task.detach_and_notify_err(window, cx);
449 } else {
450 cx.propagate();
451 }
452 });
453 register_action(editor, window, |editor, action, window, cx| {
454 if let Some(task) = editor.confirm_code_action(action, window, cx) {
455 task.detach_and_notify_err(window, cx);
456 } else {
457 cx.propagate();
458 }
459 });
460 register_action(editor, window, |editor, action, window, cx| {
461 if let Some(task) = editor.rename(action, window, cx) {
462 task.detach_and_notify_err(window, cx);
463 } else {
464 cx.propagate();
465 }
466 });
467 register_action(editor, window, |editor, action, window, cx| {
468 if let Some(task) = editor.confirm_rename(action, window, cx) {
469 task.detach_and_notify_err(window, cx);
470 } else {
471 cx.propagate();
472 }
473 });
474 register_action(editor, window, |editor, action, window, cx| {
475 if let Some(task) = editor.find_all_references(action, window, cx) {
476 task.detach_and_log_err(cx);
477 } else {
478 cx.propagate();
479 }
480 });
481 register_action(editor, window, Editor::show_signature_help);
482 register_action(editor, window, Editor::next_edit_prediction);
483 register_action(editor, window, Editor::previous_edit_prediction);
484 register_action(editor, window, Editor::show_inline_completion);
485 register_action(editor, window, Editor::context_menu_first);
486 register_action(editor, window, Editor::context_menu_prev);
487 register_action(editor, window, Editor::context_menu_next);
488 register_action(editor, window, Editor::context_menu_last);
489 register_action(editor, window, Editor::display_cursor_names);
490 register_action(editor, window, Editor::unique_lines_case_insensitive);
491 register_action(editor, window, Editor::unique_lines_case_sensitive);
492 register_action(editor, window, Editor::accept_partial_inline_completion);
493 register_action(editor, window, Editor::accept_edit_prediction);
494 register_action(editor, window, Editor::revert_file);
495 register_action(editor, window, Editor::revert_selected_hunks);
496 register_action(editor, window, Editor::apply_all_diff_hunks);
497 register_action(editor, window, Editor::apply_selected_diff_hunks);
498 register_action(editor, window, Editor::open_active_item_in_terminal);
499 register_action(editor, window, Editor::reload_file);
500 register_action(editor, window, Editor::spawn_nearest_task);
501 register_action(editor, window, Editor::insert_uuid_v4);
502 register_action(editor, window, Editor::insert_uuid_v7);
503 register_action(editor, window, Editor::open_selections_in_multibuffer);
504 }
505
506 fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
507 let position_map = layout.position_map.clone();
508 window.on_key_event({
509 let editor = self.editor.clone();
510 move |event: &ModifiersChangedEvent, phase, window, cx| {
511 if phase != DispatchPhase::Bubble {
512 return;
513 }
514 editor.update(cx, |editor, cx| {
515 if editor.hover_state.focused(window, cx) {
516 return;
517 }
518 editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
519 })
520 }
521 });
522 }
523
524 fn mouse_left_down(
525 editor: &mut Editor,
526 event: &MouseDownEvent,
527 hovered_hunk: Option<Range<Anchor>>,
528 position_map: &PositionMap,
529 line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
530 window: &mut Window,
531 cx: &mut Context<Editor>,
532 ) {
533 if window.default_prevented() {
534 return;
535 }
536
537 let text_hitbox = &position_map.text_hitbox;
538 let gutter_hitbox = &position_map.gutter_hitbox;
539 let mut click_count = event.click_count;
540 let mut modifiers = event.modifiers;
541
542 if let Some(hovered_hunk) = hovered_hunk {
543 editor.toggle_diff_hunks_in_ranges_narrow(vec![hovered_hunk], cx);
544 cx.notify();
545 return;
546 } else if gutter_hitbox.is_hovered(window) {
547 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
548 } else if !text_hitbox.is_hovered(window) {
549 return;
550 }
551
552 let is_singleton = editor.buffer().read(cx).is_singleton();
553
554 if click_count == 2 && !is_singleton {
555 match EditorSettings::get_global(cx).double_click_in_multibuffer {
556 DoubleClickInMultibuffer::Select => {
557 // do nothing special on double click, all selection logic is below
558 }
559 DoubleClickInMultibuffer::Open => {
560 if modifiers.alt {
561 // if double click is made with alt, pretend it's a regular double click without opening and alt,
562 // and run the selection logic.
563 modifiers.alt = false;
564 } else {
565 let scroll_position_row =
566 position_map.scroll_pixel_position.y / position_map.line_height;
567 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
568 + position_map.scroll_pixel_position.y)
569 / position_map.line_height)
570 as u32;
571 let multi_buffer_row = position_map
572 .snapshot
573 .display_point_to_point(
574 DisplayPoint::new(DisplayRow(display_row), 0),
575 Bias::Right,
576 )
577 .row;
578 let line_offset_from_top = display_row - scroll_position_row as u32;
579 // if double click is made without alt, open the corresponding excerp
580 editor.open_excerpts_common(
581 Some(JumpData::MultiBufferRow {
582 row: MultiBufferRow(multi_buffer_row),
583 line_offset_from_top,
584 }),
585 false,
586 window,
587 cx,
588 );
589 return;
590 }
591 }
592 }
593 }
594
595 let point_for_position = position_map.point_for_position(event.position);
596 let position = point_for_position.previous_valid;
597 if modifiers.shift && modifiers.alt {
598 editor.select(
599 SelectPhase::BeginColumnar {
600 position,
601 reset: false,
602 goal_column: point_for_position.exact_unclipped.column(),
603 },
604 window,
605 cx,
606 );
607 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
608 {
609 editor.select(
610 SelectPhase::Extend {
611 position,
612 click_count,
613 },
614 window,
615 cx,
616 );
617 } else {
618 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
619 let multi_cursor_modifier = match multi_cursor_setting {
620 MultiCursorModifier::Alt => modifiers.alt,
621 MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
622 };
623 editor.select(
624 SelectPhase::Begin {
625 position,
626 add: multi_cursor_modifier,
627 click_count,
628 },
629 window,
630 cx,
631 );
632 }
633 cx.stop_propagation();
634
635 if !is_singleton {
636 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
637 + position_map.scroll_pixel_position.y)
638 / position_map.line_height) as u32;
639 let multi_buffer_row = position_map
640 .snapshot
641 .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
642 .row;
643 if line_numbers
644 .get(&MultiBufferRow(multi_buffer_row))
645 .and_then(|line_number| line_number.hitbox.as_ref())
646 .is_some_and(|hitbox| hitbox.contains(&event.position))
647 {
648 let scroll_position_row =
649 position_map.scroll_pixel_position.y / position_map.line_height;
650 let line_offset_from_top = display_row - scroll_position_row as u32;
651
652 editor.open_excerpts_common(
653 Some(JumpData::MultiBufferRow {
654 row: MultiBufferRow(multi_buffer_row),
655 line_offset_from_top,
656 }),
657 modifiers.alt,
658 window,
659 cx,
660 );
661 cx.stop_propagation();
662 }
663 }
664 }
665
666 fn mouse_right_down(
667 editor: &mut Editor,
668 event: &MouseDownEvent,
669 position_map: &PositionMap,
670 window: &mut Window,
671 cx: &mut Context<Editor>,
672 ) {
673 if !position_map.text_hitbox.is_hovered(window) {
674 return;
675 }
676 let point_for_position = position_map.point_for_position(event.position);
677 mouse_context_menu::deploy_context_menu(
678 editor,
679 Some(event.position),
680 point_for_position.previous_valid,
681 window,
682 cx,
683 );
684 cx.stop_propagation();
685 }
686
687 fn mouse_middle_down(
688 editor: &mut Editor,
689 event: &MouseDownEvent,
690 position_map: &PositionMap,
691 window: &mut Window,
692 cx: &mut Context<Editor>,
693 ) {
694 if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
695 return;
696 }
697
698 let point_for_position = position_map.point_for_position(event.position);
699 let position = point_for_position.previous_valid;
700
701 editor.select(
702 SelectPhase::BeginColumnar {
703 position,
704 reset: true,
705 goal_column: point_for_position.exact_unclipped.column(),
706 },
707 window,
708 cx,
709 );
710 }
711
712 fn mouse_up(
713 editor: &mut Editor,
714 event: &MouseUpEvent,
715 position_map: &PositionMap,
716 window: &mut Window,
717 cx: &mut Context<Editor>,
718 ) {
719 let text_hitbox = &position_map.text_hitbox;
720 let end_selection = editor.has_pending_selection();
721 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
722
723 if end_selection {
724 editor.select(SelectPhase::End, window, cx);
725 }
726
727 if end_selection && pending_nonempty_selections {
728 cx.stop_propagation();
729 } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
730 && event.button == MouseButton::Middle
731 {
732 if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
733 return;
734 }
735
736 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
737 if EditorSettings::get_global(cx).middle_click_paste {
738 if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
739 let point_for_position = position_map.point_for_position(event.position);
740 let position = point_for_position.previous_valid;
741
742 editor.select(
743 SelectPhase::Begin {
744 position,
745 add: false,
746 click_count: 1,
747 },
748 window,
749 cx,
750 );
751 editor.insert(&text, window, cx);
752 }
753 cx.stop_propagation()
754 }
755 }
756 }
757
758 fn click(
759 editor: &mut Editor,
760 event: &ClickEvent,
761 position_map: &PositionMap,
762 window: &mut Window,
763 cx: &mut Context<Editor>,
764 ) {
765 let text_hitbox = &position_map.text_hitbox;
766 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
767
768 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
769 let multi_cursor_modifier = match multi_cursor_setting {
770 MultiCursorModifier::Alt => event.modifiers().secondary(),
771 MultiCursorModifier::CmdOrCtrl => event.modifiers().alt,
772 };
773
774 if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(window) {
775 let point = position_map.point_for_position(event.up.position);
776 editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
777
778 cx.stop_propagation();
779 }
780 }
781
782 fn mouse_dragged(
783 editor: &mut Editor,
784 event: &MouseMoveEvent,
785 position_map: &PositionMap,
786 window: &mut Window,
787 cx: &mut Context<Editor>,
788 ) {
789 if !editor.has_pending_selection() {
790 return;
791 }
792
793 let text_bounds = position_map.text_hitbox.bounds;
794 let point_for_position = position_map.point_for_position(event.position);
795 let mut scroll_delta = gpui::Point::<f32>::default();
796 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
797 let top = text_bounds.origin.y + vertical_margin;
798 let bottom = text_bounds.bottom_left().y - vertical_margin;
799 if event.position.y < top {
800 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
801 }
802 if event.position.y > bottom {
803 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
804 }
805
806 // We need horizontal width of text
807 let style = editor.style.clone().unwrap_or_default();
808 let font_id = window.text_system().resolve_font(&style.text.font());
809 let font_size = style.text.font_size.to_pixels(window.rem_size());
810 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
811
812 let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
813
814 let scroll_space: Pixels = scroll_margin_x * em_width;
815
816 let left = text_bounds.origin.x + scroll_space;
817 let right = text_bounds.top_right().x - scroll_space;
818
819 if event.position.x < left {
820 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
821 }
822 if event.position.x > right {
823 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
824 }
825
826 editor.select(
827 SelectPhase::Update {
828 position: point_for_position.previous_valid,
829 goal_column: point_for_position.exact_unclipped.column(),
830 scroll_delta,
831 },
832 window,
833 cx,
834 );
835 }
836
837 fn mouse_moved(
838 editor: &mut Editor,
839 event: &MouseMoveEvent,
840 position_map: &PositionMap,
841 window: &mut Window,
842 cx: &mut Context<Editor>,
843 ) {
844 let text_hitbox = &position_map.text_hitbox;
845 let gutter_hitbox = &position_map.gutter_hitbox;
846 let modifiers = event.modifiers;
847 let gutter_hovered = gutter_hitbox.is_hovered(window);
848 editor.set_gutter_hovered(gutter_hovered, cx);
849
850 // Don't trigger hover popover if mouse is hovering over context menu
851 if text_hitbox.is_hovered(window) {
852 let point_for_position = position_map.point_for_position(event.position);
853
854 editor.update_hovered_link(
855 point_for_position,
856 &position_map.snapshot,
857 modifiers,
858 window,
859 cx,
860 );
861
862 if let Some(point) = point_for_position.as_valid() {
863 let anchor = position_map
864 .snapshot
865 .buffer_snapshot
866 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
867 hover_at(editor, Some(anchor), window, cx);
868 Self::update_visible_cursor(editor, point, position_map, window, cx);
869 } else {
870 hover_at(editor, None, window, cx);
871 }
872 } else {
873 editor.hide_hovered_link(cx);
874 hover_at(editor, None, window, cx);
875 if gutter_hovered {
876 cx.stop_propagation();
877 }
878 }
879 }
880
881 fn update_visible_cursor(
882 editor: &mut Editor,
883 point: DisplayPoint,
884 position_map: &PositionMap,
885 window: &mut Window,
886 cx: &mut Context<Editor>,
887 ) {
888 let snapshot = &position_map.snapshot;
889 let Some(hub) = editor.collaboration_hub() else {
890 return;
891 };
892 let start = snapshot.display_snapshot.clip_point(
893 DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
894 Bias::Left,
895 );
896 let end = snapshot.display_snapshot.clip_point(
897 DisplayPoint::new(
898 point.row(),
899 (point.column() + 1).min(snapshot.line_len(point.row())),
900 ),
901 Bias::Right,
902 );
903
904 let range = snapshot
905 .buffer_snapshot
906 .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
907 ..snapshot
908 .buffer_snapshot
909 .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
910
911 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
912 return;
913 };
914 let key = crate::HoveredCursor {
915 replica_id: selection.replica_id,
916 selection_id: selection.selection.id,
917 };
918 editor.hovered_cursors.insert(
919 key.clone(),
920 cx.spawn_in(window, |editor, mut cx| async move {
921 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
922 editor
923 .update(&mut cx, |editor, cx| {
924 editor.hovered_cursors.remove(&key);
925 cx.notify();
926 })
927 .ok();
928 }),
929 );
930 cx.notify()
931 }
932
933 #[allow(clippy::too_many_arguments)]
934 fn layout_selections(
935 &self,
936 start_anchor: Anchor,
937 end_anchor: Anchor,
938 local_selections: &[Selection<Point>],
939 snapshot: &EditorSnapshot,
940 start_row: DisplayRow,
941 end_row: DisplayRow,
942 window: &mut Window,
943 cx: &mut App,
944 ) -> (
945 Vec<(PlayerColor, Vec<SelectionLayout>)>,
946 BTreeMap<DisplayRow, bool>,
947 Option<DisplayPoint>,
948 ) {
949 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
950 let mut active_rows = BTreeMap::new();
951 let mut newest_selection_head = None;
952 self.editor.update(cx, |editor, cx| {
953 if editor.show_local_selections {
954 let mut layouts = Vec::new();
955 let newest = editor.selections.newest(cx);
956 for selection in local_selections.iter().cloned() {
957 let is_empty = selection.start == selection.end;
958 let is_newest = selection == newest;
959
960 let layout = SelectionLayout::new(
961 selection,
962 editor.selections.line_mode,
963 editor.cursor_shape,
964 &snapshot.display_snapshot,
965 is_newest,
966 editor.leader_peer_id.is_none(),
967 None,
968 );
969 if is_newest {
970 newest_selection_head = Some(layout.head);
971 }
972
973 for row in cmp::max(layout.active_rows.start.0, start_row.0)
974 ..=cmp::min(layout.active_rows.end.0, end_row.0)
975 {
976 let contains_non_empty_selection =
977 active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
978 *contains_non_empty_selection |= !is_empty;
979 }
980 layouts.push(layout);
981 }
982
983 let player = editor.current_user_player_color(cx);
984 selections.push((player, layouts));
985 }
986
987 if let Some(collaboration_hub) = &editor.collaboration_hub {
988 // When following someone, render the local selections in their color.
989 if let Some(leader_id) = editor.leader_peer_id {
990 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id)
991 {
992 if let Some(participant_index) = collaboration_hub
993 .user_participant_indices(cx)
994 .get(&collaborator.user_id)
995 {
996 if let Some((local_selection_style, _)) = selections.first_mut() {
997 *local_selection_style = cx
998 .theme()
999 .players()
1000 .color_for_participant(participant_index.0);
1001 }
1002 }
1003 }
1004 }
1005
1006 let mut remote_selections = HashMap::default();
1007 for selection in snapshot.remote_selections_in_range(
1008 &(start_anchor..end_anchor),
1009 collaboration_hub.as_ref(),
1010 cx,
1011 ) {
1012 let selection_style =
1013 Self::get_participant_color(selection.participant_index, cx);
1014
1015 // Don't re-render the leader's selections, since the local selections
1016 // match theirs.
1017 if Some(selection.peer_id) == editor.leader_peer_id {
1018 continue;
1019 }
1020 let key = HoveredCursor {
1021 replica_id: selection.replica_id,
1022 selection_id: selection.selection.id,
1023 };
1024
1025 let is_shown =
1026 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
1027
1028 remote_selections
1029 .entry(selection.replica_id)
1030 .or_insert((selection_style, Vec::new()))
1031 .1
1032 .push(SelectionLayout::new(
1033 selection.selection,
1034 selection.line_mode,
1035 selection.cursor_shape,
1036 &snapshot.display_snapshot,
1037 false,
1038 false,
1039 if is_shown { selection.user_name } else { None },
1040 ));
1041 }
1042
1043 selections.extend(remote_selections.into_values());
1044 } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
1045 let layouts = snapshot
1046 .buffer_snapshot
1047 .selections_in_range(&(start_anchor..end_anchor), true)
1048 .map(move |(_, line_mode, cursor_shape, selection)| {
1049 SelectionLayout::new(
1050 selection,
1051 line_mode,
1052 cursor_shape,
1053 &snapshot.display_snapshot,
1054 false,
1055 false,
1056 None,
1057 )
1058 })
1059 .collect::<Vec<_>>();
1060 let player = editor.current_user_player_color(cx);
1061 selections.push((player, layouts));
1062 }
1063 });
1064 (selections, active_rows, newest_selection_head)
1065 }
1066
1067 fn collect_cursors(
1068 &self,
1069 snapshot: &EditorSnapshot,
1070 cx: &mut App,
1071 ) -> Vec<(DisplayPoint, Hsla)> {
1072 let editor = self.editor.read(cx);
1073 let mut cursors = Vec::new();
1074 let mut skip_local = false;
1075 let mut add_cursor = |anchor: Anchor, color| {
1076 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
1077 };
1078 // Remote cursors
1079 if let Some(collaboration_hub) = &editor.collaboration_hub {
1080 for remote_selection in snapshot.remote_selections_in_range(
1081 &(Anchor::min()..Anchor::max()),
1082 collaboration_hub.deref(),
1083 cx,
1084 ) {
1085 let color = Self::get_participant_color(remote_selection.participant_index, cx);
1086 add_cursor(remote_selection.selection.head(), color.cursor);
1087 if Some(remote_selection.peer_id) == editor.leader_peer_id {
1088 skip_local = true;
1089 }
1090 }
1091 }
1092 // Local cursors
1093 if !skip_local {
1094 let color = cx.theme().players().local().cursor;
1095 editor.selections.disjoint.iter().for_each(|selection| {
1096 add_cursor(selection.head(), color);
1097 });
1098 if let Some(ref selection) = editor.selections.pending_anchor() {
1099 add_cursor(selection.head(), color);
1100 }
1101 }
1102 cursors
1103 }
1104
1105 #[allow(clippy::too_many_arguments)]
1106 fn layout_visible_cursors(
1107 &self,
1108 snapshot: &EditorSnapshot,
1109 selections: &[(PlayerColor, Vec<SelectionLayout>)],
1110 block_start_rows: &HashSet<DisplayRow>,
1111 visible_display_row_range: Range<DisplayRow>,
1112 line_layouts: &[LineWithInvisibles],
1113 text_hitbox: &Hitbox,
1114 content_origin: gpui::Point<Pixels>,
1115 scroll_position: gpui::Point<f32>,
1116 scroll_pixel_position: gpui::Point<Pixels>,
1117 line_height: Pixels,
1118 em_width: Pixels,
1119 em_advance: Pixels,
1120 autoscroll_containing_element: bool,
1121 window: &mut Window,
1122 cx: &mut App,
1123 ) -> Vec<CursorLayout> {
1124 let mut autoscroll_bounds = None;
1125 let cursor_layouts = self.editor.update(cx, |editor, cx| {
1126 let mut cursors = Vec::new();
1127
1128 let show_local_cursors = editor.show_local_cursors(window, cx);
1129
1130 for (player_color, selections) in selections {
1131 for selection in selections {
1132 let cursor_position = selection.head;
1133
1134 let in_range = visible_display_row_range.contains(&cursor_position.row());
1135 if (selection.is_local && !show_local_cursors)
1136 || !in_range
1137 || block_start_rows.contains(&cursor_position.row())
1138 {
1139 continue;
1140 }
1141
1142 let cursor_row_layout = &line_layouts
1143 [cursor_position.row().minus(visible_display_row_range.start) as usize];
1144 let cursor_column = cursor_position.column() as usize;
1145
1146 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
1147 let mut block_width =
1148 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
1149 if block_width == Pixels::ZERO {
1150 block_width = em_advance;
1151 }
1152 let block_text = if let CursorShape::Block = selection.cursor_shape {
1153 snapshot
1154 .grapheme_at(cursor_position)
1155 .or_else(|| {
1156 if cursor_column == 0 {
1157 snapshot.placeholder_text().and_then(|s| {
1158 s.graphemes(true).next().map(|s| s.to_string().into())
1159 })
1160 } else {
1161 None
1162 }
1163 })
1164 .and_then(|text| {
1165 let len = text.len();
1166
1167 let font = cursor_row_layout
1168 .font_id_for_index(cursor_column)
1169 .and_then(|cursor_font_id| {
1170 window.text_system().get_font_for_id(cursor_font_id)
1171 })
1172 .unwrap_or(self.style.text.font());
1173
1174 // Invert the text color for the block cursor. Ensure that the text
1175 // color is opaque enough to be visible against the background color.
1176 //
1177 // 0.75 is an arbitrary threshold to determine if the background color is
1178 // opaque enough to use as a text color.
1179 //
1180 // TODO: In the future we should ensure themes have a `text_inverse` color.
1181 let color = if cx.theme().colors().editor_background.a < 0.75 {
1182 match cx.theme().appearance {
1183 Appearance::Dark => Hsla::black(),
1184 Appearance::Light => Hsla::white(),
1185 }
1186 } else {
1187 cx.theme().colors().editor_background
1188 };
1189
1190 window
1191 .text_system()
1192 .shape_line(
1193 text,
1194 cursor_row_layout.font_size,
1195 &[TextRun {
1196 len,
1197 font,
1198 color,
1199 background_color: None,
1200 strikethrough: None,
1201 underline: None,
1202 }],
1203 )
1204 .log_err()
1205 })
1206 } else {
1207 None
1208 };
1209
1210 let x = cursor_character_x - scroll_pixel_position.x;
1211 let y = (cursor_position.row().as_f32()
1212 - scroll_pixel_position.y / line_height)
1213 * line_height;
1214 if selection.is_newest {
1215 editor.pixel_position_of_newest_cursor = Some(point(
1216 text_hitbox.origin.x + x + block_width / 2.,
1217 text_hitbox.origin.y + y + line_height / 2.,
1218 ));
1219
1220 if autoscroll_containing_element {
1221 let top = text_hitbox.origin.y
1222 + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1223 * line_height;
1224 let left = text_hitbox.origin.x
1225 + (cursor_position.column() as f32 - scroll_position.x - 3.)
1226 .max(0.)
1227 * em_width;
1228
1229 let bottom = text_hitbox.origin.y
1230 + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1231 * line_height;
1232 let right = text_hitbox.origin.x
1233 + (cursor_position.column() as f32 - scroll_position.x + 4.)
1234 * em_width;
1235
1236 autoscroll_bounds =
1237 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1238 }
1239 }
1240
1241 let mut cursor = CursorLayout {
1242 color: player_color.cursor,
1243 block_width,
1244 origin: point(x, y),
1245 line_height,
1246 shape: selection.cursor_shape,
1247 block_text,
1248 cursor_name: None,
1249 };
1250 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1251 string: name,
1252 color: self.style.background,
1253 is_top_row: cursor_position.row().0 == 0,
1254 });
1255 cursor.layout(content_origin, cursor_name, window, cx);
1256 cursors.push(cursor);
1257 }
1258 }
1259
1260 cursors
1261 });
1262
1263 if let Some(bounds) = autoscroll_bounds {
1264 window.request_autoscroll(bounds);
1265 }
1266
1267 cursor_layouts
1268 }
1269
1270 fn layout_scrollbars(
1271 &self,
1272 snapshot: &EditorSnapshot,
1273 scrollbar_range_data: ScrollbarRangeData,
1274 scroll_position: gpui::Point<f32>,
1275 non_visible_cursors: bool,
1276 window: &mut Window,
1277 cx: &mut App,
1278 ) -> AxisPair<Option<ScrollbarLayout>> {
1279 let letter_size = scrollbar_range_data.letter_size;
1280 let text_units_per_page = axis_pair(
1281 scrollbar_range_data.scrollbar_bounds.size.width / letter_size.width,
1282 scrollbar_range_data.scrollbar_bounds.size.height / letter_size.height,
1283 );
1284
1285 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1286 let show_scrollbars = self.editor.read(cx).show_scrollbars
1287 && match scrollbar_settings.show {
1288 ShowScrollbar::Auto => {
1289 let editor = self.editor.read(cx);
1290 let is_singleton = editor.is_singleton(cx);
1291 // Git
1292 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_diff_hunks())
1293 ||
1294 // Buffer Search Results
1295 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1296 ||
1297 // Selected Symbol Occurrences
1298 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1299 ||
1300 // Diagnostics
1301 (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot.has_diagnostics())
1302 ||
1303 // Cursors out of sight
1304 non_visible_cursors
1305 ||
1306 // Scrollmanager
1307 editor.scroll_manager.scrollbars_visible()
1308 }
1309 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1310 ShowScrollbar::Always => true,
1311 ShowScrollbar::Never => false,
1312 };
1313
1314 let axes: AxisPair<bool> = scrollbar_settings.axes.into();
1315
1316 if snapshot.mode != EditorMode::Full {
1317 return axis_pair(None, None);
1318 }
1319
1320 let visible_range = axis_pair(
1321 axes.horizontal
1322 .then(|| scroll_position.x..scroll_position.x + text_units_per_page.horizontal),
1323 axes.vertical
1324 .then(|| scroll_position.y..scroll_position.y + text_units_per_page.vertical),
1325 );
1326
1327 // If a drag took place after we started dragging the scrollbar,
1328 // cancel the scrollbar drag.
1329 if cx.has_active_drag() {
1330 self.editor.update(cx, |editor, cx| {
1331 editor
1332 .scroll_manager
1333 .set_is_dragging_scrollbar(Axis::Horizontal, false, cx);
1334 editor
1335 .scroll_manager
1336 .set_is_dragging_scrollbar(Axis::Vertical, false, cx);
1337 });
1338 }
1339
1340 let text_bounds = scrollbar_range_data.scrollbar_bounds;
1341
1342 let track_bounds = axis_pair(
1343 axes.horizontal.then(|| {
1344 Bounds::from_corners(
1345 point(
1346 text_bounds.bottom_left().x,
1347 text_bounds.bottom_left().y - self.style.scrollbar_width,
1348 ),
1349 point(
1350 text_bounds.bottom_right().x
1351 - if axes.vertical {
1352 self.style.scrollbar_width
1353 } else {
1354 px(0.)
1355 },
1356 text_bounds.bottom_right().y,
1357 ),
1358 )
1359 }),
1360 axes.vertical.then(|| {
1361 Bounds::from_corners(
1362 point(self.scrollbar_left(&text_bounds), text_bounds.origin.y),
1363 text_bounds.bottom_right(),
1364 )
1365 }),
1366 );
1367
1368 let scroll_range_size = scrollbar_range_data.scroll_range.size;
1369 let total_text_units = axis_pair(
1370 Some(scroll_range_size.width / letter_size.width),
1371 Some(scroll_range_size.height / letter_size.height),
1372 );
1373
1374 let thumb_size = axis_pair(
1375 total_text_units
1376 .horizontal
1377 .zip(track_bounds.horizontal)
1378 .and_then(|(total_text_units_x, track_bounds_x)| {
1379 if text_units_per_page.horizontal >= total_text_units_x {
1380 return None;
1381 }
1382
1383 let thumb_percent =
1384 (text_units_per_page.horizontal / total_text_units_x).min(1.);
1385
1386 Some(track_bounds_x.size.width * thumb_percent)
1387 }),
1388 total_text_units.vertical.zip(track_bounds.vertical).map(
1389 |(total_text_units_y, track_bounds_y)| {
1390 let thumb_percent = (text_units_per_page.vertical / total_text_units_y).min(1.);
1391
1392 track_bounds_y.size.height * thumb_percent
1393 },
1394 ),
1395 );
1396
1397 // NOTE: Space not taken by track bounds divided by text units not on screen
1398 let text_unit_size = axis_pair(
1399 thumb_size
1400 .horizontal
1401 .zip(track_bounds.horizontal)
1402 .zip(total_text_units.horizontal)
1403 .map(|((thumb_size, track_bounds), total_text_units)| {
1404 (track_bounds.size.width - thumb_size)
1405 / (total_text_units - text_units_per_page.horizontal).max(0.)
1406 }),
1407 thumb_size
1408 .vertical
1409 .zip(track_bounds.vertical)
1410 .zip(total_text_units.vertical)
1411 .map(|((thumb_size, track_bounds), total_text_units)| {
1412 (track_bounds.size.height - thumb_size)
1413 / (total_text_units - text_units_per_page.vertical).max(0.)
1414 }),
1415 );
1416
1417 let horizontal_scrollbar = track_bounds
1418 .horizontal
1419 .zip(visible_range.horizontal)
1420 .zip(text_unit_size.horizontal)
1421 .zip(thumb_size.horizontal)
1422 .map(
1423 |(((track_bounds, visible_range), text_unit_size), thumb_size)| ScrollbarLayout {
1424 hitbox: window.insert_hitbox(track_bounds, false),
1425 visible_range,
1426 text_unit_size,
1427 visible: show_scrollbars,
1428 thumb_size,
1429 axis: Axis::Horizontal,
1430 },
1431 );
1432
1433 let vertical_scrollbar = track_bounds
1434 .vertical
1435 .zip(visible_range.vertical)
1436 .zip(text_unit_size.vertical)
1437 .zip(thumb_size.vertical)
1438 .map(
1439 |(((track_bounds, visible_range), text_unit_size), thumb_size)| ScrollbarLayout {
1440 hitbox: window.insert_hitbox(track_bounds, false),
1441 visible_range,
1442 text_unit_size,
1443 visible: show_scrollbars,
1444 thumb_size,
1445 axis: Axis::Vertical,
1446 },
1447 );
1448
1449 axis_pair(horizontal_scrollbar, vertical_scrollbar)
1450 }
1451
1452 #[allow(clippy::too_many_arguments)]
1453 fn prepaint_crease_toggles(
1454 &self,
1455 crease_toggles: &mut [Option<AnyElement>],
1456 line_height: Pixels,
1457 gutter_dimensions: &GutterDimensions,
1458 gutter_settings: crate::editor_settings::Gutter,
1459 scroll_pixel_position: gpui::Point<Pixels>,
1460 gutter_hitbox: &Hitbox,
1461 window: &mut Window,
1462 cx: &mut App,
1463 ) {
1464 for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
1465 if let Some(crease_toggle) = crease_toggle {
1466 debug_assert!(gutter_settings.folds);
1467 let available_space = size(
1468 AvailableSpace::MinContent,
1469 AvailableSpace::Definite(line_height * 0.55),
1470 );
1471 let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
1472
1473 let position = point(
1474 gutter_dimensions.width - gutter_dimensions.right_padding,
1475 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1476 );
1477 let centering_offset = point(
1478 (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
1479 (line_height - crease_toggle_size.height) / 2.,
1480 );
1481 let origin = gutter_hitbox.origin + position + centering_offset;
1482 crease_toggle.prepaint_as_root(origin, available_space, window, cx);
1483 }
1484 }
1485 }
1486
1487 #[allow(clippy::too_many_arguments)]
1488 fn prepaint_crease_trailers(
1489 &self,
1490 trailers: Vec<Option<AnyElement>>,
1491 lines: &[LineWithInvisibles],
1492 line_height: Pixels,
1493 content_origin: gpui::Point<Pixels>,
1494 scroll_pixel_position: gpui::Point<Pixels>,
1495 em_width: Pixels,
1496 window: &mut Window,
1497 cx: &mut App,
1498 ) -> Vec<Option<CreaseTrailerLayout>> {
1499 trailers
1500 .into_iter()
1501 .enumerate()
1502 .map(|(ix, element)| {
1503 let mut element = element?;
1504 let available_space = size(
1505 AvailableSpace::MinContent,
1506 AvailableSpace::Definite(line_height),
1507 );
1508 let size = element.layout_as_root(available_space, window, cx);
1509
1510 let line = &lines[ix];
1511 let padding = if line.width == Pixels::ZERO {
1512 Pixels::ZERO
1513 } else {
1514 4. * em_width
1515 };
1516 let position = point(
1517 scroll_pixel_position.x + line.width + padding,
1518 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1519 );
1520 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1521 let origin = content_origin + position + centering_offset;
1522 element.prepaint_as_root(origin, available_space, window, cx);
1523 Some(CreaseTrailerLayout {
1524 element,
1525 bounds: Bounds::new(origin, size),
1526 })
1527 })
1528 .collect()
1529 }
1530
1531 // Folds contained in a hunk are ignored apart from shrinking visual size
1532 // If a fold contains any hunks then that fold line is marked as modified
1533 fn layout_gutter_diff_hunks(
1534 &self,
1535 line_height: Pixels,
1536 gutter_hitbox: &Hitbox,
1537 display_rows: Range<DisplayRow>,
1538 snapshot: &EditorSnapshot,
1539 window: &mut Window,
1540 cx: &mut App,
1541 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1542 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(snapshot);
1543 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(snapshot);
1544
1545 let mut display_hunks = Vec::<(DisplayDiffHunk, Option<Hitbox>)>::new();
1546 let folded_buffers = self.editor.read(cx).folded_buffers(cx);
1547
1548 for hunk in snapshot
1549 .buffer_snapshot
1550 .diff_hunks_in_range(buffer_start..buffer_end)
1551 {
1552 if folded_buffers.contains(&hunk.buffer_id) {
1553 continue;
1554 }
1555
1556 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
1557 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
1558
1559 let hunk_display_start = snapshot.point_to_display_point(hunk_start_point, Bias::Left);
1560 let hunk_display_end = snapshot.point_to_display_point(hunk_end_point, Bias::Right);
1561
1562 let display_hunk = if hunk_display_start.column() != 0 {
1563 DisplayDiffHunk::Folded {
1564 display_row: hunk_display_start.row(),
1565 }
1566 } else {
1567 let mut end_row = hunk_display_end.row();
1568 if hunk_display_end.column() > 0 {
1569 end_row.0 += 1;
1570 }
1571 DisplayDiffHunk::Unfolded {
1572 status: hunk.status(),
1573 diff_base_byte_range: hunk.diff_base_byte_range,
1574 display_row_range: hunk_display_start.row()..end_row,
1575 multi_buffer_range: Anchor::range_in_buffer(
1576 hunk.excerpt_id,
1577 hunk.buffer_id,
1578 hunk.buffer_range,
1579 ),
1580 }
1581 };
1582
1583 display_hunks.push((display_hunk, None));
1584 }
1585
1586 let git_gutter_setting = ProjectSettings::get_global(cx)
1587 .git
1588 .git_gutter
1589 .unwrap_or_default();
1590 if let GitGutterSetting::TrackedFiles = git_gutter_setting {
1591 for (hunk, hitbox) in &mut display_hunks {
1592 if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
1593 let hunk_bounds =
1594 Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
1595 *hitbox = Some(window.insert_hitbox(hunk_bounds, true));
1596 }
1597 }
1598 }
1599
1600 display_hunks
1601 }
1602
1603 #[allow(clippy::too_many_arguments)]
1604 fn layout_inline_blame(
1605 &self,
1606 display_row: DisplayRow,
1607 row_info: &RowInfo,
1608 line_layout: &LineWithInvisibles,
1609 crease_trailer: Option<&CreaseTrailerLayout>,
1610 em_width: Pixels,
1611 content_origin: gpui::Point<Pixels>,
1612 scroll_pixel_position: gpui::Point<Pixels>,
1613 line_height: Pixels,
1614 window: &mut Window,
1615 cx: &mut App,
1616 ) -> Option<AnyElement> {
1617 if !self
1618 .editor
1619 .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
1620 {
1621 return None;
1622 }
1623
1624 let workspace = self
1625 .editor
1626 .read(cx)
1627 .workspace
1628 .as_ref()
1629 .map(|(w, _)| w.clone());
1630
1631 let editor = self.editor.read(cx);
1632 let blame = editor.blame.clone()?;
1633 let padding = {
1634 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1635 const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
1636
1637 let mut padding = INLINE_BLAME_PADDING_EM_WIDTHS;
1638
1639 if let Some(inline_completion) = editor.active_inline_completion.as_ref() {
1640 match &inline_completion.completion {
1641 InlineCompletion::Edit {
1642 display_mode: EditDisplayMode::TabAccept,
1643 ..
1644 } => padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS,
1645 _ => {}
1646 }
1647 }
1648
1649 padding * em_width
1650 };
1651
1652 let blame_entry = blame
1653 .update(cx, |blame, cx| {
1654 blame.blame_for_rows(&[*row_info], cx).next()
1655 })
1656 .flatten()?;
1657
1658 let mut element =
1659 render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1660
1661 let start_y = content_origin.y
1662 + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1663
1664 let start_x = {
1665 let line_end = if let Some(crease_trailer) = crease_trailer {
1666 crease_trailer.bounds.right()
1667 } else {
1668 content_origin.x - scroll_pixel_position.x + line_layout.width
1669 };
1670
1671 let padded_line_end = line_end + padding;
1672
1673 let min_column_in_pixels = ProjectSettings::get_global(cx)
1674 .git
1675 .inline_blame
1676 .and_then(|settings| settings.min_column)
1677 .map(|col| self.column_pixels(col as usize, window, cx))
1678 .unwrap_or(px(0.));
1679 let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1680
1681 cmp::max(padded_line_end, min_start)
1682 };
1683
1684 let absolute_offset = point(start_x, start_y);
1685 element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
1686
1687 Some(element)
1688 }
1689
1690 #[allow(clippy::too_many_arguments)]
1691 fn layout_blame_entries(
1692 &self,
1693 buffer_rows: &[RowInfo],
1694 em_width: Pixels,
1695 scroll_position: gpui::Point<f32>,
1696 line_height: Pixels,
1697 gutter_hitbox: &Hitbox,
1698 max_width: Option<Pixels>,
1699 window: &mut Window,
1700 cx: &mut App,
1701 ) -> Option<Vec<AnyElement>> {
1702 if !self
1703 .editor
1704 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1705 {
1706 return None;
1707 }
1708
1709 let blame = self.editor.read(cx).blame.clone()?;
1710 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1711 blame.blame_for_rows(buffer_rows, cx).collect()
1712 });
1713
1714 let width = if let Some(max_width) = max_width {
1715 AvailableSpace::Definite(max_width)
1716 } else {
1717 AvailableSpace::MaxContent
1718 };
1719 let scroll_top = scroll_position.y * line_height;
1720 let start_x = em_width;
1721
1722 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1723
1724 let shaped_lines = blamed_rows
1725 .into_iter()
1726 .enumerate()
1727 .flat_map(|(ix, blame_entry)| {
1728 if let Some(blame_entry) = blame_entry {
1729 let mut element = render_blame_entry(
1730 ix,
1731 &blame,
1732 blame_entry,
1733 &self.style,
1734 &mut last_used_color,
1735 self.editor.clone(),
1736 cx,
1737 );
1738
1739 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1740 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1741
1742 element.prepaint_as_root(
1743 absolute_offset,
1744 size(width, AvailableSpace::MinContent),
1745 window,
1746 cx,
1747 );
1748
1749 Some(element)
1750 } else {
1751 None
1752 }
1753 })
1754 .collect();
1755
1756 Some(shaped_lines)
1757 }
1758
1759 #[allow(clippy::too_many_arguments)]
1760 fn layout_indent_guides(
1761 &self,
1762 content_origin: gpui::Point<Pixels>,
1763 text_origin: gpui::Point<Pixels>,
1764 visible_buffer_range: Range<MultiBufferRow>,
1765 scroll_pixel_position: gpui::Point<Pixels>,
1766 line_height: Pixels,
1767 snapshot: &DisplaySnapshot,
1768 window: &mut Window,
1769 cx: &mut App,
1770 ) -> Option<Vec<IndentGuideLayout>> {
1771 let indent_guides = self.editor.update(cx, |editor, cx| {
1772 editor.indent_guides(visible_buffer_range, snapshot, cx)
1773 })?;
1774
1775 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1776 editor
1777 .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
1778 .unwrap_or_default()
1779 });
1780
1781 Some(
1782 indent_guides
1783 .into_iter()
1784 .enumerate()
1785 .filter_map(|(i, indent_guide)| {
1786 let single_indent_width =
1787 self.column_pixels(indent_guide.tab_size as usize, window, cx);
1788 let total_width = single_indent_width * indent_guide.depth as f32;
1789 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1790 if start_x >= text_origin.x {
1791 let (offset_y, length) = Self::calculate_indent_guide_bounds(
1792 indent_guide.start_row..indent_guide.end_row,
1793 line_height,
1794 snapshot,
1795 );
1796
1797 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1798
1799 Some(IndentGuideLayout {
1800 origin: point(start_x, start_y),
1801 length,
1802 single_indent_width,
1803 depth: indent_guide.depth,
1804 active: active_indent_guide_indices.contains(&i),
1805 settings: indent_guide.settings,
1806 })
1807 } else {
1808 None
1809 }
1810 })
1811 .collect(),
1812 )
1813 }
1814
1815 fn calculate_indent_guide_bounds(
1816 row_range: Range<MultiBufferRow>,
1817 line_height: Pixels,
1818 snapshot: &DisplaySnapshot,
1819 ) -> (gpui::Pixels, gpui::Pixels) {
1820 let start_point = Point::new(row_range.start.0, 0);
1821 let end_point = Point::new(row_range.end.0, 0);
1822
1823 let row_range = start_point.to_display_point(snapshot).row()
1824 ..end_point.to_display_point(snapshot).row();
1825
1826 let mut prev_line = start_point;
1827 prev_line.row = prev_line.row.saturating_sub(1);
1828 let prev_line = prev_line.to_display_point(snapshot).row();
1829
1830 let mut cons_line = end_point;
1831 cons_line.row += 1;
1832 let cons_line = cons_line.to_display_point(snapshot).row();
1833
1834 let mut offset_y = row_range.start.0 as f32 * line_height;
1835 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1836
1837 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1838 if row_range.end == cons_line {
1839 length += line_height;
1840 }
1841
1842 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1843 // we want to extend the indent guide to the start of the block.
1844 let mut block_height = 0;
1845 let mut block_offset = 0;
1846 let mut found_excerpt_header = false;
1847 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1848 if matches!(block, Block::ExcerptBoundary { .. }) {
1849 found_excerpt_header = true;
1850 break;
1851 }
1852 block_offset += block.height();
1853 block_height += block.height();
1854 }
1855 if !found_excerpt_header {
1856 offset_y -= block_offset as f32 * line_height;
1857 length += block_height as f32 * line_height;
1858 }
1859
1860 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1861 // we want to ensure that the indent guide stops before the excerpt header.
1862 let mut block_height = 0;
1863 let mut found_excerpt_header = false;
1864 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1865 if matches!(block, Block::ExcerptBoundary { .. }) {
1866 found_excerpt_header = true;
1867 }
1868 block_height += block.height();
1869 }
1870 if found_excerpt_header {
1871 length -= block_height as f32 * line_height;
1872 }
1873
1874 (offset_y, length)
1875 }
1876
1877 #[allow(clippy::too_many_arguments)]
1878 fn layout_run_indicators(
1879 &self,
1880 line_height: Pixels,
1881 range: Range<DisplayRow>,
1882 scroll_pixel_position: gpui::Point<Pixels>,
1883 gutter_dimensions: &GutterDimensions,
1884 gutter_hitbox: &Hitbox,
1885 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
1886 snapshot: &EditorSnapshot,
1887 window: &mut Window,
1888 cx: &mut App,
1889 ) -> Vec<AnyElement> {
1890 self.editor.update(cx, |editor, cx| {
1891 let active_task_indicator_row =
1892 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
1893 deployed_from_indicator,
1894 actions,
1895 ..
1896 })) = editor.context_menu.borrow().as_ref()
1897 {
1898 actions
1899 .tasks
1900 .as_ref()
1901 .map(|tasks| tasks.position.to_display_point(snapshot).row())
1902 .or(*deployed_from_indicator)
1903 } else {
1904 None
1905 };
1906
1907 let offset_range_start = snapshot
1908 .display_point_to_anchor(DisplayPoint::new(range.start, 0), Bias::Left)
1909 .to_offset(&snapshot.buffer_snapshot);
1910 let offset_range_end = snapshot
1911 .display_point_to_anchor(DisplayPoint::new(range.end, 0), Bias::Right)
1912 .to_offset(&snapshot.buffer_snapshot);
1913
1914 editor
1915 .tasks
1916 .iter()
1917 .filter_map(|(_, tasks)| {
1918 if tasks.offset.0 < offset_range_start || tasks.offset.0 >= offset_range_end {
1919 return None;
1920 }
1921 let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1922 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1923 let buffer_folded = snapshot
1924 .buffer_snapshot
1925 .buffer_line_for_row(multibuffer_row)
1926 .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
1927 .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
1928 .unwrap_or(false);
1929 if buffer_folded {
1930 return None;
1931 }
1932
1933 if snapshot.is_line_folded(multibuffer_row) {
1934 // Skip folded indicators, unless it's the starting line of a fold.
1935 if multibuffer_row
1936 .0
1937 .checked_sub(1)
1938 .map_or(false, |previous_row| {
1939 snapshot.is_line_folded(MultiBufferRow(previous_row))
1940 })
1941 {
1942 return None;
1943 }
1944 }
1945 let display_row = multibuffer_point.to_display_point(snapshot).row();
1946 let button = editor.render_run_indicator(
1947 &self.style,
1948 Some(display_row) == active_task_indicator_row,
1949 display_row,
1950 cx,
1951 );
1952
1953 let button = prepaint_gutter_button(
1954 button,
1955 display_row,
1956 line_height,
1957 gutter_dimensions,
1958 scroll_pixel_position,
1959 gutter_hitbox,
1960 rows_with_hunk_bounds,
1961 window,
1962 cx,
1963 );
1964 Some(button)
1965 })
1966 .collect_vec()
1967 })
1968 }
1969
1970 #[allow(clippy::too_many_arguments)]
1971 fn layout_code_actions_indicator(
1972 &self,
1973 line_height: Pixels,
1974 newest_selection_head: DisplayPoint,
1975 scroll_pixel_position: gpui::Point<Pixels>,
1976 gutter_dimensions: &GutterDimensions,
1977 gutter_hitbox: &Hitbox,
1978 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
1979 window: &mut Window,
1980 cx: &mut App,
1981 ) -> Option<AnyElement> {
1982 let mut active = false;
1983 let mut button = None;
1984 let row = newest_selection_head.row();
1985 self.editor.update(cx, |editor, cx| {
1986 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
1987 deployed_from_indicator,
1988 ..
1989 })) = editor.context_menu.borrow().as_ref()
1990 {
1991 active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1992 };
1993 button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1994 });
1995
1996 let button = prepaint_gutter_button(
1997 button?,
1998 row,
1999 line_height,
2000 gutter_dimensions,
2001 scroll_pixel_position,
2002 gutter_hitbox,
2003 rows_with_hunk_bounds,
2004 window,
2005 cx,
2006 );
2007
2008 Some(button)
2009 }
2010
2011 fn get_participant_color(participant_index: Option<ParticipantIndex>, cx: &App) -> PlayerColor {
2012 if let Some(index) = participant_index {
2013 cx.theme().players().color_for_participant(index.0)
2014 } else {
2015 cx.theme().players().absent()
2016 }
2017 }
2018
2019 fn calculate_relative_line_numbers(
2020 &self,
2021 snapshot: &EditorSnapshot,
2022 rows: &Range<DisplayRow>,
2023 relative_to: Option<DisplayRow>,
2024 ) -> HashMap<DisplayRow, DisplayRowDelta> {
2025 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
2026 let Some(relative_to) = relative_to else {
2027 return relative_rows;
2028 };
2029
2030 let start = rows.start.min(relative_to);
2031 let end = rows.end.max(relative_to);
2032
2033 let buffer_rows = snapshot
2034 .row_infos(start)
2035 .take(1 + end.minus(start) as usize)
2036 .collect::<Vec<_>>();
2037
2038 let head_idx = relative_to.minus(start);
2039 let mut delta = 1;
2040 let mut i = head_idx + 1;
2041 while i < buffer_rows.len() as u32 {
2042 if buffer_rows[i as usize].buffer_row.is_some() {
2043 if rows.contains(&DisplayRow(i + start.0)) {
2044 relative_rows.insert(DisplayRow(i + start.0), delta);
2045 }
2046 delta += 1;
2047 }
2048 i += 1;
2049 }
2050 delta = 1;
2051 i = head_idx.min(buffer_rows.len() as u32 - 1);
2052 while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
2053 i -= 1;
2054 }
2055
2056 while i > 0 {
2057 i -= 1;
2058 if buffer_rows[i as usize].buffer_row.is_some() {
2059 if rows.contains(&DisplayRow(i + start.0)) {
2060 relative_rows.insert(DisplayRow(i + start.0), delta);
2061 }
2062 delta += 1;
2063 }
2064 }
2065
2066 relative_rows
2067 }
2068
2069 #[allow(clippy::too_many_arguments)]
2070 fn layout_line_numbers(
2071 &self,
2072 gutter_hitbox: Option<&Hitbox>,
2073 gutter_dimensions: GutterDimensions,
2074 line_height: Pixels,
2075 scroll_position: gpui::Point<f32>,
2076 rows: Range<DisplayRow>,
2077 buffer_rows: &[RowInfo],
2078 newest_selection_head: Option<DisplayPoint>,
2079 snapshot: &EditorSnapshot,
2080 window: &mut Window,
2081 cx: &mut App,
2082 ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
2083 let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
2084 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
2085 });
2086 if !include_line_numbers {
2087 return Arc::default();
2088 }
2089
2090 let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
2091 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
2092 let newest = editor.selections.newest::<Point>(cx);
2093 SelectionLayout::new(
2094 newest,
2095 editor.selections.line_mode,
2096 editor.cursor_shape,
2097 &snapshot.display_snapshot,
2098 true,
2099 true,
2100 None,
2101 )
2102 .head
2103 });
2104 let is_relative = editor.should_use_relative_line_numbers(cx);
2105 (newest_selection_head, is_relative)
2106 });
2107
2108 let relative_to = if is_relative {
2109 Some(newest_selection_head.row())
2110 } else {
2111 None
2112 };
2113 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
2114 let mut line_number = String::new();
2115 let line_numbers = buffer_rows
2116 .into_iter()
2117 .enumerate()
2118 .flat_map(|(ix, row_info)| {
2119 let display_row = DisplayRow(rows.start.0 + ix as u32);
2120 line_number.clear();
2121 let non_relative_number = row_info.buffer_row? + 1;
2122 let number = relative_rows
2123 .get(&display_row)
2124 .unwrap_or(&non_relative_number);
2125 write!(&mut line_number, "{number}").unwrap();
2126 if matches!(row_info.diff_status, Some(DiffHunkStatus::Removed(_))) {
2127 return None;
2128 }
2129
2130 let color = cx.theme().colors().editor_line_number;
2131 let shaped_line = self
2132 .shape_line_number(SharedString::from(&line_number), color, window)
2133 .log_err()?;
2134 let scroll_top = scroll_position.y * line_height;
2135 let line_origin = gutter_hitbox.map(|hitbox| {
2136 hitbox.origin
2137 + point(
2138 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
2139 ix as f32 * line_height - (scroll_top % line_height),
2140 )
2141 });
2142
2143 #[cfg(not(test))]
2144 let hitbox = line_origin.map(|line_origin| {
2145 window.insert_hitbox(
2146 Bounds::new(line_origin, size(shaped_line.width, line_height)),
2147 false,
2148 )
2149 });
2150 #[cfg(test)]
2151 let hitbox = {
2152 let _ = line_origin;
2153 None
2154 };
2155
2156 let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
2157 let multi_buffer_row = MultiBufferRow(multi_buffer_row);
2158 let line_number = LineNumberLayout {
2159 shaped_line,
2160 hitbox,
2161 display_row,
2162 };
2163 Some((multi_buffer_row, line_number))
2164 })
2165 .collect();
2166 Arc::new(line_numbers)
2167 }
2168
2169 fn layout_crease_toggles(
2170 &self,
2171 rows: Range<DisplayRow>,
2172 row_infos: &[RowInfo],
2173 active_rows: &BTreeMap<DisplayRow, bool>,
2174 snapshot: &EditorSnapshot,
2175 window: &mut Window,
2176 cx: &mut App,
2177 ) -> Vec<Option<AnyElement>> {
2178 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
2179 && snapshot.mode == EditorMode::Full
2180 && self.editor.read(cx).is_singleton(cx);
2181 if include_fold_statuses {
2182 row_infos
2183 .into_iter()
2184 .enumerate()
2185 .map(|(ix, info)| {
2186 let row = info.multibuffer_row?;
2187 let display_row = DisplayRow(rows.start.0 + ix as u32);
2188 let active = active_rows.contains_key(&display_row);
2189
2190 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
2191 })
2192 .collect()
2193 } else {
2194 Vec::new()
2195 }
2196 }
2197
2198 fn layout_crease_trailers(
2199 &self,
2200 buffer_rows: impl IntoIterator<Item = RowInfo>,
2201 snapshot: &EditorSnapshot,
2202 window: &mut Window,
2203 cx: &mut App,
2204 ) -> Vec<Option<AnyElement>> {
2205 buffer_rows
2206 .into_iter()
2207 .map(|row_info| {
2208 if let Some(row) = row_info.multibuffer_row {
2209 snapshot.render_crease_trailer(row, window, cx)
2210 } else {
2211 None
2212 }
2213 })
2214 .collect()
2215 }
2216
2217 fn layout_lines(
2218 rows: Range<DisplayRow>,
2219 snapshot: &EditorSnapshot,
2220 style: &EditorStyle,
2221 editor_width: Pixels,
2222 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2223 window: &mut Window,
2224 cx: &mut App,
2225 ) -> Vec<LineWithInvisibles> {
2226 if rows.start >= rows.end {
2227 return Vec::new();
2228 }
2229
2230 // Show the placeholder when the editor is empty
2231 if snapshot.is_empty() {
2232 let font_size = style.text.font_size.to_pixels(window.rem_size());
2233 let placeholder_color = cx.theme().colors().text_placeholder;
2234 let placeholder_text = snapshot.placeholder_text();
2235
2236 let placeholder_lines = placeholder_text
2237 .as_ref()
2238 .map_or("", AsRef::as_ref)
2239 .split('\n')
2240 .skip(rows.start.0 as usize)
2241 .chain(iter::repeat(""))
2242 .take(rows.len());
2243 placeholder_lines
2244 .filter_map(move |line| {
2245 let run = TextRun {
2246 len: line.len(),
2247 font: style.text.font(),
2248 color: placeholder_color,
2249 background_color: None,
2250 underline: Default::default(),
2251 strikethrough: None,
2252 };
2253 window
2254 .text_system()
2255 .shape_line(line.to_string().into(), font_size, &[run])
2256 .log_err()
2257 })
2258 .map(|line| LineWithInvisibles {
2259 width: line.width,
2260 len: line.len,
2261 fragments: smallvec![LineFragment::Text(line)],
2262 invisibles: Vec::new(),
2263 font_size,
2264 })
2265 .collect()
2266 } else {
2267 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
2268 LineWithInvisibles::from_chunks(
2269 chunks,
2270 &style,
2271 MAX_LINE_LEN,
2272 rows.len(),
2273 snapshot.mode,
2274 editor_width,
2275 is_row_soft_wrapped,
2276 window,
2277 cx,
2278 )
2279 }
2280 }
2281
2282 #[allow(clippy::too_many_arguments)]
2283 fn prepaint_lines(
2284 &self,
2285 start_row: DisplayRow,
2286 line_layouts: &mut [LineWithInvisibles],
2287 line_height: Pixels,
2288 scroll_pixel_position: gpui::Point<Pixels>,
2289 content_origin: gpui::Point<Pixels>,
2290 window: &mut Window,
2291 cx: &mut App,
2292 ) -> SmallVec<[AnyElement; 1]> {
2293 let mut line_elements = SmallVec::new();
2294 for (ix, line) in line_layouts.iter_mut().enumerate() {
2295 let row = start_row + DisplayRow(ix as u32);
2296 line.prepaint(
2297 line_height,
2298 scroll_pixel_position,
2299 row,
2300 content_origin,
2301 &mut line_elements,
2302 window,
2303 cx,
2304 );
2305 }
2306 line_elements
2307 }
2308
2309 #[allow(clippy::too_many_arguments)]
2310 fn render_block(
2311 &self,
2312 block: &Block,
2313 available_width: AvailableSpace,
2314 block_id: BlockId,
2315 block_row_start: DisplayRow,
2316 snapshot: &EditorSnapshot,
2317 text_x: Pixels,
2318 rows: &Range<DisplayRow>,
2319 line_layouts: &[LineWithInvisibles],
2320 gutter_dimensions: &GutterDimensions,
2321 line_height: Pixels,
2322 em_width: Pixels,
2323 text_hitbox: &Hitbox,
2324 editor_width: Pixels,
2325 scroll_width: &mut Pixels,
2326 resized_blocks: &mut HashMap<CustomBlockId, u32>,
2327 selections: &[Selection<Point>],
2328 selected_buffer_ids: &Vec<BufferId>,
2329 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2330 sticky_header_excerpt_id: Option<ExcerptId>,
2331 window: &mut Window,
2332 cx: &mut App,
2333 ) -> (AnyElement, Size<Pixels>) {
2334 let mut element = match block {
2335 Block::Custom(block) => {
2336 let block_start = block.start().to_point(&snapshot.buffer_snapshot);
2337 let block_end = block.end().to_point(&snapshot.buffer_snapshot);
2338 let align_to = block_start.to_display_point(snapshot);
2339 let anchor_x = text_x
2340 + if rows.contains(&align_to.row()) {
2341 line_layouts[align_to.row().minus(rows.start) as usize]
2342 .x_for_index(align_to.column() as usize)
2343 } else {
2344 layout_line(
2345 align_to.row(),
2346 snapshot,
2347 &self.style,
2348 editor_width,
2349 is_row_soft_wrapped,
2350 window,
2351 cx,
2352 )
2353 .x_for_index(align_to.column() as usize)
2354 };
2355
2356 let selected = selections
2357 .binary_search_by(|selection| {
2358 if selection.end <= block_start {
2359 Ordering::Less
2360 } else if selection.start >= block_end {
2361 Ordering::Greater
2362 } else {
2363 Ordering::Equal
2364 }
2365 })
2366 .is_ok();
2367
2368 div()
2369 .size_full()
2370 .child(block.render(&mut BlockContext {
2371 window,
2372 app: cx,
2373 anchor_x,
2374 gutter_dimensions,
2375 line_height,
2376 em_width,
2377 block_id,
2378 selected,
2379 max_width: text_hitbox.size.width.max(*scroll_width),
2380 editor_style: &self.style,
2381 }))
2382 .into_any()
2383 }
2384
2385 Block::FoldedBuffer {
2386 first_excerpt,
2387 prev_excerpt,
2388 show_excerpt_controls,
2389 height,
2390 } => {
2391 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
2392 let mut result = v_flex().id(block_id).w_full();
2393
2394 if let Some(prev_excerpt) = prev_excerpt {
2395 if *show_excerpt_controls {
2396 result = result.child(self.render_expand_excerpt_control(
2397 block_id,
2398 ExpandExcerptDirection::Down,
2399 prev_excerpt.id,
2400 gutter_dimensions,
2401 window,
2402 cx,
2403 ));
2404 }
2405 }
2406
2407 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
2408 result
2409 .child(self.render_buffer_header(
2410 first_excerpt,
2411 true,
2412 selected,
2413 jump_data,
2414 window,
2415 cx,
2416 ))
2417 .into_any_element()
2418 }
2419
2420 Block::ExcerptBoundary {
2421 prev_excerpt,
2422 next_excerpt,
2423 show_excerpt_controls,
2424 height,
2425 starts_new_buffer,
2426 } => {
2427 let color = cx.theme().colors().clone();
2428 let mut result = v_flex().id(block_id).w_full();
2429
2430 if let Some(prev_excerpt) = prev_excerpt {
2431 if *show_excerpt_controls {
2432 result = result.child(self.render_expand_excerpt_control(
2433 block_id,
2434 ExpandExcerptDirection::Down,
2435 prev_excerpt.id,
2436 gutter_dimensions,
2437 window,
2438 cx,
2439 ));
2440 }
2441 }
2442
2443 if let Some(next_excerpt) = next_excerpt {
2444 let jump_data =
2445 header_jump_data(snapshot, block_row_start, *height, next_excerpt);
2446
2447 if *starts_new_buffer {
2448 if sticky_header_excerpt_id != Some(next_excerpt.id) {
2449 let selected = selected_buffer_ids.contains(&next_excerpt.buffer_id);
2450
2451 result = result.child(self.render_buffer_header(
2452 next_excerpt,
2453 false,
2454 selected,
2455 jump_data,
2456 window,
2457 cx,
2458 ));
2459 } else {
2460 result = result
2461 .child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
2462 }
2463
2464 if *show_excerpt_controls {
2465 result = result.child(self.render_expand_excerpt_control(
2466 block_id,
2467 ExpandExcerptDirection::Up,
2468 next_excerpt.id,
2469 gutter_dimensions,
2470 window,
2471 cx,
2472 ));
2473 }
2474 } else {
2475 if *show_excerpt_controls {
2476 result = result.child(
2477 h_flex()
2478 .relative()
2479 .child(
2480 div()
2481 .top(px(0.))
2482 .absolute()
2483 .w_full()
2484 .h_px()
2485 .bg(color.border_variant),
2486 )
2487 .child(self.render_expand_excerpt_control(
2488 block_id,
2489 ExpandExcerptDirection::Up,
2490 next_excerpt.id,
2491 gutter_dimensions,
2492 window,
2493 cx,
2494 )),
2495 );
2496 }
2497 };
2498 }
2499
2500 result.into_any()
2501 }
2502 };
2503
2504 // Discover the element's content height, then round up to the nearest multiple of line height.
2505 let preliminary_size = element.layout_as_root(
2506 size(available_width, AvailableSpace::MinContent),
2507 window,
2508 cx,
2509 );
2510 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2511 let final_size = if preliminary_size.height == quantized_height {
2512 preliminary_size
2513 } else {
2514 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
2515 };
2516
2517 if let BlockId::Custom(custom_block_id) = block_id {
2518 if block.height() > 0 {
2519 let element_height_in_lines =
2520 ((final_size.height / line_height).ceil() as u32).max(1);
2521 if element_height_in_lines != block.height() {
2522 resized_blocks.insert(custom_block_id, element_height_in_lines);
2523 }
2524 }
2525 }
2526
2527 (element, final_size)
2528 }
2529
2530 fn render_buffer_header(
2531 &self,
2532 for_excerpt: &ExcerptInfo,
2533 is_folded: bool,
2534 is_selected: bool,
2535 jump_data: JumpData,
2536 window: &mut Window,
2537 cx: &mut App,
2538 ) -> Div {
2539 let include_root = self
2540 .editor
2541 .read(cx)
2542 .project
2543 .as_ref()
2544 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2545 .unwrap_or_default();
2546 let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
2547 let filename = path
2548 .as_ref()
2549 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
2550 let parent_path = path.as_ref().and_then(|path| {
2551 Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
2552 });
2553 let focus_handle = self.editor.focus_handle(cx);
2554 let colors = cx.theme().colors();
2555
2556 div()
2557 .px_2()
2558 .pt_2()
2559 .w_full()
2560 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
2561 .child(
2562 h_flex()
2563 .size_full()
2564 .gap_2()
2565 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2566 .pl_0p5()
2567 .pr_5()
2568 .rounded_md()
2569 .shadow_md()
2570 .border_1()
2571 .map(|div| {
2572 let border_color = if is_selected && is_folded {
2573 colors.border_focused
2574 } else {
2575 colors.border
2576 };
2577 div.border_color(border_color)
2578 })
2579 .bg(colors.editor_subheader_background)
2580 .hover(|style| style.bg(colors.element_hover))
2581 .map(|header| {
2582 let editor = self.editor.clone();
2583 let buffer_id = for_excerpt.buffer_id;
2584 let toggle_chevron_icon =
2585 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
2586 header.child(
2587 div()
2588 .hover(|style| style.bg(colors.element_selected))
2589 .rounded_sm()
2590 .child(
2591 ButtonLike::new("toggle-buffer-fold")
2592 .style(ui::ButtonStyle::Transparent)
2593 .size(ButtonSize::Large)
2594 .width(px(30.).into())
2595 .children(toggle_chevron_icon)
2596 .tooltip({
2597 let focus_handle = focus_handle.clone();
2598 move |window, cx| {
2599 Tooltip::for_action_in(
2600 "Toggle Excerpt Fold",
2601 &ToggleFold,
2602 &focus_handle,
2603 window,
2604 cx,
2605 )
2606 }
2607 })
2608 .on_click(move |_, _, cx| {
2609 if is_folded {
2610 editor.update(cx, |editor, cx| {
2611 editor.unfold_buffer(buffer_id, cx);
2612 });
2613 } else {
2614 editor.update(cx, |editor, cx| {
2615 editor.fold_buffer(buffer_id, cx);
2616 });
2617 }
2618 }),
2619 ),
2620 )
2621 })
2622 .children(
2623 self.editor
2624 .read(cx)
2625 .addons
2626 .values()
2627 .filter_map(|addon| {
2628 addon.render_buffer_header_controls(for_excerpt, window, cx)
2629 })
2630 .take(1),
2631 )
2632 .child(
2633 h_flex()
2634 .cursor_pointer()
2635 .id("path header block")
2636 .size_full()
2637 .justify_between()
2638 .child(
2639 h_flex()
2640 .gap_2()
2641 .child(
2642 filename
2643 .map(SharedString::from)
2644 .unwrap_or_else(|| "untitled".into()),
2645 )
2646 .when_some(parent_path, |then, path| {
2647 then.child(div().child(path).text_color(colors.text_muted))
2648 }),
2649 )
2650 .when(is_selected, |el| {
2651 el.child(
2652 h_flex()
2653 .id("jump-to-file-button")
2654 .gap_2p5()
2655 .child(Label::new("Jump To File"))
2656 .children(
2657 KeyBinding::for_action_in(
2658 &OpenExcerpts,
2659 &focus_handle,
2660 window,
2661 )
2662 .map(|binding| binding.into_any_element()),
2663 ),
2664 )
2665 })
2666 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
2667 .on_click(window.listener_for(&self.editor, {
2668 move |editor, e: &ClickEvent, window, cx| {
2669 editor.open_excerpts_common(
2670 Some(jump_data.clone()),
2671 e.down.modifiers.secondary(),
2672 window,
2673 cx,
2674 );
2675 }
2676 })),
2677 ),
2678 )
2679 }
2680
2681 fn render_expand_excerpt_control(
2682 &self,
2683 block_id: BlockId,
2684 direction: ExpandExcerptDirection,
2685 excerpt_id: ExcerptId,
2686 gutter_dimensions: &GutterDimensions,
2687 window: &Window,
2688 cx: &mut App,
2689 ) -> impl IntoElement {
2690 let color = cx.theme().colors().clone();
2691 let hover_color = color.border_variant.opacity(0.5);
2692 let focus_handle = self.editor.focus_handle(cx).clone();
2693
2694 let icon_offset =
2695 gutter_dimensions.width - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2696 let header_height = MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * window.line_height();
2697 let group_name = if direction == ExpandExcerptDirection::Down {
2698 "expand-down"
2699 } else {
2700 "expand-up"
2701 };
2702
2703 let expand_area = |id: SharedString| {
2704 h_flex()
2705 .id(id)
2706 .w_full()
2707 .cursor_pointer()
2708 .block_mouse_down()
2709 .on_mouse_move(|_, _, cx| cx.stop_propagation())
2710 .hover(|style| style.bg(hover_color))
2711 .tooltip({
2712 let focus_handle = focus_handle.clone();
2713 move |window, cx| {
2714 Tooltip::for_action_in(
2715 "Expand Excerpt",
2716 &ExpandExcerpts { lines: 0 },
2717 &focus_handle,
2718 window,
2719 cx,
2720 )
2721 }
2722 })
2723 };
2724
2725 expand_area(
2726 format!(
2727 "block-{}-{}",
2728 block_id,
2729 if direction == ExpandExcerptDirection::Down {
2730 "down"
2731 } else {
2732 "up"
2733 }
2734 )
2735 .into(),
2736 )
2737 .group(group_name)
2738 .child(
2739 h_flex()
2740 .w(icon_offset)
2741 .h(header_height)
2742 .flex_none()
2743 .justify_end()
2744 .child(
2745 ButtonLike::new("expand-icon")
2746 .style(ButtonStyle::Transparent)
2747 .child(
2748 svg()
2749 .path(if direction == ExpandExcerptDirection::Down {
2750 IconName::ArrowDownFromLine.path()
2751 } else {
2752 IconName::ArrowUpFromLine.path()
2753 })
2754 .size(IconSize::XSmall.rems())
2755 .text_color(cx.theme().colors().editor_line_number)
2756 .group_hover(group_name, |style| {
2757 style.text_color(cx.theme().colors().editor_active_line_number)
2758 }),
2759 ),
2760 ),
2761 )
2762 .on_click(window.listener_for(&self.editor, {
2763 move |editor, _, _, cx| {
2764 editor.expand_excerpt(excerpt_id, direction, cx);
2765 cx.stop_propagation();
2766 }
2767 }))
2768 }
2769
2770 #[allow(clippy::too_many_arguments)]
2771 fn render_blocks(
2772 &self,
2773 rows: Range<DisplayRow>,
2774 snapshot: &EditorSnapshot,
2775 hitbox: &Hitbox,
2776 text_hitbox: &Hitbox,
2777 editor_width: Pixels,
2778 scroll_width: &mut Pixels,
2779 gutter_dimensions: &GutterDimensions,
2780 em_width: Pixels,
2781 text_x: Pixels,
2782 line_height: Pixels,
2783 line_layouts: &[LineWithInvisibles],
2784 selections: &[Selection<Point>],
2785 selected_buffer_ids: &Vec<BufferId>,
2786 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2787 sticky_header_excerpt_id: Option<ExcerptId>,
2788 window: &mut Window,
2789 cx: &mut App,
2790 ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2791 let (fixed_blocks, non_fixed_blocks) = snapshot
2792 .blocks_in_range(rows.clone())
2793 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2794
2795 let mut focused_block = self
2796 .editor
2797 .update(cx, |editor, _| editor.take_focused_block());
2798 let mut fixed_block_max_width = Pixels::ZERO;
2799 let mut blocks = Vec::new();
2800 let mut resized_blocks = HashMap::default();
2801
2802 for (row, block) in fixed_blocks {
2803 let block_id = block.id();
2804
2805 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2806 focused_block = None;
2807 }
2808
2809 let (element, element_size) = self.render_block(
2810 block,
2811 AvailableSpace::MinContent,
2812 block_id,
2813 row,
2814 snapshot,
2815 text_x,
2816 &rows,
2817 line_layouts,
2818 gutter_dimensions,
2819 line_height,
2820 em_width,
2821 text_hitbox,
2822 editor_width,
2823 scroll_width,
2824 &mut resized_blocks,
2825 selections,
2826 selected_buffer_ids,
2827 is_row_soft_wrapped,
2828 sticky_header_excerpt_id,
2829 window,
2830 cx,
2831 );
2832 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2833 blocks.push(BlockLayout {
2834 id: block_id,
2835 row: Some(row),
2836 element,
2837 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2838 style: BlockStyle::Fixed,
2839 });
2840 }
2841
2842 for (row, block) in non_fixed_blocks {
2843 let style = block.style();
2844 let width = match style {
2845 BlockStyle::Sticky => hitbox.size.width,
2846 BlockStyle::Flex => hitbox
2847 .size
2848 .width
2849 .max(fixed_block_max_width)
2850 .max(gutter_dimensions.width + *scroll_width),
2851 BlockStyle::Fixed => unreachable!(),
2852 };
2853 let block_id = block.id();
2854
2855 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2856 focused_block = None;
2857 }
2858
2859 let (element, element_size) = self.render_block(
2860 block,
2861 width.into(),
2862 block_id,
2863 row,
2864 snapshot,
2865 text_x,
2866 &rows,
2867 line_layouts,
2868 gutter_dimensions,
2869 line_height,
2870 em_width,
2871 text_hitbox,
2872 editor_width,
2873 scroll_width,
2874 &mut resized_blocks,
2875 selections,
2876 selected_buffer_ids,
2877 is_row_soft_wrapped,
2878 sticky_header_excerpt_id,
2879 window,
2880 cx,
2881 );
2882
2883 blocks.push(BlockLayout {
2884 id: block_id,
2885 row: Some(row),
2886 element,
2887 available_space: size(width.into(), element_size.height.into()),
2888 style,
2889 });
2890 }
2891
2892 if let Some(focused_block) = focused_block {
2893 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2894 if focus_handle.is_focused(window) {
2895 if let Some(block) = snapshot.block_for_id(focused_block.id) {
2896 let style = block.style();
2897 let width = match style {
2898 BlockStyle::Fixed => AvailableSpace::MinContent,
2899 BlockStyle::Flex => AvailableSpace::Definite(
2900 hitbox
2901 .size
2902 .width
2903 .max(fixed_block_max_width)
2904 .max(gutter_dimensions.width + *scroll_width),
2905 ),
2906 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2907 };
2908
2909 let (element, element_size) = self.render_block(
2910 &block,
2911 width,
2912 focused_block.id,
2913 rows.end,
2914 snapshot,
2915 text_x,
2916 &rows,
2917 line_layouts,
2918 gutter_dimensions,
2919 line_height,
2920 em_width,
2921 text_hitbox,
2922 editor_width,
2923 scroll_width,
2924 &mut resized_blocks,
2925 selections,
2926 selected_buffer_ids,
2927 is_row_soft_wrapped,
2928 sticky_header_excerpt_id,
2929 window,
2930 cx,
2931 );
2932
2933 blocks.push(BlockLayout {
2934 id: block.id(),
2935 row: None,
2936 element,
2937 available_space: size(width, element_size.height.into()),
2938 style,
2939 });
2940 }
2941 }
2942 }
2943 }
2944
2945 if resized_blocks.is_empty() {
2946 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2947 Ok(blocks)
2948 } else {
2949 Err(resized_blocks)
2950 }
2951 }
2952
2953 /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2954 /// a restart of rendering for the editor based on the new sizes.
2955 #[allow(clippy::too_many_arguments)]
2956 fn layout_blocks(
2957 &self,
2958 blocks: &mut Vec<BlockLayout>,
2959 block_starts: &mut HashSet<DisplayRow>,
2960 hitbox: &Hitbox,
2961 line_height: Pixels,
2962 scroll_pixel_position: gpui::Point<Pixels>,
2963 window: &mut Window,
2964 cx: &mut App,
2965 ) {
2966 for block in blocks {
2967 let mut origin = if let Some(row) = block.row {
2968 block_starts.insert(row);
2969 hitbox.origin
2970 + point(
2971 Pixels::ZERO,
2972 row.as_f32() * line_height - scroll_pixel_position.y,
2973 )
2974 } else {
2975 // Position the block outside the visible area
2976 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2977 };
2978
2979 if !matches!(block.style, BlockStyle::Sticky) {
2980 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2981 }
2982
2983 let focus_handle =
2984 block
2985 .element
2986 .prepaint_as_root(origin, block.available_space, window, cx);
2987
2988 if let Some(focus_handle) = focus_handle {
2989 self.editor.update(cx, |editor, _cx| {
2990 editor.set_focused_block(FocusedBlock {
2991 id: block.id,
2992 focus_handle: focus_handle.downgrade(),
2993 });
2994 });
2995 }
2996 }
2997 }
2998
2999 #[allow(clippy::too_many_arguments)]
3000 fn layout_sticky_buffer_header(
3001 &self,
3002 StickyHeaderExcerpt {
3003 excerpt,
3004 next_excerpt_controls_present,
3005 next_buffer_row,
3006 }: StickyHeaderExcerpt<'_>,
3007 scroll_position: f32,
3008 line_height: Pixels,
3009 snapshot: &EditorSnapshot,
3010 hitbox: &Hitbox,
3011 selected_buffer_ids: &Vec<BufferId>,
3012 window: &mut Window,
3013 cx: &mut App,
3014 ) -> AnyElement {
3015 let jump_data = header_jump_data(
3016 snapshot,
3017 DisplayRow(scroll_position as u32),
3018 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3019 excerpt,
3020 );
3021
3022 let editor_bg_color = cx.theme().colors().editor_background;
3023
3024 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3025
3026 let mut header = v_flex()
3027 .relative()
3028 .child(
3029 div()
3030 .w(hitbox.bounds.size.width)
3031 .h(FILE_HEADER_HEIGHT as f32 * line_height)
3032 .bg(linear_gradient(
3033 0.,
3034 linear_color_stop(editor_bg_color.opacity(0.), 0.),
3035 linear_color_stop(editor_bg_color, 0.6),
3036 ))
3037 .absolute()
3038 .top_0(),
3039 )
3040 .child(
3041 self.render_buffer_header(excerpt, false, selected, jump_data, window, cx)
3042 .into_any_element(),
3043 )
3044 .into_any_element();
3045
3046 let mut origin = hitbox.origin;
3047
3048 if let Some(next_buffer_row) = next_buffer_row {
3049 // Push up the sticky header when the excerpt is getting close to the top of the viewport
3050
3051 let mut max_row = next_buffer_row - FILE_HEADER_HEIGHT * 2;
3052
3053 if next_excerpt_controls_present {
3054 max_row -= MULTI_BUFFER_EXCERPT_HEADER_HEIGHT;
3055 }
3056
3057 let offset = scroll_position - max_row as f32;
3058
3059 if offset > 0.0 {
3060 origin.y -= Pixels(offset) * line_height;
3061 }
3062 }
3063
3064 let size = size(
3065 AvailableSpace::Definite(hitbox.size.width),
3066 AvailableSpace::MinContent,
3067 );
3068
3069 header.prepaint_as_root(origin, size, window, cx);
3070
3071 header
3072 }
3073
3074 #[allow(clippy::too_many_arguments)]
3075 fn layout_cursor_popovers(
3076 &self,
3077 line_height: Pixels,
3078 text_hitbox: &Hitbox,
3079 content_origin: gpui::Point<Pixels>,
3080 start_row: DisplayRow,
3081 scroll_pixel_position: gpui::Point<Pixels>,
3082 line_layouts: &[LineWithInvisibles],
3083 cursor: DisplayPoint,
3084 cursor_point: Point,
3085 style: &EditorStyle,
3086 window: &mut Window,
3087 cx: &mut App,
3088 ) {
3089 let mut min_menu_height = Pixels::ZERO;
3090 let mut max_menu_height = Pixels::ZERO;
3091 let mut height_above_menu = Pixels::ZERO;
3092 let height_below_menu = Pixels::ZERO;
3093 let mut edit_prediction_popover_visible = false;
3094 let mut context_menu_visible = false;
3095
3096 {
3097 let editor = self.editor.read(cx);
3098 if editor
3099 .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3100 {
3101 height_above_menu +=
3102 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3103 edit_prediction_popover_visible = true;
3104 }
3105
3106 if editor.context_menu_visible() {
3107 if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3108 min_menu_height += line_height * 3. + POPOVER_Y_PADDING;
3109 max_menu_height += line_height * 12. + POPOVER_Y_PADDING;
3110 context_menu_visible = true;
3111 }
3112 }
3113 }
3114
3115 let visible = edit_prediction_popover_visible || context_menu_visible;
3116 if !visible {
3117 return;
3118 }
3119
3120 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3121 let target_position = content_origin
3122 + gpui::Point {
3123 x: cmp::max(
3124 px(0.),
3125 cursor_row_layout.x_for_index(cursor.column() as usize)
3126 - scroll_pixel_position.x,
3127 ),
3128 y: cmp::max(
3129 px(0.),
3130 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3131 ),
3132 };
3133
3134 let viewport_bounds =
3135 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3136 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3137 ..Default::default()
3138 });
3139
3140 let min_height = height_above_menu + min_menu_height + height_below_menu;
3141 let max_height = height_above_menu + max_menu_height + height_below_menu;
3142 let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3143 target_position,
3144 line_height,
3145 min_height,
3146 max_height,
3147 text_hitbox,
3148 viewport_bounds,
3149 window,
3150 cx,
3151 |height, max_width_for_stable_x, y_flipped, window, cx| {
3152 // First layout the menu to get its size - others can be at least this wide.
3153 let context_menu = if context_menu_visible {
3154 let menu_height = if y_flipped {
3155 height - height_below_menu
3156 } else {
3157 height - height_above_menu
3158 };
3159 let mut element = self
3160 .render_context_menu(line_height, menu_height, y_flipped, window, cx)
3161 .expect("Visible context menu should always render.");
3162 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3163 Some((CursorPopoverType::CodeContextMenu, element, size))
3164 } else {
3165 None
3166 };
3167 let min_width = context_menu
3168 .as_ref()
3169 .map_or(px(0.), |(_, _, size)| size.width);
3170 let max_width = max_width_for_stable_x.max(
3171 context_menu
3172 .as_ref()
3173 .map_or(px(0.), |(_, _, size)| size.width),
3174 );
3175
3176 let edit_prediction = if edit_prediction_popover_visible {
3177 self.editor.update(cx, move |editor, cx| {
3178 let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3179 let mut element = editor.render_edit_prediction_cursor_popover(
3180 min_width,
3181 max_width,
3182 cursor_point,
3183 style,
3184 accept_binding.keystroke()?,
3185 window,
3186 cx,
3187 )?;
3188 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3189 Some((CursorPopoverType::EditPrediction, element, size))
3190 })
3191 } else {
3192 None
3193 };
3194 vec![edit_prediction, context_menu]
3195 .into_iter()
3196 .flatten()
3197 .collect::<Vec<_>>()
3198 },
3199 ) else {
3200 return;
3201 };
3202
3203 let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3204 .iter()
3205 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3206 else {
3207 return;
3208 };
3209 let last_ix = laid_out_popovers.len() - 1;
3210 let menu_is_last = menu_ix == last_ix;
3211 let first_popover_bounds = laid_out_popovers[0].1;
3212 let last_popover_bounds = laid_out_popovers[last_ix].1;
3213
3214 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3215 // right, and otherwise it goes below or to the right.
3216 let mut target_bounds = Bounds::from_corners(
3217 first_popover_bounds.origin,
3218 last_popover_bounds.bottom_right(),
3219 );
3220 target_bounds.size.width = menu_bounds.size.width;
3221
3222 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3223 // based on this is preferred for layout stability.
3224 let mut max_target_bounds = target_bounds;
3225 max_target_bounds.size.height = max_height;
3226 if y_flipped {
3227 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3228 }
3229
3230 // Add spacing around `target_bounds` and `max_target_bounds`.
3231 let mut extend_amount = Edges::all(MENU_GAP);
3232 if y_flipped {
3233 extend_amount.bottom = line_height;
3234 } else {
3235 extend_amount.top = line_height;
3236 }
3237 let target_bounds = target_bounds.extend(extend_amount);
3238 let max_target_bounds = max_target_bounds.extend(extend_amount);
3239
3240 let must_place_above_or_below =
3241 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3242 laid_out_popovers[menu_ix + 1..]
3243 .iter()
3244 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3245 } else {
3246 false
3247 };
3248
3249 self.layout_context_menu_aside(
3250 y_flipped,
3251 *menu_bounds,
3252 target_bounds,
3253 max_target_bounds,
3254 max_menu_height,
3255 must_place_above_or_below,
3256 text_hitbox,
3257 viewport_bounds,
3258 window,
3259 cx,
3260 );
3261 }
3262
3263 #[allow(clippy::too_many_arguments)]
3264 fn layout_gutter_menu(
3265 &self,
3266 line_height: Pixels,
3267 text_hitbox: &Hitbox,
3268 content_origin: gpui::Point<Pixels>,
3269 scroll_pixel_position: gpui::Point<Pixels>,
3270 gutter_overshoot: Pixels,
3271 window: &mut Window,
3272 cx: &mut App,
3273 ) {
3274 let editor = self.editor.read(cx);
3275 if !editor.context_menu_visible() {
3276 return;
3277 }
3278 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3279 editor.context_menu_origin()
3280 else {
3281 return;
3282 };
3283 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3284 // indicator than just a plain first column of the text field.
3285 let target_position = content_origin
3286 + gpui::Point {
3287 x: -gutter_overshoot,
3288 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3289 };
3290 let min_height = line_height * 3. + POPOVER_Y_PADDING;
3291 let max_height = line_height * 12. + POPOVER_Y_PADDING;
3292 let viewport_bounds =
3293 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3294 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3295 ..Default::default()
3296 });
3297 self.layout_popovers_above_or_below_line(
3298 target_position,
3299 line_height,
3300 min_height,
3301 max_height,
3302 text_hitbox,
3303 viewport_bounds,
3304 window,
3305 cx,
3306 move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3307 let mut element = self
3308 .render_context_menu(line_height, height, y_flipped, window, cx)
3309 .expect("Visible context menu should always render.");
3310 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3311 vec![(CursorPopoverType::CodeContextMenu, element, size)]
3312 },
3313 );
3314 }
3315
3316 #[allow(clippy::too_many_arguments)]
3317 fn layout_popovers_above_or_below_line(
3318 &self,
3319 target_position: gpui::Point<Pixels>,
3320 line_height: Pixels,
3321 min_height: Pixels,
3322 max_height: Pixels,
3323 text_hitbox: &Hitbox,
3324 viewport_bounds: Bounds<Pixels>,
3325 window: &mut Window,
3326 cx: &mut App,
3327 make_sized_popovers: impl FnOnce(
3328 Pixels,
3329 Pixels,
3330 bool,
3331 &mut Window,
3332 &mut App,
3333 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3334 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3335 // If the max height won't fit below and there is more space above, put it above the line.
3336 let bottom_y_when_flipped = target_position.y - line_height;
3337 let available_above = bottom_y_when_flipped - text_hitbox.top();
3338 let available_below = text_hitbox.bottom() - target_position.y;
3339 let y_overflows_below = max_height > available_below;
3340 let mut y_flipped = y_overflows_below && available_above > available_below;
3341 let mut height = cmp::min(
3342 max_height,
3343 if y_flipped {
3344 available_above
3345 } else {
3346 available_below
3347 },
3348 );
3349
3350 // If the min height doesn't fit within text bounds, instead fit within the window.
3351 if height < min_height {
3352 let available_above = bottom_y_when_flipped;
3353 let available_below = viewport_bounds.bottom() - target_position.y;
3354 if available_below > min_height {
3355 y_flipped = false;
3356 height = min_height;
3357 } else if available_above > min_height {
3358 y_flipped = true;
3359 height = min_height;
3360 } else if available_above > available_below {
3361 y_flipped = true;
3362 height = available_above;
3363 } else {
3364 y_flipped = false;
3365 height = available_below;
3366 }
3367 }
3368
3369 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3370
3371 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3372 // for very narrow windows.
3373 let popovers = make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3374 if popovers.is_empty() {
3375 return None;
3376 }
3377
3378 let max_width = popovers
3379 .iter()
3380 .map(|(_, _, size)| size.width)
3381 .max()
3382 .unwrap_or_default();
3383
3384 let mut current_position = gpui::Point {
3385 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3386 // overflow. Include space for the scrollbar.
3387 x: target_position
3388 .x
3389 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3390 y: if y_flipped {
3391 bottom_y_when_flipped
3392 } else {
3393 target_position.y
3394 },
3395 };
3396
3397 let mut laid_out_popovers = popovers
3398 .into_iter()
3399 .map(|(popover_type, element, size)| {
3400 if y_flipped {
3401 current_position.y -= size.height;
3402 }
3403 let position = current_position;
3404 window.defer_draw(element, current_position, 1);
3405 if !y_flipped {
3406 current_position.y += size.height + MENU_GAP;
3407 } else {
3408 current_position.y -= MENU_GAP;
3409 }
3410 (popover_type, Bounds::new(position, size))
3411 })
3412 .collect::<Vec<_>>();
3413
3414 if y_flipped {
3415 laid_out_popovers.reverse();
3416 }
3417
3418 Some((laid_out_popovers, y_flipped))
3419 }
3420
3421 #[allow(clippy::too_many_arguments)]
3422 fn layout_context_menu_aside(
3423 &self,
3424 y_flipped: bool,
3425 menu_bounds: Bounds<Pixels>,
3426 target_bounds: Bounds<Pixels>,
3427 max_target_bounds: Bounds<Pixels>,
3428 max_height: Pixels,
3429 must_place_above_or_below: bool,
3430 text_hitbox: &Hitbox,
3431 viewport_bounds: Bounds<Pixels>,
3432 window: &mut Window,
3433 cx: &mut App,
3434 ) {
3435 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3436 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3437 && !must_place_above_or_below
3438 {
3439 let max_width = cmp::min(
3440 available_within_viewport.right - px(1.),
3441 MENU_ASIDE_MAX_WIDTH,
3442 );
3443 let Some(mut aside) =
3444 self.render_context_menu_aside(size(max_width, max_height - POPOVER_Y_PADDING), cx)
3445 else {
3446 return;
3447 };
3448 aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3449 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3450 Some((aside, right_position))
3451 } else {
3452 let max_size = size(
3453 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3454 // won't be needed here.
3455 cmp::min(
3456 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3457 viewport_bounds.right(),
3458 ),
3459 cmp::min(
3460 max_height,
3461 cmp::max(
3462 available_within_viewport.top,
3463 available_within_viewport.bottom,
3464 ),
3465 ) - POPOVER_Y_PADDING,
3466 );
3467 let Some(mut aside) = self.render_context_menu_aside(max_size, cx) else {
3468 return;
3469 };
3470 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3471
3472 let top_position = point(
3473 menu_bounds.origin.x,
3474 target_bounds.top() - actual_size.height,
3475 );
3476 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3477
3478 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3479 // Prefer to fit on the same side of the line as the menu, then on the other side of
3480 // the line.
3481 if !y_flipped && wanted.height < available.bottom {
3482 Some(bottom_position)
3483 } else if !y_flipped && wanted.height < available.top {
3484 Some(top_position)
3485 } else if y_flipped && wanted.height < available.top {
3486 Some(top_position)
3487 } else if y_flipped && wanted.height < available.bottom {
3488 Some(bottom_position)
3489 } else {
3490 None
3491 }
3492 };
3493
3494 // Prefer choosing a direction using max sizes rather than actual size for stability.
3495 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3496 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3497 let aside_position = fit_within(available_within_text, wanted)
3498 // Fallback: fit max size in window.
3499 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3500 // Fallback: fit actual size in window.
3501 .or_else(|| fit_within(available_within_viewport, actual_size));
3502
3503 aside_position.map(|position| (aside, position))
3504 };
3505
3506 // Skip drawing if it doesn't fit anywhere.
3507 if let Some((aside, position)) = positioned_aside {
3508 window.defer_draw(aside, position, 1);
3509 }
3510 }
3511
3512 fn render_context_menu(
3513 &self,
3514 line_height: Pixels,
3515 height: Pixels,
3516 y_flipped: bool,
3517 window: &mut Window,
3518 cx: &mut App,
3519 ) -> Option<AnyElement> {
3520 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3521 self.editor.update(cx, |editor, cx| {
3522 editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3523 })
3524 }
3525
3526 fn render_context_menu_aside(
3527 &self,
3528 max_size: Size<Pixels>,
3529
3530 cx: &mut App,
3531 ) -> Option<AnyElement> {
3532 if max_size.width < px(100.) || max_size.height < px(12.) {
3533 None
3534 } else {
3535 self.editor.update(cx, |editor, cx| {
3536 editor.render_context_menu_aside(&self.style, max_size, cx)
3537 })
3538 }
3539 }
3540
3541 #[allow(clippy::too_many_arguments)]
3542 fn layout_edit_prediction_popover(
3543 &self,
3544 text_bounds: &Bounds<Pixels>,
3545 content_origin: gpui::Point<Pixels>,
3546 editor_snapshot: &EditorSnapshot,
3547 visible_row_range: Range<DisplayRow>,
3548 scroll_top: f32,
3549 scroll_bottom: f32,
3550 line_layouts: &[LineWithInvisibles],
3551 line_height: Pixels,
3552 scroll_pixel_position: gpui::Point<Pixels>,
3553 newest_selection_head: Option<DisplayPoint>,
3554 editor_width: Pixels,
3555 style: &EditorStyle,
3556 window: &mut Window,
3557 cx: &mut App,
3558 ) -> Option<AnyElement> {
3559 const PADDING_X: Pixels = Pixels(24.);
3560 const PADDING_Y: Pixels = Pixels(2.);
3561
3562 let editor = self.editor.read(cx);
3563 let active_inline_completion = editor.active_inline_completion.as_ref()?;
3564
3565 if editor.edit_prediction_visible_in_cursor_popover(true) {
3566 return None;
3567 }
3568
3569 // Adjust text origin for horizontal scrolling (in some cases here)
3570 let start_point = content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
3571
3572 // Clamp left offset after extreme scrollings
3573 let clamp_start = |point: gpui::Point<Pixels>| gpui::Point {
3574 x: point.x.max(content_origin.x),
3575 y: point.y,
3576 };
3577
3578 match &active_inline_completion.completion {
3579 InlineCompletion::Move { target, .. } => {
3580 let target_display_point = target.to_display_point(editor_snapshot);
3581
3582 if editor.edit_prediction_requires_modifier() {
3583 if !editor.edit_prediction_preview_is_active() {
3584 return None;
3585 }
3586
3587 if target_display_point.row() < visible_row_range.start {
3588 let mut element = editor
3589 .render_edit_prediction_line_popover(
3590 "Scroll",
3591 Some(IconName::ArrowUp),
3592 window,
3593 cx,
3594 )?
3595 .into_any();
3596
3597 element.layout_as_root(AvailableSpace::min_size(), window, cx);
3598
3599 let cursor = newest_selection_head?;
3600 let cursor_row_layout = line_layouts
3601 .get(cursor.row().minus(visible_row_range.start) as usize)?;
3602 let cursor_column = cursor.column() as usize;
3603
3604 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
3605
3606 const PADDING_Y: Pixels = px(12.);
3607
3608 let origin = start_point + point(cursor_character_x, PADDING_Y);
3609
3610 element.prepaint_at(origin, window, cx);
3611 return Some(element);
3612 } else if target_display_point.row() >= visible_row_range.end {
3613 let mut element = editor
3614 .render_edit_prediction_line_popover(
3615 "Scroll",
3616 Some(IconName::ArrowDown),
3617 window,
3618 cx,
3619 )?
3620 .into_any();
3621
3622 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3623
3624 let cursor = newest_selection_head?;
3625 let cursor_row_layout = line_layouts
3626 .get(cursor.row().minus(visible_row_range.start) as usize)?;
3627 let cursor_column = cursor.column() as usize;
3628
3629 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
3630 const PADDING_Y: Pixels = px(12.);
3631
3632 let origin = start_point
3633 + point(
3634 cursor_character_x,
3635 text_bounds.size.height - size.height - PADDING_Y,
3636 );
3637
3638 element.prepaint_at(origin, window, cx);
3639 return Some(element);
3640 } else {
3641 const POLE_WIDTH: Pixels = px(2.);
3642
3643 let mut element = v_flex()
3644 .child(
3645 editor
3646 .render_edit_prediction_line_popover("Jump", None, window, cx)?
3647 .rounded_br(px(0.))
3648 .rounded_tr(px(0.))
3649 .border_r_2(),
3650 )
3651 .child(
3652 div()
3653 .w(POLE_WIDTH)
3654 .bg(cx.theme().colors().text_accent.opacity(0.8))
3655 .h(line_height),
3656 )
3657 .items_end()
3658 .into_any();
3659
3660 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3661
3662 let line_layout =
3663 line_layouts
3664 .get(target_display_point.row().minus(visible_row_range.start)
3665 as usize)?;
3666 let target_column = target_display_point.column() as usize;
3667
3668 let target_x = line_layout.x_for_index(target_column);
3669 let target_y = (target_display_point.row().as_f32() * line_height)
3670 - scroll_pixel_position.y;
3671
3672 let origin = clamp_start(
3673 start_point + point(target_x, target_y)
3674 - point(size.width - POLE_WIDTH, size.height - line_height),
3675 );
3676
3677 element.prepaint_at(origin, window, cx);
3678
3679 return Some(element);
3680 }
3681 }
3682
3683 if target_display_point.row().as_f32() < scroll_top {
3684 let mut element = editor
3685 .render_edit_prediction_line_popover(
3686 "Jump to Edit",
3687 Some(IconName::ArrowUp),
3688 window,
3689 cx,
3690 )?
3691 .into_any();
3692
3693 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3694 let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
3695
3696 element.prepaint_at(text_bounds.origin + offset, window, cx);
3697 Some(element)
3698 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
3699 let mut element = editor
3700 .render_edit_prediction_line_popover(
3701 "Jump to Edit",
3702 Some(IconName::ArrowDown),
3703 window,
3704 cx,
3705 )?
3706 .into_any();
3707
3708 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3709 let offset = point(
3710 (text_bounds.size.width - size.width) / 2.,
3711 text_bounds.size.height - size.height - PADDING_Y,
3712 );
3713
3714 element.prepaint_at(text_bounds.origin + offset, window, cx);
3715 Some(element)
3716 } else {
3717 let mut element = editor
3718 .render_edit_prediction_line_popover("Jump to Edit", None, window, cx)?
3719 .into_any();
3720 let target_line_end = DisplayPoint::new(
3721 target_display_point.row(),
3722 editor_snapshot.line_len(target_display_point.row()),
3723 );
3724 let origin = self.editor.update(cx, |editor, _cx| {
3725 editor.display_to_pixel_point(target_line_end, editor_snapshot, window)
3726 })?;
3727
3728 element.prepaint_as_root(
3729 clamp_start(start_point + origin + point(PADDING_X, px(0.))),
3730 AvailableSpace::min_size(),
3731 window,
3732 cx,
3733 );
3734 Some(element)
3735 }
3736 }
3737 InlineCompletion::Edit {
3738 edits,
3739 edit_preview,
3740 display_mode,
3741 snapshot,
3742 } => {
3743 if self.editor.read(cx).has_visible_completions_menu() {
3744 return None;
3745 }
3746
3747 let edit_start = edits
3748 .first()
3749 .unwrap()
3750 .0
3751 .start
3752 .to_display_point(editor_snapshot);
3753 let edit_end = edits
3754 .last()
3755 .unwrap()
3756 .0
3757 .end
3758 .to_display_point(editor_snapshot);
3759
3760 let is_visible = visible_row_range.contains(&edit_start.row())
3761 || visible_row_range.contains(&edit_end.row());
3762 if !is_visible {
3763 return None;
3764 }
3765
3766 match display_mode {
3767 EditDisplayMode::TabAccept => {
3768 let range = &edits.first()?.0;
3769 let target_display_point = range.end.to_display_point(editor_snapshot);
3770
3771 let target_line_end = DisplayPoint::new(
3772 target_display_point.row(),
3773 editor_snapshot.line_len(target_display_point.row()),
3774 );
3775 let (mut element, origin) = self.editor.update(cx, |editor, cx| {
3776 Some((
3777 editor
3778 .render_edit_prediction_line_popover(
3779 "Accept", None, window, cx,
3780 )?
3781 .into_any(),
3782 editor.display_to_pixel_point(
3783 target_line_end,
3784 editor_snapshot,
3785 window,
3786 )?,
3787 ))
3788 })?;
3789
3790 element.prepaint_as_root(
3791 clamp_start(start_point + origin + point(PADDING_X, px(0.))),
3792 AvailableSpace::min_size(),
3793 window,
3794 cx,
3795 );
3796 return Some(element);
3797 }
3798 EditDisplayMode::Inline => return None,
3799 EditDisplayMode::DiffPopover => {}
3800 }
3801
3802 let highlighted_edits = crate::inline_completion_edit_text(
3803 &snapshot,
3804 edits,
3805 edit_preview.as_ref()?,
3806 false,
3807 cx,
3808 );
3809
3810 let styled_text = highlighted_edits.to_styled_text(&style.text);
3811 let line_count = highlighted_edits.text.lines().count();
3812
3813 const BORDER_WIDTH: Pixels = px(1.);
3814
3815 let mut element = h_flex()
3816 .items_start()
3817 .child(
3818 h_flex()
3819 .bg(cx.theme().colors().editor_background)
3820 .border(BORDER_WIDTH)
3821 .shadow_sm()
3822 .border_color(cx.theme().colors().border)
3823 .rounded_l_lg()
3824 .when(line_count > 1, |el| el.rounded_br_lg())
3825 .pr_1()
3826 .child(styled_text),
3827 )
3828 .child(
3829 h_flex()
3830 .h(line_height + BORDER_WIDTH * px(2.))
3831 .px_1p5()
3832 .gap_1()
3833 // Workaround: For some reason, there's a gap if we don't do this
3834 .ml(-BORDER_WIDTH)
3835 .shadow(smallvec![gpui::BoxShadow {
3836 color: gpui::black().opacity(0.05),
3837 offset: point(px(1.), px(1.)),
3838 blur_radius: px(2.),
3839 spread_radius: px(0.),
3840 }])
3841 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
3842 .border(BORDER_WIDTH)
3843 .border_color(cx.theme().colors().border)
3844 .rounded_r_lg()
3845 .children(editor.render_edit_prediction_accept_keybind(window, cx)),
3846 )
3847 .into_any();
3848
3849 let longest_row =
3850 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
3851 let longest_line_width = if visible_row_range.contains(&longest_row) {
3852 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
3853 } else {
3854 layout_line(
3855 longest_row,
3856 editor_snapshot,
3857 style,
3858 editor_width,
3859 |_| false,
3860 window,
3861 cx,
3862 )
3863 .width
3864 };
3865
3866 let viewport_bounds = Bounds::new(Default::default(), window.viewport_size())
3867 .extend(Edges {
3868 right: -Self::SCROLLBAR_WIDTH,
3869 ..Default::default()
3870 });
3871
3872 let x_after_longest =
3873 text_bounds.origin.x + longest_line_width + PADDING_X - scroll_pixel_position.x;
3874
3875 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3876
3877 // Fully visible if it can be displayed within the window (allow overlapping other
3878 // panes). However, this is only allowed if the popover starts within text_bounds.
3879 let can_position_to_the_right = x_after_longest < text_bounds.right()
3880 && x_after_longest + element_bounds.width < viewport_bounds.right();
3881
3882 let mut origin = if can_position_to_the_right {
3883 point(
3884 x_after_longest,
3885 text_bounds.origin.y + edit_start.row().as_f32() * line_height
3886 - scroll_pixel_position.y,
3887 )
3888 } else {
3889 let cursor_row = newest_selection_head.map(|head| head.row());
3890 let above_edit = edit_start
3891 .row()
3892 .0
3893 .checked_sub(line_count as u32)
3894 .map(DisplayRow);
3895 let below_edit = Some(edit_end.row() + 1);
3896 let above_cursor = cursor_row
3897 .and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
3898 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
3899
3900 // Place the edit popover adjacent to the edit if there is a location
3901 // available that is onscreen and does not obscure the cursor. Otherwise,
3902 // place it adjacent to the cursor.
3903 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
3904 .into_iter()
3905 .flatten()
3906 .find(|&start_row| {
3907 let end_row = start_row + line_count as u32;
3908 visible_row_range.contains(&start_row)
3909 && visible_row_range.contains(&end_row)
3910 && cursor_row.map_or(true, |cursor_row| {
3911 !((start_row..end_row).contains(&cursor_row))
3912 })
3913 })?;
3914
3915 content_origin
3916 + point(
3917 -scroll_pixel_position.x,
3918 row_target.as_f32() * line_height - scroll_pixel_position.y,
3919 )
3920 };
3921
3922 origin.x -= BORDER_WIDTH;
3923
3924 window.defer_draw(element, origin, 1);
3925
3926 // Do not return an element, since it will already be drawn due to defer_draw.
3927 None
3928 }
3929 }
3930 }
3931
3932 fn layout_mouse_context_menu(
3933 &self,
3934 editor_snapshot: &EditorSnapshot,
3935 visible_range: Range<DisplayRow>,
3936 content_origin: gpui::Point<Pixels>,
3937 window: &mut Window,
3938 cx: &mut App,
3939 ) -> Option<AnyElement> {
3940 let position = self.editor.update(cx, |editor, _cx| {
3941 let visible_start_point = editor.display_to_pixel_point(
3942 DisplayPoint::new(visible_range.start, 0),
3943 editor_snapshot,
3944 window,
3945 )?;
3946 let visible_end_point = editor.display_to_pixel_point(
3947 DisplayPoint::new(visible_range.end, 0),
3948 editor_snapshot,
3949 window,
3950 )?;
3951
3952 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3953 let (source_display_point, position) = match mouse_context_menu.position {
3954 MenuPosition::PinnedToScreen(point) => (None, point),
3955 MenuPosition::PinnedToEditor { source, offset } => {
3956 let source_display_point = source.to_display_point(editor_snapshot);
3957 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3958 let position = content_origin + source_point + offset;
3959 (Some(source_display_point), position)
3960 }
3961 };
3962
3963 let source_included = source_display_point.map_or(true, |source_display_point| {
3964 visible_range
3965 .to_inclusive()
3966 .contains(&source_display_point.row())
3967 });
3968 let position_included =
3969 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3970 if !source_included && !position_included {
3971 None
3972 } else {
3973 Some(position)
3974 }
3975 })?;
3976
3977 let mut element = self.editor.update(cx, |editor, _| {
3978 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3979 let context_menu = mouse_context_menu.context_menu.clone();
3980
3981 Some(
3982 deferred(
3983 anchored()
3984 .position(position)
3985 .child(context_menu)
3986 .anchor(Corner::TopLeft)
3987 .snap_to_window_with_margin(px(8.)),
3988 )
3989 .with_priority(1)
3990 .into_any(),
3991 )
3992 })?;
3993
3994 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3995 Some(element)
3996 }
3997
3998 #[allow(clippy::too_many_arguments)]
3999 fn layout_hover_popovers(
4000 &self,
4001 snapshot: &EditorSnapshot,
4002 hitbox: &Hitbox,
4003 text_hitbox: &Hitbox,
4004 visible_display_row_range: Range<DisplayRow>,
4005 content_origin: gpui::Point<Pixels>,
4006 scroll_pixel_position: gpui::Point<Pixels>,
4007 line_layouts: &[LineWithInvisibles],
4008 line_height: Pixels,
4009 em_width: Pixels,
4010 window: &mut Window,
4011 cx: &mut App,
4012 ) {
4013 struct MeasuredHoverPopover {
4014 element: AnyElement,
4015 size: Size<Pixels>,
4016 horizontal_offset: Pixels,
4017 }
4018
4019 let max_size = size(
4020 (120. * em_width) // Default size
4021 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4022 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4023 (16. * line_height) // Default size
4024 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4025 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4026 );
4027
4028 let hover_popovers = self.editor.update(cx, |editor, cx| {
4029 editor
4030 .hover_state
4031 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
4032 });
4033 let Some((position, hover_popovers)) = hover_popovers else {
4034 return;
4035 };
4036
4037 // This is safe because we check on layout whether the required row is available
4038 let hovered_row_layout =
4039 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
4040
4041 // Compute Hovered Point
4042 let x =
4043 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
4044 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
4045 let hovered_point = content_origin + point(x, y);
4046
4047 let mut overall_height = Pixels::ZERO;
4048 let mut measured_hover_popovers = Vec::new();
4049 for mut hover_popover in hover_popovers {
4050 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
4051 let horizontal_offset =
4052 (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
4053
4054 overall_height += HOVER_POPOVER_GAP + size.height;
4055
4056 measured_hover_popovers.push(MeasuredHoverPopover {
4057 element: hover_popover,
4058 size,
4059 horizontal_offset,
4060 });
4061 }
4062 overall_height += HOVER_POPOVER_GAP;
4063
4064 fn draw_occluder(
4065 width: Pixels,
4066 origin: gpui::Point<Pixels>,
4067 window: &mut Window,
4068 cx: &mut App,
4069 ) {
4070 let mut occlusion = div()
4071 .size_full()
4072 .occlude()
4073 .on_mouse_move(|_, _, cx| cx.stop_propagation())
4074 .into_any_element();
4075 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4076 window.defer_draw(occlusion, origin, 2);
4077 }
4078
4079 if hovered_point.y > overall_height {
4080 // There is enough space above. Render popovers above the hovered point
4081 let mut current_y = hovered_point.y;
4082 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4083 let size = popover.size;
4084 let popover_origin = point(
4085 hovered_point.x + popover.horizontal_offset,
4086 current_y - size.height,
4087 );
4088
4089 window.defer_draw(popover.element, popover_origin, 2);
4090 if position != itertools::Position::Last {
4091 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4092 draw_occluder(size.width, origin, window, cx);
4093 }
4094
4095 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4096 }
4097 } else {
4098 // There is not enough space above. Render popovers below the hovered point
4099 let mut current_y = hovered_point.y + line_height;
4100 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4101 let size = popover.size;
4102 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4103
4104 window.defer_draw(popover.element, popover_origin, 2);
4105 if position != itertools::Position::Last {
4106 let origin = point(popover_origin.x, popover_origin.y + size.height);
4107 draw_occluder(size.width, origin, window, cx);
4108 }
4109
4110 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4111 }
4112 }
4113 }
4114
4115 #[allow(clippy::too_many_arguments)]
4116 fn layout_diff_hunk_controls(
4117 &self,
4118 row_range: Range<DisplayRow>,
4119 row_infos: &[RowInfo],
4120 text_hitbox: &Hitbox,
4121 position_map: &PositionMap,
4122 newest_cursor_position: Option<DisplayPoint>,
4123 line_height: Pixels,
4124 scroll_pixel_position: gpui::Point<Pixels>,
4125 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4126 editor: Entity<Editor>,
4127 window: &mut Window,
4128 cx: &mut App,
4129 ) -> Vec<AnyElement> {
4130 let point_for_position = position_map.point_for_position(window.mouse_position());
4131
4132 let mut controls = vec![];
4133
4134 let active_positions = [
4135 Some(point_for_position.previous_valid),
4136 newest_cursor_position,
4137 ];
4138
4139 for (hunk, _) in display_hunks {
4140 if let DisplayDiffHunk::Unfolded {
4141 display_row_range,
4142 multi_buffer_range,
4143 status,
4144 ..
4145 } = &hunk
4146 {
4147 if display_row_range.start < row_range.start
4148 || display_row_range.start >= row_range.end
4149 {
4150 continue;
4151 }
4152 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4153 if row_infos[row_ix].diff_status.is_none() {
4154 continue;
4155 }
4156 if matches!(
4157 row_infos[row_ix].diff_status,
4158 Some(DiffHunkStatus::Added(_))
4159 ) && !matches!(*status, DiffHunkStatus::Added(_))
4160 {
4161 continue;
4162 }
4163 if active_positions
4164 .iter()
4165 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4166 {
4167 let y = display_row_range.start.as_f32() * line_height
4168 + text_hitbox.bounds.top()
4169 - scroll_pixel_position.y;
4170 let x = text_hitbox.bounds.right() - px(100.);
4171
4172 let mut element = diff_hunk_controls(
4173 display_row_range.start.0,
4174 multi_buffer_range.clone(),
4175 line_height,
4176 &editor,
4177 cx,
4178 );
4179 element.prepaint_as_root(
4180 gpui::Point::new(x, y),
4181 size(px(100.0), line_height).into(),
4182 window,
4183 cx,
4184 );
4185 controls.push(element);
4186 }
4187 }
4188 }
4189
4190 controls
4191 }
4192
4193 #[allow(clippy::too_many_arguments)]
4194 fn layout_signature_help(
4195 &self,
4196 hitbox: &Hitbox,
4197 content_origin: gpui::Point<Pixels>,
4198 scroll_pixel_position: gpui::Point<Pixels>,
4199 newest_selection_head: Option<DisplayPoint>,
4200 start_row: DisplayRow,
4201 line_layouts: &[LineWithInvisibles],
4202 line_height: Pixels,
4203 em_width: Pixels,
4204 window: &mut Window,
4205 cx: &mut App,
4206 ) {
4207 if !self.editor.focus_handle(cx).is_focused(window) {
4208 return;
4209 }
4210 let Some(newest_selection_head) = newest_selection_head else {
4211 return;
4212 };
4213 let selection_row = newest_selection_head.row();
4214 if selection_row < start_row {
4215 return;
4216 }
4217 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4218 else {
4219 return;
4220 };
4221
4222 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4223 - scroll_pixel_position.x
4224 + content_origin.x;
4225 let start_y =
4226 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4227
4228 let max_size = size(
4229 (120. * em_width) // Default size
4230 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4231 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4232 (16. * line_height) // Default size
4233 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4234 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4235 );
4236
4237 let maybe_element = self.editor.update(cx, |editor, cx| {
4238 if let Some(popover) = editor.signature_help_state.popover_mut() {
4239 let element = popover.render(
4240 &self.style,
4241 max_size,
4242 editor.workspace.as_ref().map(|(w, _)| w.clone()),
4243 cx,
4244 );
4245 Some(element)
4246 } else {
4247 None
4248 }
4249 });
4250 if let Some(mut element) = maybe_element {
4251 let window_size = window.viewport_size();
4252 let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4253 let mut point = point(start_x, start_y - size.height);
4254
4255 // Adjusting to ensure the popover does not overflow in the X-axis direction.
4256 if point.x + size.width >= window_size.width {
4257 point.x = window_size.width - size.width;
4258 }
4259
4260 window.defer_draw(element, point, 1)
4261 }
4262 }
4263
4264 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4265 window.paint_layer(layout.hitbox.bounds, |window| {
4266 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4267 let gutter_bg = cx.theme().colors().editor_gutter_background;
4268 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4269 window.paint_quad(fill(
4270 layout.position_map.text_hitbox.bounds,
4271 self.style.background,
4272 ));
4273
4274 if let EditorMode::Full = layout.mode {
4275 let mut active_rows = layout.active_rows.iter().peekable();
4276 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4277 let mut end_row = start_row.0;
4278 while active_rows
4279 .peek()
4280 .map_or(false, |(active_row, has_selection)| {
4281 active_row.0 == end_row + 1
4282 && *has_selection == contains_non_empty_selection
4283 })
4284 {
4285 active_rows.next().unwrap();
4286 end_row += 1;
4287 }
4288
4289 if !contains_non_empty_selection {
4290 let highlight_h_range =
4291 match layout.position_map.snapshot.current_line_highlight {
4292 CurrentLineHighlight::Gutter => Some(Range {
4293 start: layout.hitbox.left(),
4294 end: layout.gutter_hitbox.right(),
4295 }),
4296 CurrentLineHighlight::Line => Some(Range {
4297 start: layout.position_map.text_hitbox.bounds.left(),
4298 end: layout.position_map.text_hitbox.bounds.right(),
4299 }),
4300 CurrentLineHighlight::All => Some(Range {
4301 start: layout.hitbox.left(),
4302 end: layout.hitbox.right(),
4303 }),
4304 CurrentLineHighlight::None => None,
4305 };
4306 if let Some(range) = highlight_h_range {
4307 let active_line_bg = cx.theme().colors().editor_active_line_background;
4308 let bounds = Bounds {
4309 origin: point(
4310 range.start,
4311 layout.hitbox.origin.y
4312 + (start_row.as_f32() - scroll_top)
4313 * layout.position_map.line_height,
4314 ),
4315 size: size(
4316 range.end - range.start,
4317 layout.position_map.line_height
4318 * (end_row - start_row.0 + 1) as f32,
4319 ),
4320 };
4321 window.paint_quad(fill(bounds, active_line_bg));
4322 }
4323 }
4324 }
4325
4326 let mut paint_highlight =
4327 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4328 let origin = point(
4329 layout.hitbox.origin.x,
4330 layout.hitbox.origin.y
4331 + (highlight_row_start.as_f32() - scroll_top)
4332 * layout.position_map.line_height,
4333 );
4334 let size = size(
4335 layout.hitbox.size.width,
4336 layout.position_map.line_height
4337 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4338 );
4339 window.paint_quad(fill(Bounds { origin, size }, color));
4340 };
4341
4342 let mut current_paint: Option<(gpui::Background, Range<DisplayRow>)> = None;
4343 for (&new_row, &new_background) in &layout.highlighted_rows {
4344 match &mut current_paint {
4345 Some((current_background, current_range)) => {
4346 let current_background = *current_background;
4347 let new_range_started = current_background != new_background
4348 || current_range.end.next_row() != new_row;
4349 if new_range_started {
4350 paint_highlight(
4351 current_range.start,
4352 current_range.end,
4353 current_background,
4354 );
4355 current_paint = Some((new_background, new_row..new_row));
4356 continue;
4357 } else {
4358 current_range.end = current_range.end.next_row();
4359 }
4360 }
4361 None => current_paint = Some((new_background, new_row..new_row)),
4362 };
4363 }
4364 if let Some((color, range)) = current_paint {
4365 paint_highlight(range.start, range.end, color);
4366 }
4367
4368 let scroll_left =
4369 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4370
4371 for (wrap_position, active) in layout.wrap_guides.iter() {
4372 let x = (layout.position_map.text_hitbox.origin.x
4373 + *wrap_position
4374 + layout.position_map.em_width / 2.)
4375 - scroll_left;
4376
4377 let show_scrollbars = {
4378 let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4379
4380 scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4381 || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4382 };
4383
4384 if x < layout.position_map.text_hitbox.origin.x
4385 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4386 {
4387 continue;
4388 }
4389
4390 let color = if *active {
4391 cx.theme().colors().editor_active_wrap_guide
4392 } else {
4393 cx.theme().colors().editor_wrap_guide
4394 };
4395 window.paint_quad(fill(
4396 Bounds {
4397 origin: point(x, layout.position_map.text_hitbox.origin.y),
4398 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4399 },
4400 color,
4401 ));
4402 }
4403 }
4404 })
4405 }
4406
4407 fn paint_indent_guides(
4408 &mut self,
4409 layout: &mut EditorLayout,
4410 window: &mut Window,
4411 cx: &mut App,
4412 ) {
4413 let Some(indent_guides) = &layout.indent_guides else {
4414 return;
4415 };
4416
4417 let faded_color = |color: Hsla, alpha: f32| {
4418 let mut faded = color;
4419 faded.a = alpha;
4420 faded
4421 };
4422
4423 for indent_guide in indent_guides {
4424 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4425 let settings = indent_guide.settings;
4426
4427 // TODO fixed for now, expose them through themes later
4428 const INDENT_AWARE_ALPHA: f32 = 0.2;
4429 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4430 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4431 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4432
4433 let line_color = match (settings.coloring, indent_guide.active) {
4434 (IndentGuideColoring::Disabled, _) => None,
4435 (IndentGuideColoring::Fixed, false) => {
4436 Some(cx.theme().colors().editor_indent_guide)
4437 }
4438 (IndentGuideColoring::Fixed, true) => {
4439 Some(cx.theme().colors().editor_indent_guide_active)
4440 }
4441 (IndentGuideColoring::IndentAware, false) => {
4442 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4443 }
4444 (IndentGuideColoring::IndentAware, true) => {
4445 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4446 }
4447 };
4448
4449 let background_color = match (settings.background_coloring, indent_guide.active) {
4450 (IndentGuideBackgroundColoring::Disabled, _) => None,
4451 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4452 indent_accent_colors,
4453 INDENT_AWARE_BACKGROUND_ALPHA,
4454 )),
4455 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4456 indent_accent_colors,
4457 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4458 )),
4459 };
4460
4461 let requested_line_width = if indent_guide.active {
4462 settings.active_line_width
4463 } else {
4464 settings.line_width
4465 }
4466 .clamp(1, 10);
4467 let mut line_indicator_width = 0.;
4468 if let Some(color) = line_color {
4469 window.paint_quad(fill(
4470 Bounds {
4471 origin: indent_guide.origin,
4472 size: size(px(requested_line_width as f32), indent_guide.length),
4473 },
4474 color,
4475 ));
4476 line_indicator_width = requested_line_width as f32;
4477 }
4478
4479 if let Some(color) = background_color {
4480 let width = indent_guide.single_indent_width - px(line_indicator_width);
4481 window.paint_quad(fill(
4482 Bounds {
4483 origin: point(
4484 indent_guide.origin.x + px(line_indicator_width),
4485 indent_guide.origin.y,
4486 ),
4487 size: size(width, indent_guide.length),
4488 },
4489 color,
4490 ));
4491 }
4492 }
4493 }
4494
4495 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4496 let is_singleton = self.editor.read(cx).is_singleton(cx);
4497
4498 let line_height = layout.position_map.line_height;
4499 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4500
4501 for LineNumberLayout {
4502 shaped_line,
4503 hitbox,
4504 display_row,
4505 } in layout.line_numbers.values()
4506 {
4507 let Some(hitbox) = hitbox else {
4508 continue;
4509 };
4510
4511 let is_active = layout.active_rows.contains_key(&display_row);
4512
4513 let color = if is_active {
4514 cx.theme().colors().editor_active_line_number
4515 } else if !is_singleton && hitbox.is_hovered(window) {
4516 cx.theme().colors().editor_hover_line_number
4517 } else {
4518 cx.theme().colors().editor_line_number
4519 };
4520
4521 let Some(line) = self
4522 .shape_line_number(shaped_line.text.clone(), color, window)
4523 .log_err()
4524 else {
4525 continue;
4526 };
4527 let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4528 continue;
4529 };
4530 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4531 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4532 if is_singleton {
4533 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4534 } else {
4535 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4536 }
4537 }
4538 }
4539
4540 fn paint_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4541 if layout.display_hunks.is_empty() {
4542 return;
4543 }
4544
4545 let line_height = layout.position_map.line_height;
4546 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4547 for (hunk, hitbox) in &layout.display_hunks {
4548 let hunk_to_paint = match hunk {
4549 DisplayDiffHunk::Folded { .. } => {
4550 let hunk_bounds = Self::diff_hunk_bounds(
4551 &layout.position_map.snapshot,
4552 line_height,
4553 layout.gutter_hitbox.bounds,
4554 hunk,
4555 );
4556 Some((
4557 hunk_bounds,
4558 cx.theme().status().modified,
4559 Corners::all(px(0.)),
4560 &DiffHunkSecondaryStatus::None,
4561 ))
4562 }
4563 DisplayDiffHunk::Unfolded {
4564 status,
4565 display_row_range,
4566 ..
4567 } => hitbox.as_ref().map(|hunk_hitbox| match status {
4568 DiffHunkStatus::Added(secondary_status) => (
4569 hunk_hitbox.bounds,
4570 cx.theme().status().created,
4571 Corners::all(px(0.)),
4572 secondary_status,
4573 ),
4574 DiffHunkStatus::Modified(secondary_status) => (
4575 hunk_hitbox.bounds,
4576 cx.theme().status().modified,
4577 Corners::all(px(0.)),
4578 secondary_status,
4579 ),
4580 DiffHunkStatus::Removed(secondary_status)
4581 if !display_row_range.is_empty() =>
4582 {
4583 (
4584 hunk_hitbox.bounds,
4585 cx.theme().status().deleted,
4586 Corners::all(px(0.)),
4587 secondary_status,
4588 )
4589 }
4590 DiffHunkStatus::Removed(secondary_status) => (
4591 Bounds::new(
4592 point(
4593 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4594 hunk_hitbox.origin.y,
4595 ),
4596 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4597 ),
4598 cx.theme().status().deleted,
4599 Corners::all(1. * line_height),
4600 secondary_status,
4601 ),
4602 }),
4603 };
4604
4605 if let Some((hunk_bounds, mut background_color, corner_radii, secondary_status)) =
4606 hunk_to_paint
4607 {
4608 if *secondary_status != DiffHunkSecondaryStatus::None {
4609 background_color.a *= 0.6;
4610 }
4611 window.paint_quad(quad(
4612 hunk_bounds,
4613 corner_radii,
4614 background_color,
4615 Edges::default(),
4616 transparent_black(),
4617 ));
4618 }
4619 }
4620 });
4621 }
4622
4623 fn diff_hunk_bounds(
4624 snapshot: &EditorSnapshot,
4625 line_height: Pixels,
4626 gutter_bounds: Bounds<Pixels>,
4627 hunk: &DisplayDiffHunk,
4628 ) -> Bounds<Pixels> {
4629 let scroll_position = snapshot.scroll_position();
4630 let scroll_top = scroll_position.y * line_height;
4631 let gutter_strip_width = (0.275 * line_height).floor();
4632
4633 match hunk {
4634 DisplayDiffHunk::Folded { display_row, .. } => {
4635 let start_y = display_row.as_f32() * line_height - scroll_top;
4636 let end_y = start_y + line_height;
4637 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4638 let highlight_size = size(gutter_strip_width, end_y - start_y);
4639 Bounds::new(highlight_origin, highlight_size)
4640 }
4641 DisplayDiffHunk::Unfolded {
4642 display_row_range,
4643 status,
4644 ..
4645 } => {
4646 if status.is_removed() && display_row_range.is_empty() {
4647 let row = display_row_range.start;
4648
4649 let offset = line_height / 2.;
4650 let start_y = row.as_f32() * line_height - offset - scroll_top;
4651 let end_y = start_y + line_height;
4652
4653 let width = (0.35 * line_height).floor();
4654 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4655 let highlight_size = size(width, end_y - start_y);
4656 Bounds::new(highlight_origin, highlight_size)
4657 } else {
4658 let start_row = display_row_range.start;
4659 let end_row = display_row_range.end;
4660 // If we're in a multibuffer, row range span might include an
4661 // excerpt header, so if we were to draw the marker straight away,
4662 // the hunk might include the rows of that header.
4663 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4664 // Instead, we simply check whether the range we're dealing with includes
4665 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4666 let end_row_in_current_excerpt = snapshot
4667 .blocks_in_range(start_row..end_row)
4668 .find_map(|(start_row, block)| {
4669 if matches!(block, Block::ExcerptBoundary { .. }) {
4670 Some(start_row)
4671 } else {
4672 None
4673 }
4674 })
4675 .unwrap_or(end_row);
4676
4677 let start_y = start_row.as_f32() * line_height - scroll_top;
4678 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4679
4680 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4681 let highlight_size = size(gutter_strip_width, end_y - start_y);
4682 Bounds::new(highlight_origin, highlight_size)
4683 }
4684 }
4685 }
4686 }
4687
4688 fn paint_gutter_indicators(
4689 &self,
4690 layout: &mut EditorLayout,
4691 window: &mut Window,
4692 cx: &mut App,
4693 ) {
4694 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4695 window.with_element_namespace("crease_toggles", |window| {
4696 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4697 crease_toggle.paint(window, cx);
4698 }
4699 });
4700
4701 for test_indicator in layout.test_indicators.iter_mut() {
4702 test_indicator.paint(window, cx);
4703 }
4704
4705 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4706 indicator.paint(window, cx);
4707 }
4708 });
4709 }
4710
4711 fn paint_gutter_highlights(
4712 &self,
4713 layout: &mut EditorLayout,
4714 window: &mut Window,
4715 cx: &mut App,
4716 ) {
4717 for (_, hunk_hitbox) in &layout.display_hunks {
4718 if let Some(hunk_hitbox) = hunk_hitbox {
4719 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4720 }
4721 }
4722
4723 let show_git_gutter = layout
4724 .position_map
4725 .snapshot
4726 .show_git_diff_gutter
4727 .unwrap_or_else(|| {
4728 matches!(
4729 ProjectSettings::get_global(cx).git.git_gutter,
4730 Some(GitGutterSetting::TrackedFiles)
4731 )
4732 });
4733 if show_git_gutter {
4734 Self::paint_diff_hunks(layout, window, cx)
4735 }
4736
4737 let highlight_width = 0.275 * layout.position_map.line_height;
4738 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4739 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4740 for (range, color) in &layout.highlighted_gutter_ranges {
4741 let start_row = if range.start.row() < layout.visible_display_row_range.start {
4742 layout.visible_display_row_range.start - DisplayRow(1)
4743 } else {
4744 range.start.row()
4745 };
4746 let end_row = if range.end.row() > layout.visible_display_row_range.end {
4747 layout.visible_display_row_range.end + DisplayRow(1)
4748 } else {
4749 range.end.row()
4750 };
4751
4752 let start_y = layout.gutter_hitbox.top()
4753 + start_row.0 as f32 * layout.position_map.line_height
4754 - layout.position_map.scroll_pixel_position.y;
4755 let end_y = layout.gutter_hitbox.top()
4756 + (end_row.0 + 1) as f32 * layout.position_map.line_height
4757 - layout.position_map.scroll_pixel_position.y;
4758 let bounds = Bounds::from_corners(
4759 point(layout.gutter_hitbox.left(), start_y),
4760 point(layout.gutter_hitbox.left() + highlight_width, end_y),
4761 );
4762 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4763 }
4764 });
4765 }
4766
4767 fn paint_blamed_display_rows(
4768 &self,
4769 layout: &mut EditorLayout,
4770 window: &mut Window,
4771 cx: &mut App,
4772 ) {
4773 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4774 return;
4775 };
4776
4777 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4778 for mut blame_element in blamed_display_rows.into_iter() {
4779 blame_element.paint(window, cx);
4780 }
4781 })
4782 }
4783
4784 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4785 window.with_content_mask(
4786 Some(ContentMask {
4787 bounds: layout.position_map.text_hitbox.bounds,
4788 }),
4789 |window| {
4790 let cursor_style = if self
4791 .editor
4792 .read(cx)
4793 .hovered_link_state
4794 .as_ref()
4795 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4796 {
4797 CursorStyle::PointingHand
4798 } else {
4799 CursorStyle::IBeam
4800 };
4801 window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4802
4803 let invisible_display_ranges = self.paint_highlights(layout, window);
4804 self.paint_lines(&invisible_display_ranges, layout, window, cx);
4805 self.paint_redactions(layout, window);
4806 self.paint_cursors(layout, window, cx);
4807 self.paint_inline_blame(layout, window, cx);
4808 self.paint_diff_hunk_controls(layout, window, cx);
4809 window.with_element_namespace("crease_trailers", |window| {
4810 for trailer in layout.crease_trailers.iter_mut().flatten() {
4811 trailer.element.paint(window, cx);
4812 }
4813 });
4814 },
4815 )
4816 }
4817
4818 fn paint_highlights(
4819 &mut self,
4820 layout: &mut EditorLayout,
4821 window: &mut Window,
4822 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4823 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4824 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4825 let line_end_overshoot = 0.15 * layout.position_map.line_height;
4826 for (range, color) in &layout.highlighted_ranges {
4827 self.paint_highlighted_range(
4828 range.clone(),
4829 *color,
4830 Pixels::ZERO,
4831 line_end_overshoot,
4832 layout,
4833 window,
4834 );
4835 }
4836
4837 let corner_radius = 0.15 * layout.position_map.line_height;
4838
4839 for (player_color, selections) in &layout.selections {
4840 for selection in selections.iter() {
4841 self.paint_highlighted_range(
4842 selection.range.clone(),
4843 player_color.selection,
4844 corner_radius,
4845 corner_radius * 2.,
4846 layout,
4847 window,
4848 );
4849
4850 if selection.is_local && !selection.range.is_empty() {
4851 invisible_display_ranges.push(selection.range.clone());
4852 }
4853 }
4854 }
4855 invisible_display_ranges
4856 })
4857 }
4858
4859 fn paint_lines(
4860 &mut self,
4861 invisible_display_ranges: &[Range<DisplayPoint>],
4862 layout: &mut EditorLayout,
4863 window: &mut Window,
4864 cx: &mut App,
4865 ) {
4866 let whitespace_setting = self
4867 .editor
4868 .read(cx)
4869 .buffer
4870 .read(cx)
4871 .settings_at(0, cx)
4872 .show_whitespaces;
4873
4874 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4875 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4876 line_with_invisibles.draw(
4877 layout,
4878 row,
4879 layout.content_origin,
4880 whitespace_setting,
4881 invisible_display_ranges,
4882 window,
4883 cx,
4884 )
4885 }
4886
4887 for line_element in &mut layout.line_elements {
4888 line_element.paint(window, cx);
4889 }
4890 }
4891
4892 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4893 if layout.redacted_ranges.is_empty() {
4894 return;
4895 }
4896
4897 let line_end_overshoot = layout.line_end_overshoot();
4898
4899 // A softer than perfect black
4900 let redaction_color = gpui::rgb(0x0e1111);
4901
4902 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4903 for range in layout.redacted_ranges.iter() {
4904 self.paint_highlighted_range(
4905 range.clone(),
4906 redaction_color.into(),
4907 Pixels::ZERO,
4908 line_end_overshoot,
4909 layout,
4910 window,
4911 );
4912 }
4913 });
4914 }
4915
4916 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4917 for cursor in &mut layout.visible_cursors {
4918 cursor.paint(layout.content_origin, window, cx);
4919 }
4920 }
4921
4922 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4923 let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4924
4925 if let Some(scrollbar_layout) = scrollbar_x {
4926 let hitbox = scrollbar_layout.hitbox.clone();
4927 let text_unit_size = scrollbar_layout.text_unit_size;
4928 let visible_range = scrollbar_layout.visible_range.clone();
4929 let thumb_bounds = scrollbar_layout.thumb_bounds();
4930
4931 if scrollbar_layout.visible {
4932 window.paint_layer(hitbox.bounds, |window| {
4933 window.paint_quad(quad(
4934 hitbox.bounds,
4935 Corners::default(),
4936 cx.theme().colors().scrollbar_track_background,
4937 Edges {
4938 top: Pixels::ZERO,
4939 right: Pixels::ZERO,
4940 bottom: Pixels::ZERO,
4941 left: Pixels::ZERO,
4942 },
4943 cx.theme().colors().scrollbar_track_border,
4944 ));
4945
4946 window.paint_quad(quad(
4947 thumb_bounds,
4948 Corners::default(),
4949 cx.theme().colors().scrollbar_thumb_background,
4950 Edges {
4951 top: Pixels::ZERO,
4952 right: Pixels::ZERO,
4953 bottom: Pixels::ZERO,
4954 left: ScrollbarLayout::BORDER_WIDTH,
4955 },
4956 cx.theme().colors().scrollbar_thumb_border,
4957 ));
4958 })
4959 }
4960
4961 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4962
4963 window.on_mouse_event({
4964 let editor = self.editor.clone();
4965
4966 // there may be a way to avoid this clone
4967 let hitbox = hitbox.clone();
4968
4969 let mut mouse_position = window.mouse_position();
4970 move |event: &MouseMoveEvent, phase, window, cx| {
4971 if phase == DispatchPhase::Capture {
4972 return;
4973 }
4974
4975 editor.update(cx, |editor, cx| {
4976 if event.pressed_button == Some(MouseButton::Left)
4977 && editor
4978 .scroll_manager
4979 .is_dragging_scrollbar(Axis::Horizontal)
4980 {
4981 let x = mouse_position.x;
4982 let new_x = event.position.x;
4983 if (hitbox.left()..hitbox.right()).contains(&x) {
4984 let mut position = editor.scroll_position(cx);
4985
4986 position.x += (new_x - x) / text_unit_size;
4987 if position.x < 0.0 {
4988 position.x = 0.0;
4989 }
4990 editor.set_scroll_position(position, window, cx);
4991 }
4992
4993 cx.stop_propagation();
4994 } else {
4995 editor.scroll_manager.set_is_dragging_scrollbar(
4996 Axis::Horizontal,
4997 false,
4998 cx,
4999 );
5000
5001 if hitbox.is_hovered(window) {
5002 editor.scroll_manager.show_scrollbar(window, cx);
5003 }
5004 }
5005 mouse_position = event.position;
5006 })
5007 }
5008 });
5009
5010 if self
5011 .editor
5012 .read(cx)
5013 .scroll_manager
5014 .is_dragging_scrollbar(Axis::Horizontal)
5015 {
5016 window.on_mouse_event({
5017 let editor = self.editor.clone();
5018 move |_: &MouseUpEvent, phase, _, cx| {
5019 if phase == DispatchPhase::Capture {
5020 return;
5021 }
5022
5023 editor.update(cx, |editor, cx| {
5024 editor.scroll_manager.set_is_dragging_scrollbar(
5025 Axis::Horizontal,
5026 false,
5027 cx,
5028 );
5029 cx.stop_propagation();
5030 });
5031 }
5032 });
5033 } else {
5034 window.on_mouse_event({
5035 let editor = self.editor.clone();
5036
5037 move |event: &MouseDownEvent, phase, window, cx| {
5038 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5039 return;
5040 }
5041
5042 editor.update(cx, |editor, cx| {
5043 editor.scroll_manager.set_is_dragging_scrollbar(
5044 Axis::Horizontal,
5045 true,
5046 cx,
5047 );
5048
5049 let x = event.position.x;
5050
5051 if x < thumb_bounds.left() || thumb_bounds.right() < x {
5052 let center_row =
5053 ((x - hitbox.left()) / text_unit_size).round() as u32;
5054 let top_row = center_row.saturating_sub(
5055 (visible_range.end - visible_range.start) as u32 / 2,
5056 );
5057
5058 let mut position = editor.scroll_position(cx);
5059 position.x = top_row as f32;
5060
5061 editor.set_scroll_position(position, window, cx);
5062 } else {
5063 editor.scroll_manager.show_scrollbar(window, cx);
5064 }
5065
5066 cx.stop_propagation();
5067 });
5068 }
5069 });
5070 }
5071 }
5072
5073 if let Some(scrollbar_layout) = scrollbar_y {
5074 let hitbox = scrollbar_layout.hitbox.clone();
5075 let text_unit_size = scrollbar_layout.text_unit_size;
5076 let visible_range = scrollbar_layout.visible_range.clone();
5077 let thumb_bounds = scrollbar_layout.thumb_bounds();
5078
5079 if scrollbar_layout.visible {
5080 window.paint_layer(hitbox.bounds, |window| {
5081 window.paint_quad(quad(
5082 hitbox.bounds,
5083 Corners::default(),
5084 cx.theme().colors().scrollbar_track_background,
5085 Edges {
5086 top: Pixels::ZERO,
5087 right: Pixels::ZERO,
5088 bottom: Pixels::ZERO,
5089 left: ScrollbarLayout::BORDER_WIDTH,
5090 },
5091 cx.theme().colors().scrollbar_track_border,
5092 ));
5093
5094 let fast_markers =
5095 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5096 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5097 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5098
5099 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5100 for marker in markers.iter().chain(&fast_markers) {
5101 let mut marker = marker.clone();
5102 marker.bounds.origin += hitbox.origin;
5103 window.paint_quad(marker);
5104 }
5105
5106 window.paint_quad(quad(
5107 thumb_bounds,
5108 Corners::default(),
5109 cx.theme().colors().scrollbar_thumb_background,
5110 Edges {
5111 top: Pixels::ZERO,
5112 right: Pixels::ZERO,
5113 bottom: Pixels::ZERO,
5114 left: ScrollbarLayout::BORDER_WIDTH,
5115 },
5116 cx.theme().colors().scrollbar_thumb_border,
5117 ));
5118 });
5119 }
5120
5121 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5122
5123 window.on_mouse_event({
5124 let editor = self.editor.clone();
5125
5126 let hitbox = hitbox.clone();
5127
5128 let mut mouse_position = window.mouse_position();
5129 move |event: &MouseMoveEvent, phase, window, cx| {
5130 if phase == DispatchPhase::Capture {
5131 return;
5132 }
5133
5134 editor.update(cx, |editor, cx| {
5135 if event.pressed_button == Some(MouseButton::Left)
5136 && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5137 {
5138 let y = mouse_position.y;
5139 let new_y = event.position.y;
5140 if (hitbox.top()..hitbox.bottom()).contains(&y) {
5141 let mut position = editor.scroll_position(cx);
5142 position.y += (new_y - y) / text_unit_size;
5143 if position.y < 0.0 {
5144 position.y = 0.0;
5145 }
5146 editor.set_scroll_position(position, window, cx);
5147 }
5148 } else {
5149 editor.scroll_manager.set_is_dragging_scrollbar(
5150 Axis::Vertical,
5151 false,
5152 cx,
5153 );
5154
5155 if hitbox.is_hovered(window) {
5156 editor.scroll_manager.show_scrollbar(window, cx);
5157 }
5158 }
5159 mouse_position = event.position;
5160 })
5161 }
5162 });
5163
5164 if self
5165 .editor
5166 .read(cx)
5167 .scroll_manager
5168 .is_dragging_scrollbar(Axis::Vertical)
5169 {
5170 window.on_mouse_event({
5171 let editor = self.editor.clone();
5172 move |_: &MouseUpEvent, phase, _, cx| {
5173 if phase == DispatchPhase::Capture {
5174 return;
5175 }
5176
5177 editor.update(cx, |editor, cx| {
5178 editor.scroll_manager.set_is_dragging_scrollbar(
5179 Axis::Vertical,
5180 false,
5181 cx,
5182 );
5183 cx.stop_propagation();
5184 });
5185 }
5186 });
5187 } else {
5188 window.on_mouse_event({
5189 let editor = self.editor.clone();
5190
5191 move |event: &MouseDownEvent, phase, window, cx| {
5192 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5193 return;
5194 }
5195
5196 editor.update(cx, |editor, cx| {
5197 editor.scroll_manager.set_is_dragging_scrollbar(
5198 Axis::Vertical,
5199 true,
5200 cx,
5201 );
5202
5203 let y = event.position.y;
5204 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5205 let center_row =
5206 ((y - hitbox.top()) / text_unit_size).round() as u32;
5207 let top_row = center_row.saturating_sub(
5208 (visible_range.end - visible_range.start) as u32 / 2,
5209 );
5210 let mut position = editor.scroll_position(cx);
5211 position.y = top_row as f32;
5212 editor.set_scroll_position(position, window, cx);
5213 } else {
5214 editor.scroll_manager.show_scrollbar(window, cx);
5215 }
5216
5217 cx.stop_propagation();
5218 });
5219 }
5220 });
5221 }
5222 }
5223 }
5224
5225 fn collect_fast_scrollbar_markers(
5226 &self,
5227 layout: &EditorLayout,
5228 scrollbar_layout: &ScrollbarLayout,
5229 cx: &mut App,
5230 ) -> Vec<PaintQuad> {
5231 const LIMIT: usize = 100;
5232 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5233 return vec![];
5234 }
5235 let cursor_ranges = layout
5236 .cursors
5237 .iter()
5238 .map(|(point, color)| ColoredRange {
5239 start: point.row(),
5240 end: point.row(),
5241 color: *color,
5242 })
5243 .collect_vec();
5244 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5245 }
5246
5247 fn refresh_slow_scrollbar_markers(
5248 &self,
5249 layout: &EditorLayout,
5250 scrollbar_layout: &ScrollbarLayout,
5251 window: &mut Window,
5252 cx: &mut App,
5253 ) {
5254 self.editor.update(cx, |editor, cx| {
5255 if !editor.is_singleton(cx)
5256 || !editor
5257 .scrollbar_marker_state
5258 .should_refresh(scrollbar_layout.hitbox.size)
5259 {
5260 return;
5261 }
5262
5263 let scrollbar_layout = scrollbar_layout.clone();
5264 let background_highlights = editor.background_highlights.clone();
5265 let snapshot = layout.position_map.snapshot.clone();
5266 let theme = cx.theme().clone();
5267 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5268
5269 editor.scrollbar_marker_state.dirty = false;
5270 editor.scrollbar_marker_state.pending_refresh =
5271 Some(cx.spawn_in(window, |editor, mut cx| async move {
5272 let scrollbar_size = scrollbar_layout.hitbox.size;
5273 let scrollbar_markers = cx
5274 .background_executor()
5275 .spawn(async move {
5276 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5277 let mut marker_quads = Vec::new();
5278 if scrollbar_settings.git_diff {
5279 let marker_row_ranges =
5280 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5281 let start_display_row =
5282 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5283 .to_display_point(&snapshot.display_snapshot)
5284 .row();
5285 let mut end_display_row =
5286 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5287 .to_display_point(&snapshot.display_snapshot)
5288 .row();
5289 if end_display_row != start_display_row {
5290 end_display_row.0 -= 1;
5291 }
5292 let color = match &hunk.status() {
5293 DiffHunkStatus::Added(_) => theme.status().created,
5294 DiffHunkStatus::Modified(_) => theme.status().modified,
5295 DiffHunkStatus::Removed(_) => theme.status().deleted,
5296 };
5297 ColoredRange {
5298 start: start_display_row,
5299 end: end_display_row,
5300 color,
5301 }
5302 });
5303
5304 marker_quads.extend(
5305 scrollbar_layout
5306 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5307 );
5308 }
5309
5310 for (background_highlight_id, (_, background_ranges)) in
5311 background_highlights.iter()
5312 {
5313 let is_search_highlights = *background_highlight_id
5314 == TypeId::of::<BufferSearchHighlights>();
5315 let is_symbol_occurrences = *background_highlight_id
5316 == TypeId::of::<DocumentHighlightRead>()
5317 || *background_highlight_id
5318 == TypeId::of::<DocumentHighlightWrite>();
5319 if (is_search_highlights && scrollbar_settings.search_results)
5320 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5321 {
5322 let mut color = theme.status().info;
5323 if is_symbol_occurrences {
5324 color.fade_out(0.5);
5325 }
5326 let marker_row_ranges = background_ranges.iter().map(|range| {
5327 let display_start = range
5328 .start
5329 .to_display_point(&snapshot.display_snapshot);
5330 let display_end =
5331 range.end.to_display_point(&snapshot.display_snapshot);
5332 ColoredRange {
5333 start: display_start.row(),
5334 end: display_end.row(),
5335 color,
5336 }
5337 });
5338 marker_quads.extend(
5339 scrollbar_layout
5340 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5341 );
5342 }
5343 }
5344
5345 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5346 let diagnostics = snapshot
5347 .buffer_snapshot
5348 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5349 // Don't show diagnostics the user doesn't care about
5350 .filter(|diagnostic| {
5351 match (
5352 scrollbar_settings.diagnostics,
5353 diagnostic.diagnostic.severity,
5354 ) {
5355 (ScrollbarDiagnostics::All, _) => true,
5356 (
5357 ScrollbarDiagnostics::Error,
5358 DiagnosticSeverity::ERROR,
5359 ) => true,
5360 (
5361 ScrollbarDiagnostics::Warning,
5362 DiagnosticSeverity::ERROR
5363 | DiagnosticSeverity::WARNING,
5364 ) => true,
5365 (
5366 ScrollbarDiagnostics::Information,
5367 DiagnosticSeverity::ERROR
5368 | DiagnosticSeverity::WARNING
5369 | DiagnosticSeverity::INFORMATION,
5370 ) => true,
5371 (_, _) => false,
5372 }
5373 })
5374 // We want to sort by severity, in order to paint the most severe diagnostics last.
5375 .sorted_by_key(|diagnostic| {
5376 std::cmp::Reverse(diagnostic.diagnostic.severity)
5377 });
5378
5379 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5380 let start_display = diagnostic
5381 .range
5382 .start
5383 .to_display_point(&snapshot.display_snapshot);
5384 let end_display = diagnostic
5385 .range
5386 .end
5387 .to_display_point(&snapshot.display_snapshot);
5388 let color = match diagnostic.diagnostic.severity {
5389 DiagnosticSeverity::ERROR => theme.status().error,
5390 DiagnosticSeverity::WARNING => theme.status().warning,
5391 DiagnosticSeverity::INFORMATION => theme.status().info,
5392 _ => theme.status().hint,
5393 };
5394 ColoredRange {
5395 start: start_display.row(),
5396 end: end_display.row(),
5397 color,
5398 }
5399 });
5400 marker_quads.extend(
5401 scrollbar_layout
5402 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5403 );
5404 }
5405
5406 Arc::from(marker_quads)
5407 })
5408 .await;
5409
5410 editor.update(&mut cx, |editor, cx| {
5411 editor.scrollbar_marker_state.markers = scrollbar_markers;
5412 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5413 editor.scrollbar_marker_state.pending_refresh = None;
5414 cx.notify();
5415 })?;
5416
5417 Ok(())
5418 }));
5419 });
5420 }
5421
5422 #[allow(clippy::too_many_arguments)]
5423 fn paint_highlighted_range(
5424 &self,
5425 range: Range<DisplayPoint>,
5426 color: Hsla,
5427 corner_radius: Pixels,
5428 line_end_overshoot: Pixels,
5429 layout: &EditorLayout,
5430 window: &mut Window,
5431 ) {
5432 let start_row = layout.visible_display_row_range.start;
5433 let end_row = layout.visible_display_row_range.end;
5434 if range.start != range.end {
5435 let row_range = if range.end.column() == 0 {
5436 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5437 } else {
5438 cmp::max(range.start.row(), start_row)
5439 ..cmp::min(range.end.row().next_row(), end_row)
5440 };
5441
5442 let highlighted_range = HighlightedRange {
5443 color,
5444 line_height: layout.position_map.line_height,
5445 corner_radius,
5446 start_y: layout.content_origin.y
5447 + row_range.start.as_f32() * layout.position_map.line_height
5448 - layout.position_map.scroll_pixel_position.y,
5449 lines: row_range
5450 .iter_rows()
5451 .map(|row| {
5452 let line_layout =
5453 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5454 HighlightedRangeLine {
5455 start_x: if row == range.start.row() {
5456 layout.content_origin.x
5457 + line_layout.x_for_index(range.start.column() as usize)
5458 - layout.position_map.scroll_pixel_position.x
5459 } else {
5460 layout.content_origin.x
5461 - layout.position_map.scroll_pixel_position.x
5462 },
5463 end_x: if row == range.end.row() {
5464 layout.content_origin.x
5465 + line_layout.x_for_index(range.end.column() as usize)
5466 - layout.position_map.scroll_pixel_position.x
5467 } else {
5468 layout.content_origin.x + line_layout.width + line_end_overshoot
5469 - layout.position_map.scroll_pixel_position.x
5470 },
5471 }
5472 })
5473 .collect(),
5474 };
5475
5476 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5477 }
5478 }
5479
5480 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5481 if let Some(mut inline_blame) = layout.inline_blame.take() {
5482 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5483 inline_blame.paint(window, cx);
5484 })
5485 }
5486 }
5487
5488 fn paint_diff_hunk_controls(
5489 &mut self,
5490 layout: &mut EditorLayout,
5491 window: &mut Window,
5492 cx: &mut App,
5493 ) {
5494 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5495 diff_hunk_control.paint(window, cx);
5496 }
5497 }
5498
5499 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5500 for mut block in layout.blocks.drain(..) {
5501 block.element.paint(window, cx);
5502 }
5503 }
5504
5505 fn paint_inline_completion_popover(
5506 &mut self,
5507 layout: &mut EditorLayout,
5508 window: &mut Window,
5509 cx: &mut App,
5510 ) {
5511 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5512 inline_completion_popover.paint(window, cx);
5513 }
5514 }
5515
5516 fn paint_mouse_context_menu(
5517 &mut self,
5518 layout: &mut EditorLayout,
5519 window: &mut Window,
5520 cx: &mut App,
5521 ) {
5522 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5523 mouse_context_menu.paint(window, cx);
5524 }
5525 }
5526
5527 fn paint_scroll_wheel_listener(
5528 &mut self,
5529 layout: &EditorLayout,
5530 window: &mut Window,
5531 cx: &mut App,
5532 ) {
5533 window.on_mouse_event({
5534 let position_map = layout.position_map.clone();
5535 let editor = self.editor.clone();
5536 let hitbox = layout.hitbox.clone();
5537 let mut delta = ScrollDelta::default();
5538
5539 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5540 // accidentally turn off their scrolling.
5541 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5542
5543 move |event: &ScrollWheelEvent, phase, window, cx| {
5544 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5545 delta = delta.coalesce(event.delta);
5546 editor.update(cx, |editor, cx| {
5547 let position_map: &PositionMap = &position_map;
5548
5549 let line_height = position_map.line_height;
5550 let max_glyph_width = position_map.em_width;
5551 let (delta, axis) = match delta {
5552 gpui::ScrollDelta::Pixels(mut pixels) => {
5553 //Trackpad
5554 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5555 (pixels, axis)
5556 }
5557
5558 gpui::ScrollDelta::Lines(lines) => {
5559 //Not trackpad
5560 let pixels =
5561 point(lines.x * max_glyph_width, lines.y * line_height);
5562 (pixels, None)
5563 }
5564 };
5565
5566 let current_scroll_position = position_map.snapshot.scroll_position();
5567 let x = (current_scroll_position.x * max_glyph_width
5568 - (delta.x * scroll_sensitivity))
5569 / max_glyph_width;
5570 let y = (current_scroll_position.y * line_height
5571 - (delta.y * scroll_sensitivity))
5572 / line_height;
5573 let mut scroll_position =
5574 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5575 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5576 if forbid_vertical_scroll {
5577 scroll_position.y = current_scroll_position.y;
5578 }
5579
5580 if scroll_position != current_scroll_position {
5581 editor.scroll(scroll_position, axis, window, cx);
5582 cx.stop_propagation();
5583 } else if y < 0. {
5584 // Due to clamping, we may fail to detect cases of overscroll to the top;
5585 // We want the scroll manager to get an update in such cases and detect the change of direction
5586 // on the next frame.
5587 cx.notify();
5588 }
5589 });
5590 }
5591 }
5592 });
5593 }
5594
5595 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5596 self.paint_scroll_wheel_listener(layout, window, cx);
5597
5598 window.on_mouse_event({
5599 let position_map = layout.position_map.clone();
5600 let editor = self.editor.clone();
5601 let multi_buffer_range =
5602 layout
5603 .display_hunks
5604 .iter()
5605 .find_map(|(hunk, hunk_hitbox)| match hunk {
5606 DisplayDiffHunk::Folded { .. } => None,
5607 DisplayDiffHunk::Unfolded {
5608 multi_buffer_range, ..
5609 } => {
5610 if hunk_hitbox
5611 .as_ref()
5612 .map(|hitbox| hitbox.is_hovered(window))
5613 .unwrap_or(false)
5614 {
5615 Some(multi_buffer_range.clone())
5616 } else {
5617 None
5618 }
5619 }
5620 });
5621 let line_numbers = layout.line_numbers.clone();
5622
5623 move |event: &MouseDownEvent, phase, window, cx| {
5624 if phase == DispatchPhase::Bubble {
5625 match event.button {
5626 MouseButton::Left => editor.update(cx, |editor, cx| {
5627 let pending_mouse_down = editor
5628 .pending_mouse_down
5629 .get_or_insert_with(Default::default)
5630 .clone();
5631
5632 *pending_mouse_down.borrow_mut() = Some(event.clone());
5633
5634 Self::mouse_left_down(
5635 editor,
5636 event,
5637 multi_buffer_range.clone(),
5638 &position_map,
5639 line_numbers.as_ref(),
5640 window,
5641 cx,
5642 );
5643 }),
5644 MouseButton::Right => editor.update(cx, |editor, cx| {
5645 Self::mouse_right_down(editor, event, &position_map, window, cx);
5646 }),
5647 MouseButton::Middle => editor.update(cx, |editor, cx| {
5648 Self::mouse_middle_down(editor, event, &position_map, window, cx);
5649 }),
5650 _ => {}
5651 };
5652 }
5653 }
5654 });
5655
5656 window.on_mouse_event({
5657 let editor = self.editor.clone();
5658 let position_map = layout.position_map.clone();
5659
5660 move |event: &MouseUpEvent, phase, window, cx| {
5661 if phase == DispatchPhase::Bubble {
5662 editor.update(cx, |editor, cx| {
5663 Self::mouse_up(editor, event, &position_map, window, cx)
5664 });
5665 }
5666 }
5667 });
5668
5669 window.on_mouse_event({
5670 let editor = self.editor.clone();
5671 let position_map = layout.position_map.clone();
5672 let mut captured_mouse_down = None;
5673
5674 move |event: &MouseUpEvent, phase, window, cx| match phase {
5675 // Clear the pending mouse down during the capture phase,
5676 // so that it happens even if another event handler stops
5677 // propagation.
5678 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5679 let pending_mouse_down = editor
5680 .pending_mouse_down
5681 .get_or_insert_with(Default::default)
5682 .clone();
5683
5684 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5685 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5686 captured_mouse_down = pending_mouse_down.take();
5687 window.refresh();
5688 }
5689 }),
5690 // Fire click handlers during the bubble phase.
5691 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5692 if let Some(mouse_down) = captured_mouse_down.take() {
5693 let event = ClickEvent {
5694 down: mouse_down,
5695 up: event.clone(),
5696 };
5697 Self::click(editor, &event, &position_map, window, cx);
5698 }
5699 }),
5700 }
5701 });
5702
5703 window.on_mouse_event({
5704 let position_map = layout.position_map.clone();
5705 let editor = self.editor.clone();
5706
5707 move |event: &MouseMoveEvent, phase, window, cx| {
5708 if phase == DispatchPhase::Bubble {
5709 editor.update(cx, |editor, cx| {
5710 if editor.hover_state.focused(window, cx) {
5711 return;
5712 }
5713 if event.pressed_button == Some(MouseButton::Left)
5714 || event.pressed_button == Some(MouseButton::Middle)
5715 {
5716 Self::mouse_dragged(editor, event, &position_map, window, cx)
5717 }
5718
5719 Self::mouse_moved(editor, event, &position_map, window, cx)
5720 });
5721 }
5722 }
5723 });
5724 }
5725
5726 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5727 bounds.top_right().x - self.style.scrollbar_width
5728 }
5729
5730 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5731 let style = &self.style;
5732 let font_size = style.text.font_size.to_pixels(window.rem_size());
5733 let layout = window
5734 .text_system()
5735 .shape_line(
5736 SharedString::from(" ".repeat(column)),
5737 font_size,
5738 &[TextRun {
5739 len: column,
5740 font: style.text.font(),
5741 color: Hsla::default(),
5742 background_color: None,
5743 underline: None,
5744 strikethrough: None,
5745 }],
5746 )
5747 .unwrap();
5748
5749 layout.width
5750 }
5751
5752 fn max_line_number_width(
5753 &self,
5754 snapshot: &EditorSnapshot,
5755 window: &mut Window,
5756 cx: &mut App,
5757 ) -> Pixels {
5758 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5759 self.column_pixels(digit_count, window, cx)
5760 }
5761
5762 fn shape_line_number(
5763 &self,
5764 text: SharedString,
5765 color: Hsla,
5766 window: &mut Window,
5767 ) -> anyhow::Result<ShapedLine> {
5768 let run = TextRun {
5769 len: text.len(),
5770 font: self.style.text.font(),
5771 color,
5772 background_color: None,
5773 underline: None,
5774 strikethrough: None,
5775 };
5776 window.text_system().shape_line(
5777 text,
5778 self.style.text.font_size.to_pixels(window.rem_size()),
5779 &[run],
5780 )
5781 }
5782}
5783
5784fn header_jump_data(
5785 snapshot: &EditorSnapshot,
5786 block_row_start: DisplayRow,
5787 height: u32,
5788 for_excerpt: &ExcerptInfo,
5789) -> JumpData {
5790 let range = &for_excerpt.range;
5791 let buffer = &for_excerpt.buffer;
5792 let jump_anchor = range
5793 .primary
5794 .as_ref()
5795 .map_or(range.context.start, |primary| primary.start);
5796
5797 let excerpt_start = range.context.start;
5798 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5799 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5800 0
5801 } else {
5802 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5803 jump_position.row.saturating_sub(excerpt_start_point.row)
5804 };
5805
5806 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5807 .saturating_sub(
5808 snapshot
5809 .scroll_anchor
5810 .scroll_position(&snapshot.display_snapshot)
5811 .y as u32,
5812 );
5813
5814 JumpData::MultiBufferPoint {
5815 excerpt_id: for_excerpt.id,
5816 anchor: jump_anchor,
5817 position: jump_position,
5818 line_offset_from_top,
5819 }
5820}
5821
5822pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5823
5824impl AcceptEditPredictionBinding {
5825 pub fn keystroke(&self) -> Option<&Keystroke> {
5826 if let Some(binding) = self.0.as_ref() {
5827 match &binding.keystrokes() {
5828 [keystroke] => Some(keystroke),
5829 _ => None,
5830 }
5831 } else {
5832 None
5833 }
5834 }
5835}
5836
5837struct AcceptEditPredictionsBindingValidator;
5838
5839inventory::submit! { KeyBindingValidatorRegistration(|| Box::new(AcceptEditPredictionsBindingValidator)) }
5840
5841impl KeyBindingValidator for AcceptEditPredictionsBindingValidator {
5842 fn action_type_id(&self) -> TypeId {
5843 TypeId::of::<AcceptEditPrediction>()
5844 }
5845
5846 fn validate(&self, binding: &gpui::KeyBinding) -> Result<(), MarkdownString> {
5847 use KeyBindingContextPredicate::*;
5848
5849 if binding.keystrokes().len() == 1 && binding.keystrokes()[0].modifiers.modified() {
5850 return Ok(());
5851 }
5852 let required_predicate =
5853 Not(Identifier(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT.into()).into());
5854 match binding.predicate() {
5855 Some(predicate) if required_predicate.is_superset(&predicate) => {
5856 return Ok(());
5857 }
5858 _ => {}
5859 }
5860 Err(MarkdownString(format!(
5861 "{} can only be bound to a single keystroke with modifiers, so \
5862 that holding down these modifiers can be used to preview \
5863 completions inline when the completions menu is open.\n\n\
5864 This restriction does not apply when the context requires {}, \
5865 since these bindings will not be used when the completions menu \
5866 is open.",
5867 MarkdownString::inline_code(AcceptEditPrediction.name()),
5868 MarkdownString::inline_code(&format!(
5869 "!{}",
5870 EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT
5871 )),
5872 )))
5873 }
5874}
5875
5876#[allow(clippy::too_many_arguments)]
5877fn prepaint_gutter_button(
5878 button: IconButton,
5879 row: DisplayRow,
5880 line_height: Pixels,
5881 gutter_dimensions: &GutterDimensions,
5882 scroll_pixel_position: gpui::Point<Pixels>,
5883 gutter_hitbox: &Hitbox,
5884 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5885 window: &mut Window,
5886 cx: &mut App,
5887) -> AnyElement {
5888 let mut button = button.into_any_element();
5889 let available_space = size(
5890 AvailableSpace::MinContent,
5891 AvailableSpace::Definite(line_height),
5892 );
5893 let indicator_size = button.layout_as_root(available_space, window, cx);
5894
5895 let blame_width = gutter_dimensions.git_blame_entries_width;
5896 let gutter_width = rows_with_hunk_bounds
5897 .get(&row)
5898 .map(|bounds| bounds.size.width);
5899 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5900
5901 let mut x = left_offset;
5902 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5903 - indicator_size.width
5904 - left_offset;
5905 x += available_width / 2.;
5906
5907 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5908 y += (line_height - indicator_size.height) / 2.;
5909
5910 button.prepaint_as_root(
5911 gutter_hitbox.origin + point(x, y),
5912 available_space,
5913 window,
5914 cx,
5915 );
5916 button
5917}
5918
5919fn render_inline_blame_entry(
5920 blame: &gpui::Entity<GitBlame>,
5921 blame_entry: BlameEntry,
5922 style: &EditorStyle,
5923 workspace: Option<WeakEntity<Workspace>>,
5924 cx: &mut App,
5925) -> AnyElement {
5926 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5927
5928 let author = blame_entry.author.as_deref().unwrap_or_default();
5929 let summary_enabled = ProjectSettings::get_global(cx)
5930 .git
5931 .show_inline_commit_summary();
5932
5933 let text = match blame_entry.summary.as_ref() {
5934 Some(summary) if summary_enabled => {
5935 format!("{}, {} - {}", author, relative_timestamp, summary)
5936 }
5937 _ => format!("{}, {}", author, relative_timestamp),
5938 };
5939
5940 let details = blame.read(cx).details_for_entry(&blame_entry);
5941
5942 let tooltip =
5943 cx.new(|_| CommitTooltip::blame_entry(blame_entry, details, style.clone(), workspace));
5944
5945 h_flex()
5946 .id("inline-blame")
5947 .w_full()
5948 .font_family(style.text.font().family)
5949 .text_color(cx.theme().status().hint)
5950 .line_height(style.text.line_height)
5951 .child(Icon::new(IconName::FileGit).color(Color::Hint))
5952 .child(text)
5953 .gap_2()
5954 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5955 .into_any()
5956}
5957
5958fn render_blame_entry(
5959 ix: usize,
5960 blame: &gpui::Entity<GitBlame>,
5961 blame_entry: BlameEntry,
5962 style: &EditorStyle,
5963 last_used_color: &mut Option<(PlayerColor, Oid)>,
5964 editor: Entity<Editor>,
5965 cx: &mut App,
5966) -> AnyElement {
5967 let mut sha_color = cx
5968 .theme()
5969 .players()
5970 .color_for_participant(blame_entry.sha.into());
5971 // If the last color we used is the same as the one we get for this line, but
5972 // the commit SHAs are different, then we try again to get a different color.
5973 match *last_used_color {
5974 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5975 let index: u32 = blame_entry.sha.into();
5976 sha_color = cx.theme().players().color_for_participant(index + 1);
5977 }
5978 _ => {}
5979 };
5980 last_used_color.replace((sha_color, blame_entry.sha));
5981
5982 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5983
5984 let short_commit_id = blame_entry.sha.display_short();
5985
5986 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5987 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5988
5989 let details = blame.read(cx).details_for_entry(&blame_entry);
5990
5991 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
5992
5993 let tooltip = cx.new(|_| {
5994 CommitTooltip::blame_entry(
5995 blame_entry.clone(),
5996 details.clone(),
5997 style.clone(),
5998 workspace,
5999 )
6000 });
6001
6002 h_flex()
6003 .w_full()
6004 .justify_between()
6005 .font_family(style.text.font().family)
6006 .line_height(style.text.line_height)
6007 .id(("blame", ix))
6008 .text_color(cx.theme().status().hint)
6009 .pr_2()
6010 .gap_2()
6011 .child(
6012 h_flex()
6013 .items_center()
6014 .gap_2()
6015 .child(div().text_color(sha_color.cursor).child(short_commit_id))
6016 .child(name),
6017 )
6018 .child(relative_timestamp)
6019 .on_mouse_down(MouseButton::Right, {
6020 let blame_entry = blame_entry.clone();
6021 let details = details.clone();
6022 move |event, window, cx| {
6023 deploy_blame_entry_context_menu(
6024 &blame_entry,
6025 details.as_ref(),
6026 editor.clone(),
6027 event.position,
6028 window,
6029 cx,
6030 );
6031 }
6032 })
6033 .hover(|style| style.bg(cx.theme().colors().element_hover))
6034 .when_some(
6035 details.and_then(|details| details.permalink),
6036 |this, url| {
6037 let url = url.clone();
6038 this.cursor_pointer().on_click(move |_, _, cx| {
6039 cx.stop_propagation();
6040 cx.open_url(url.as_str())
6041 })
6042 },
6043 )
6044 .hoverable_tooltip(move |_, _| tooltip.clone().into())
6045 .into_any()
6046}
6047
6048fn deploy_blame_entry_context_menu(
6049 blame_entry: &BlameEntry,
6050 details: Option<&ParsedCommitMessage>,
6051 editor: Entity<Editor>,
6052 position: gpui::Point<Pixels>,
6053 window: &mut Window,
6054 cx: &mut App,
6055) {
6056 let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
6057 let sha = format!("{}", blame_entry.sha);
6058 menu.on_blur_subscription(Subscription::new(|| {}))
6059 .entry("Copy commit SHA", None, move |_, cx| {
6060 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
6061 })
6062 .when_some(
6063 details.and_then(|details| details.permalink.clone()),
6064 |this, url| {
6065 this.entry("Open permalink", None, move |_, cx| {
6066 cx.open_url(url.as_str())
6067 })
6068 },
6069 )
6070 });
6071
6072 editor.update(cx, move |editor, cx| {
6073 editor.mouse_context_menu = Some(MouseContextMenu::new(
6074 MenuPosition::PinnedToScreen(position),
6075 context_menu,
6076 window,
6077 cx,
6078 ));
6079 cx.notify();
6080 });
6081}
6082
6083#[derive(Debug)]
6084pub(crate) struct LineWithInvisibles {
6085 fragments: SmallVec<[LineFragment; 1]>,
6086 invisibles: Vec<Invisible>,
6087 len: usize,
6088 width: Pixels,
6089 font_size: Pixels,
6090}
6091
6092#[allow(clippy::large_enum_variant)]
6093enum LineFragment {
6094 Text(ShapedLine),
6095 Element {
6096 element: Option<AnyElement>,
6097 size: Size<Pixels>,
6098 len: usize,
6099 },
6100}
6101
6102impl fmt::Debug for LineFragment {
6103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6104 match self {
6105 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6106 LineFragment::Element { size, len, .. } => f
6107 .debug_struct("Element")
6108 .field("size", size)
6109 .field("len", len)
6110 .finish(),
6111 }
6112 }
6113}
6114
6115impl LineWithInvisibles {
6116 #[allow(clippy::too_many_arguments)]
6117 fn from_chunks<'a>(
6118 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6119 editor_style: &EditorStyle,
6120 max_line_len: usize,
6121 max_line_count: usize,
6122 editor_mode: EditorMode,
6123 text_width: Pixels,
6124 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6125 window: &mut Window,
6126 cx: &mut App,
6127 ) -> Vec<Self> {
6128 let text_style = &editor_style.text;
6129 let mut layouts = Vec::with_capacity(max_line_count);
6130 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6131 let mut line = String::new();
6132 let mut invisibles = Vec::new();
6133 let mut width = Pixels::ZERO;
6134 let mut len = 0;
6135 let mut styles = Vec::new();
6136 let mut non_whitespace_added = false;
6137 let mut row = 0;
6138 let mut line_exceeded_max_len = false;
6139 let font_size = text_style.font_size.to_pixels(window.rem_size());
6140
6141 let ellipsis = SharedString::from("⋯");
6142
6143 for highlighted_chunk in chunks.chain([HighlightedChunk {
6144 text: "\n",
6145 style: None,
6146 is_tab: false,
6147 replacement: None,
6148 }]) {
6149 if let Some(replacement) = highlighted_chunk.replacement {
6150 if !line.is_empty() {
6151 let shaped_line = window
6152 .text_system()
6153 .shape_line(line.clone().into(), font_size, &styles)
6154 .unwrap();
6155 width += shaped_line.width;
6156 len += shaped_line.len;
6157 fragments.push(LineFragment::Text(shaped_line));
6158 line.clear();
6159 styles.clear();
6160 }
6161
6162 match replacement {
6163 ChunkReplacement::Renderer(renderer) => {
6164 let available_width = if renderer.constrain_width {
6165 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6166 ellipsis.clone()
6167 } else {
6168 SharedString::from(Arc::from(highlighted_chunk.text))
6169 };
6170 let shaped_line = window
6171 .text_system()
6172 .shape_line(
6173 chunk,
6174 font_size,
6175 &[text_style.to_run(highlighted_chunk.text.len())],
6176 )
6177 .unwrap();
6178 AvailableSpace::Definite(shaped_line.width)
6179 } else {
6180 AvailableSpace::MinContent
6181 };
6182
6183 let mut element = (renderer.render)(&mut ChunkRendererContext {
6184 context: cx,
6185 window,
6186 max_width: text_width,
6187 });
6188 let line_height = text_style.line_height_in_pixels(window.rem_size());
6189 let size = element.layout_as_root(
6190 size(available_width, AvailableSpace::Definite(line_height)),
6191 window,
6192 cx,
6193 );
6194
6195 width += size.width;
6196 len += highlighted_chunk.text.len();
6197 fragments.push(LineFragment::Element {
6198 element: Some(element),
6199 size,
6200 len: highlighted_chunk.text.len(),
6201 });
6202 }
6203 ChunkReplacement::Str(x) => {
6204 let text_style = if let Some(style) = highlighted_chunk.style {
6205 Cow::Owned(text_style.clone().highlight(style))
6206 } else {
6207 Cow::Borrowed(text_style)
6208 };
6209
6210 let run = TextRun {
6211 len: x.len(),
6212 font: text_style.font(),
6213 color: text_style.color,
6214 background_color: text_style.background_color,
6215 underline: text_style.underline,
6216 strikethrough: text_style.strikethrough,
6217 };
6218 let line_layout = window
6219 .text_system()
6220 .shape_line(x, font_size, &[run])
6221 .unwrap()
6222 .with_len(highlighted_chunk.text.len());
6223
6224 width += line_layout.width;
6225 len += highlighted_chunk.text.len();
6226 fragments.push(LineFragment::Text(line_layout))
6227 }
6228 }
6229 } else {
6230 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6231 if ix > 0 {
6232 let shaped_line = window
6233 .text_system()
6234 .shape_line(line.clone().into(), font_size, &styles)
6235 .unwrap();
6236 width += shaped_line.width;
6237 len += shaped_line.len;
6238 fragments.push(LineFragment::Text(shaped_line));
6239 layouts.push(Self {
6240 width: mem::take(&mut width),
6241 len: mem::take(&mut len),
6242 fragments: mem::take(&mut fragments),
6243 invisibles: std::mem::take(&mut invisibles),
6244 font_size,
6245 });
6246
6247 line.clear();
6248 styles.clear();
6249 row += 1;
6250 line_exceeded_max_len = false;
6251 non_whitespace_added = false;
6252 if row == max_line_count {
6253 return layouts;
6254 }
6255 }
6256
6257 if !line_chunk.is_empty() && !line_exceeded_max_len {
6258 let text_style = if let Some(style) = highlighted_chunk.style {
6259 Cow::Owned(text_style.clone().highlight(style))
6260 } else {
6261 Cow::Borrowed(text_style)
6262 };
6263
6264 if line.len() + line_chunk.len() > max_line_len {
6265 let mut chunk_len = max_line_len - line.len();
6266 while !line_chunk.is_char_boundary(chunk_len) {
6267 chunk_len -= 1;
6268 }
6269 line_chunk = &line_chunk[..chunk_len];
6270 line_exceeded_max_len = true;
6271 }
6272
6273 styles.push(TextRun {
6274 len: line_chunk.len(),
6275 font: text_style.font(),
6276 color: text_style.color,
6277 background_color: text_style.background_color,
6278 underline: text_style.underline,
6279 strikethrough: text_style.strikethrough,
6280 });
6281
6282 if editor_mode == EditorMode::Full {
6283 // Line wrap pads its contents with fake whitespaces,
6284 // avoid printing them
6285 let is_soft_wrapped = is_row_soft_wrapped(row);
6286 if highlighted_chunk.is_tab {
6287 if non_whitespace_added || !is_soft_wrapped {
6288 invisibles.push(Invisible::Tab {
6289 line_start_offset: line.len(),
6290 line_end_offset: line.len() + line_chunk.len(),
6291 });
6292 }
6293 } else {
6294 invisibles.extend(line_chunk.char_indices().filter_map(
6295 |(index, c)| {
6296 let is_whitespace = c.is_whitespace();
6297 non_whitespace_added |= !is_whitespace;
6298 if is_whitespace
6299 && (non_whitespace_added || !is_soft_wrapped)
6300 {
6301 Some(Invisible::Whitespace {
6302 line_offset: line.len() + index,
6303 })
6304 } else {
6305 None
6306 }
6307 },
6308 ))
6309 }
6310 }
6311
6312 line.push_str(line_chunk);
6313 }
6314 }
6315 }
6316 }
6317
6318 layouts
6319 }
6320
6321 #[allow(clippy::too_many_arguments)]
6322 fn prepaint(
6323 &mut self,
6324 line_height: Pixels,
6325 scroll_pixel_position: gpui::Point<Pixels>,
6326 row: DisplayRow,
6327 content_origin: gpui::Point<Pixels>,
6328 line_elements: &mut SmallVec<[AnyElement; 1]>,
6329 window: &mut Window,
6330 cx: &mut App,
6331 ) {
6332 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6333 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6334 for fragment in &mut self.fragments {
6335 match fragment {
6336 LineFragment::Text(line) => {
6337 fragment_origin.x += line.width;
6338 }
6339 LineFragment::Element { element, size, .. } => {
6340 let mut element = element
6341 .take()
6342 .expect("you can't prepaint LineWithInvisibles twice");
6343
6344 // Center the element vertically within the line.
6345 let mut element_origin = fragment_origin;
6346 element_origin.y += (line_height - size.height) / 2.;
6347 element.prepaint_at(element_origin, window, cx);
6348 line_elements.push(element);
6349
6350 fragment_origin.x += size.width;
6351 }
6352 }
6353 }
6354 }
6355
6356 #[allow(clippy::too_many_arguments)]
6357 fn draw(
6358 &self,
6359 layout: &EditorLayout,
6360 row: DisplayRow,
6361 content_origin: gpui::Point<Pixels>,
6362 whitespace_setting: ShowWhitespaceSetting,
6363 selection_ranges: &[Range<DisplayPoint>],
6364 window: &mut Window,
6365 cx: &mut App,
6366 ) {
6367 let line_height = layout.position_map.line_height;
6368 let line_y = line_height
6369 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6370
6371 let mut fragment_origin =
6372 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6373
6374 for fragment in &self.fragments {
6375 match fragment {
6376 LineFragment::Text(line) => {
6377 line.paint(fragment_origin, line_height, window, cx)
6378 .log_err();
6379 fragment_origin.x += line.width;
6380 }
6381 LineFragment::Element { size, .. } => {
6382 fragment_origin.x += size.width;
6383 }
6384 }
6385 }
6386
6387 self.draw_invisibles(
6388 selection_ranges,
6389 layout,
6390 content_origin,
6391 line_y,
6392 row,
6393 line_height,
6394 whitespace_setting,
6395 window,
6396 cx,
6397 );
6398 }
6399
6400 #[allow(clippy::too_many_arguments)]
6401 fn draw_invisibles(
6402 &self,
6403 selection_ranges: &[Range<DisplayPoint>],
6404 layout: &EditorLayout,
6405 content_origin: gpui::Point<Pixels>,
6406 line_y: Pixels,
6407 row: DisplayRow,
6408 line_height: Pixels,
6409 whitespace_setting: ShowWhitespaceSetting,
6410 window: &mut Window,
6411 cx: &mut App,
6412 ) {
6413 let extract_whitespace_info = |invisible: &Invisible| {
6414 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6415 Invisible::Tab {
6416 line_start_offset,
6417 line_end_offset,
6418 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6419 Invisible::Whitespace { line_offset } => {
6420 (*line_offset, line_offset + 1, &layout.space_invisible)
6421 }
6422 };
6423
6424 let x_offset = self.x_for_index(token_offset);
6425 let invisible_offset =
6426 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6427 let origin = content_origin
6428 + gpui::point(
6429 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6430 line_y,
6431 );
6432
6433 (
6434 [token_offset, token_end_offset],
6435 Box::new(move |window: &mut Window, cx: &mut App| {
6436 invisible_symbol
6437 .paint(origin, line_height, window, cx)
6438 .log_err();
6439 }),
6440 )
6441 };
6442
6443 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6444 match whitespace_setting {
6445 ShowWhitespaceSetting::None => (),
6446 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6447 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6448 let invisible_point = DisplayPoint::new(row, start as u32);
6449 if !selection_ranges
6450 .iter()
6451 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6452 {
6453 return;
6454 }
6455
6456 paint(window, cx);
6457 }),
6458
6459 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6460 // - It is a tab
6461 // - It is adjacent to an edge (start or end)
6462 // - It is adjacent to a whitespace (left or right)
6463 ShowWhitespaceSetting::Boundary => {
6464 // 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
6465 // the above cases.
6466 // Note: We zip in the original `invisibles` to check for tab equality
6467 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6468 for (([start, end], paint), invisible) in
6469 invisible_iter.zip_eq(self.invisibles.iter())
6470 {
6471 let should_render = match (&last_seen, invisible) {
6472 (_, Invisible::Tab { .. }) => true,
6473 (Some((_, last_end, _)), _) => *last_end == start,
6474 _ => false,
6475 };
6476
6477 if should_render || start == 0 || end == self.len {
6478 paint(window, cx);
6479
6480 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6481 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6482 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6483 // Note that we need to make sure that the last one is actually adjacent
6484 if !should_render_last && last_end == start {
6485 paint_last(window, cx);
6486 }
6487 }
6488 }
6489
6490 // Manually render anything within a selection
6491 let invisible_point = DisplayPoint::new(row, start as u32);
6492 if selection_ranges.iter().any(|region| {
6493 region.start <= invisible_point && invisible_point < region.end
6494 }) {
6495 paint(window, cx);
6496 }
6497
6498 last_seen = Some((should_render, end, paint));
6499 }
6500 }
6501 }
6502 }
6503
6504 pub fn x_for_index(&self, index: usize) -> Pixels {
6505 let mut fragment_start_x = Pixels::ZERO;
6506 let mut fragment_start_index = 0;
6507
6508 for fragment in &self.fragments {
6509 match fragment {
6510 LineFragment::Text(shaped_line) => {
6511 let fragment_end_index = fragment_start_index + shaped_line.len;
6512 if index < fragment_end_index {
6513 return fragment_start_x
6514 + shaped_line.x_for_index(index - fragment_start_index);
6515 }
6516 fragment_start_x += shaped_line.width;
6517 fragment_start_index = fragment_end_index;
6518 }
6519 LineFragment::Element { len, size, .. } => {
6520 let fragment_end_index = fragment_start_index + len;
6521 if index < fragment_end_index {
6522 return fragment_start_x;
6523 }
6524 fragment_start_x += size.width;
6525 fragment_start_index = fragment_end_index;
6526 }
6527 }
6528 }
6529
6530 fragment_start_x
6531 }
6532
6533 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6534 let mut fragment_start_x = Pixels::ZERO;
6535 let mut fragment_start_index = 0;
6536
6537 for fragment in &self.fragments {
6538 match fragment {
6539 LineFragment::Text(shaped_line) => {
6540 let fragment_end_x = fragment_start_x + shaped_line.width;
6541 if x < fragment_end_x {
6542 return Some(
6543 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6544 );
6545 }
6546 fragment_start_x = fragment_end_x;
6547 fragment_start_index += shaped_line.len;
6548 }
6549 LineFragment::Element { len, size, .. } => {
6550 let fragment_end_x = fragment_start_x + size.width;
6551 if x < fragment_end_x {
6552 return Some(fragment_start_index);
6553 }
6554 fragment_start_index += len;
6555 fragment_start_x = fragment_end_x;
6556 }
6557 }
6558 }
6559
6560 None
6561 }
6562
6563 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6564 let mut fragment_start_index = 0;
6565
6566 for fragment in &self.fragments {
6567 match fragment {
6568 LineFragment::Text(shaped_line) => {
6569 let fragment_end_index = fragment_start_index + shaped_line.len;
6570 if index < fragment_end_index {
6571 return shaped_line.font_id_for_index(index - fragment_start_index);
6572 }
6573 fragment_start_index = fragment_end_index;
6574 }
6575 LineFragment::Element { len, .. } => {
6576 let fragment_end_index = fragment_start_index + len;
6577 if index < fragment_end_index {
6578 return None;
6579 }
6580 fragment_start_index = fragment_end_index;
6581 }
6582 }
6583 }
6584
6585 None
6586 }
6587}
6588
6589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6590enum Invisible {
6591 /// A tab character
6592 ///
6593 /// A tab character is internally represented by spaces (configured by the user's tab width)
6594 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6595 /// adjacency checks.
6596 Tab {
6597 line_start_offset: usize,
6598 line_end_offset: usize,
6599 },
6600 Whitespace {
6601 line_offset: usize,
6602 },
6603}
6604
6605impl EditorElement {
6606 /// Returns the rem size to use when rendering the [`EditorElement`].
6607 ///
6608 /// This allows UI elements to scale based on the `buffer_font_size`.
6609 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6610 match self.editor.read(cx).mode {
6611 EditorMode::Full => {
6612 let buffer_font_size = self.style.text.font_size;
6613 match buffer_font_size {
6614 AbsoluteLength::Pixels(pixels) => {
6615 let rem_size_scale = {
6616 // Our default UI font size is 14px on a 16px base scale.
6617 // This means the default UI font size is 0.875rems.
6618 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6619
6620 // We then determine the delta between a single rem and the default font
6621 // size scale.
6622 let default_font_size_delta = 1. - default_font_size_scale;
6623
6624 // Finally, we add this delta to 1rem to get the scale factor that
6625 // should be used to scale up the UI.
6626 1. + default_font_size_delta
6627 };
6628
6629 Some(pixels * rem_size_scale)
6630 }
6631 AbsoluteLength::Rems(rems) => {
6632 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6633 }
6634 }
6635 }
6636 // We currently use single-line and auto-height editors in UI contexts,
6637 // so we don't want to scale everything with the buffer font size, as it
6638 // ends up looking off.
6639 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6640 }
6641 }
6642}
6643
6644impl Element for EditorElement {
6645 type RequestLayoutState = ();
6646 type PrepaintState = EditorLayout;
6647
6648 fn id(&self) -> Option<ElementId> {
6649 None
6650 }
6651
6652 fn request_layout(
6653 &mut self,
6654 _: Option<&GlobalElementId>,
6655 window: &mut Window,
6656 cx: &mut App,
6657 ) -> (gpui::LayoutId, ()) {
6658 let rem_size = self.rem_size(cx);
6659 window.with_rem_size(rem_size, |window| {
6660 self.editor.update(cx, |editor, cx| {
6661 editor.set_style(self.style.clone(), window, cx);
6662
6663 let layout_id = match editor.mode {
6664 EditorMode::SingleLine { auto_width } => {
6665 let rem_size = window.rem_size();
6666
6667 let height = self.style.text.line_height_in_pixels(rem_size);
6668 if auto_width {
6669 let editor_handle = cx.entity().clone();
6670 let style = self.style.clone();
6671 window.request_measured_layout(
6672 Style::default(),
6673 move |_, _, window, cx| {
6674 let editor_snapshot = editor_handle
6675 .update(cx, |editor, cx| editor.snapshot(window, cx));
6676 let line = Self::layout_lines(
6677 DisplayRow(0)..DisplayRow(1),
6678 &editor_snapshot,
6679 &style,
6680 px(f32::MAX),
6681 |_| false, // Single lines never soft wrap
6682 window,
6683 cx,
6684 )
6685 .pop()
6686 .unwrap();
6687
6688 let font_id =
6689 window.text_system().resolve_font(&style.text.font());
6690 let font_size =
6691 style.text.font_size.to_pixels(window.rem_size());
6692 let em_width =
6693 window.text_system().em_width(font_id, font_size).unwrap();
6694
6695 size(line.width + em_width, height)
6696 },
6697 )
6698 } else {
6699 let mut style = Style::default();
6700 style.size.height = height.into();
6701 style.size.width = relative(1.).into();
6702 window.request_layout(style, None, cx)
6703 }
6704 }
6705 EditorMode::AutoHeight { max_lines } => {
6706 let editor_handle = cx.entity().clone();
6707 let max_line_number_width =
6708 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6709 window.request_measured_layout(
6710 Style::default(),
6711 move |known_dimensions, available_space, window, cx| {
6712 editor_handle
6713 .update(cx, |editor, cx| {
6714 compute_auto_height_layout(
6715 editor,
6716 max_lines,
6717 max_line_number_width,
6718 known_dimensions,
6719 available_space.width,
6720 window,
6721 cx,
6722 )
6723 })
6724 .unwrap_or_default()
6725 },
6726 )
6727 }
6728 EditorMode::Full => {
6729 let mut style = Style::default();
6730 style.size.width = relative(1.).into();
6731 style.size.height = relative(1.).into();
6732 window.request_layout(style, None, cx)
6733 }
6734 };
6735
6736 (layout_id, ())
6737 })
6738 })
6739 }
6740
6741 fn prepaint(
6742 &mut self,
6743 _: Option<&GlobalElementId>,
6744 bounds: Bounds<Pixels>,
6745 _: &mut Self::RequestLayoutState,
6746 window: &mut Window,
6747 cx: &mut App,
6748 ) -> Self::PrepaintState {
6749 let text_style = TextStyleRefinement {
6750 font_size: Some(self.style.text.font_size),
6751 line_height: Some(self.style.text.line_height),
6752 ..Default::default()
6753 };
6754 let focus_handle = self.editor.focus_handle(cx);
6755 window.set_view_id(self.editor.entity_id());
6756 window.set_focus_handle(&focus_handle, cx);
6757
6758 let rem_size = self.rem_size(cx);
6759 window.with_rem_size(rem_size, |window| {
6760 window.with_text_style(Some(text_style), |window| {
6761 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6762 let mut snapshot = self
6763 .editor
6764 .update(cx, |editor, cx| editor.snapshot(window, cx));
6765 let style = self.style.clone();
6766
6767 let font_id = window.text_system().resolve_font(&style.text.font());
6768 let font_size = style.text.font_size.to_pixels(window.rem_size());
6769 let line_height = style.text.line_height_in_pixels(window.rem_size());
6770 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6771 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6772
6773 let letter_size = size(em_width, line_height);
6774
6775 let gutter_dimensions = snapshot
6776 .gutter_dimensions(
6777 font_id,
6778 font_size,
6779 self.max_line_number_width(&snapshot, window, cx),
6780 cx,
6781 )
6782 .unwrap_or_default();
6783 let text_width = bounds.size.width - gutter_dimensions.width;
6784
6785 let editor_width =
6786 text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6787
6788 snapshot = self.editor.update(cx, |editor, cx| {
6789 editor.last_bounds = Some(bounds);
6790 editor.gutter_dimensions = gutter_dimensions;
6791 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6792
6793 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6794 snapshot
6795 } else {
6796 let wrap_width = match editor.soft_wrap_mode(cx) {
6797 SoftWrap::GitDiff => None,
6798 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6799 SoftWrap::EditorWidth => Some(editor_width),
6800 SoftWrap::Column(column) => Some(column as f32 * em_advance),
6801 SoftWrap::Bounded(column) => {
6802 Some(editor_width.min(column as f32 * em_advance))
6803 }
6804 };
6805
6806 if editor.set_wrap_width(wrap_width, cx) {
6807 editor.snapshot(window, cx)
6808 } else {
6809 snapshot
6810 }
6811 }
6812 });
6813
6814 let wrap_guides = self
6815 .editor
6816 .read(cx)
6817 .wrap_guides(cx)
6818 .iter()
6819 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6820 .collect::<SmallVec<[_; 2]>>();
6821
6822 let hitbox = window.insert_hitbox(bounds, false);
6823 let gutter_hitbox =
6824 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6825 let text_hitbox = window.insert_hitbox(
6826 Bounds {
6827 origin: gutter_hitbox.top_right(),
6828 size: size(text_width, bounds.size.height),
6829 },
6830 false,
6831 );
6832 // Offset the content_bounds from the text_bounds by the gutter margin (which
6833 // is roughly half a character wide) to make hit testing work more like how we want.
6834 let content_origin =
6835 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6836
6837 let scrollbar_bounds =
6838 Bounds::from_corners(content_origin, bounds.bottom_right());
6839
6840 let height_in_lines = scrollbar_bounds.size.height / line_height;
6841
6842 // NOTE: The max row number in the current file, minus one
6843 let max_row = snapshot.max_point().row().as_f32();
6844
6845 // NOTE: The max scroll position for the top of the window
6846 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6847 (max_row - height_in_lines + 1.).max(0.)
6848 } else {
6849 let settings = EditorSettings::get_global(cx);
6850 match settings.scroll_beyond_last_line {
6851 ScrollBeyondLastLine::OnePage => max_row,
6852 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6853 ScrollBeyondLastLine::VerticalScrollMargin => {
6854 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6855 .max(0.)
6856 }
6857 }
6858 };
6859
6860 // TODO: Autoscrolling for both axes
6861 let mut autoscroll_request = None;
6862 let mut autoscroll_containing_element = false;
6863 let mut autoscroll_horizontally = false;
6864 self.editor.update(cx, |editor, cx| {
6865 autoscroll_request = editor.autoscroll_request();
6866 autoscroll_containing_element =
6867 autoscroll_request.is_some() || editor.has_pending_selection();
6868 // TODO: Is this horizontal or vertical?!
6869 autoscroll_horizontally = editor.autoscroll_vertically(
6870 bounds,
6871 line_height,
6872 max_scroll_top,
6873 window,
6874 cx,
6875 );
6876 snapshot = editor.snapshot(window, cx);
6877 });
6878
6879 let mut scroll_position = snapshot.scroll_position();
6880 // The scroll position is a fractional point, the whole number of which represents
6881 // the top of the window in terms of display rows.
6882 let start_row = DisplayRow(scroll_position.y as u32);
6883 let max_row = snapshot.max_point().row();
6884 let end_row = cmp::min(
6885 (scroll_position.y + height_in_lines).ceil() as u32,
6886 max_row.next_row().0,
6887 );
6888 let end_row = DisplayRow(end_row);
6889
6890 let row_infos = snapshot
6891 .row_infos(start_row)
6892 .take((start_row..end_row).len())
6893 .collect::<Vec<RowInfo>>();
6894 let is_row_soft_wrapped = |row: usize| {
6895 row_infos
6896 .get(row)
6897 .map_or(true, |info| info.buffer_row.is_none())
6898 };
6899
6900 let start_anchor = if start_row == Default::default() {
6901 Anchor::min()
6902 } else {
6903 snapshot.buffer_snapshot.anchor_before(
6904 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6905 )
6906 };
6907 let end_anchor = if end_row > max_row {
6908 Anchor::max()
6909 } else {
6910 snapshot.buffer_snapshot.anchor_before(
6911 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6912 )
6913 };
6914
6915 let (mut highlighted_rows, distinguish_unstaged_hunks) =
6916 self.editor.update(cx, |editor, cx| {
6917 (
6918 editor.highlighted_display_rows(window, cx),
6919 editor.distinguish_unstaged_diff_hunks,
6920 )
6921 });
6922
6923 for (ix, row_info) in row_infos.iter().enumerate() {
6924 let background = match row_info.diff_status {
6925 Some(DiffHunkStatus::Added(secondary_status)) => {
6926 let color = style.status.created_background;
6927 match secondary_status {
6928 DiffHunkSecondaryStatus::HasSecondaryHunk
6929 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6930 if distinguish_unstaged_hunks =>
6931 {
6932 pattern_slash(color, line_height.0 / 4.0)
6933 }
6934 _ => color.into(),
6935 }
6936 }
6937 Some(DiffHunkStatus::Removed(secondary_status)) => {
6938 let color = style.status.deleted_background;
6939 match secondary_status {
6940 DiffHunkSecondaryStatus::HasSecondaryHunk
6941 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6942 if distinguish_unstaged_hunks =>
6943 {
6944 pattern_slash(color, line_height.0 / 4.0)
6945 }
6946 _ => color.into(),
6947 }
6948 }
6949 _ => continue,
6950 };
6951
6952 highlighted_rows
6953 .entry(start_row + DisplayRow(ix as u32))
6954 .or_insert(background);
6955 }
6956
6957 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6958 start_anchor..end_anchor,
6959 &snapshot.display_snapshot,
6960 cx.theme().colors(),
6961 );
6962 let highlighted_gutter_ranges =
6963 self.editor.read(cx).gutter_highlights_in_range(
6964 start_anchor..end_anchor,
6965 &snapshot.display_snapshot,
6966 cx,
6967 );
6968
6969 let redacted_ranges = self.editor.read(cx).redacted_ranges(
6970 start_anchor..end_anchor,
6971 &snapshot.display_snapshot,
6972 cx,
6973 );
6974
6975 let (local_selections, selected_buffer_ids): (
6976 Vec<Selection<Point>>,
6977 Vec<BufferId>,
6978 ) = self.editor.update(cx, |editor, cx| {
6979 let all_selections = editor.selections.all::<Point>(cx);
6980 let selected_buffer_ids = if editor.is_singleton(cx) {
6981 Vec::new()
6982 } else {
6983 let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6984
6985 for selection in all_selections {
6986 for buffer_id in snapshot
6987 .buffer_snapshot
6988 .buffer_ids_for_range(selection.range())
6989 {
6990 if selected_buffer_ids.last() != Some(&buffer_id) {
6991 selected_buffer_ids.push(buffer_id);
6992 }
6993 }
6994 }
6995
6996 selected_buffer_ids
6997 };
6998
6999 let mut selections = editor
7000 .selections
7001 .disjoint_in_range(start_anchor..end_anchor, cx);
7002 selections.extend(editor.selections.pending(cx));
7003
7004 (selections, selected_buffer_ids)
7005 });
7006
7007 let (selections, active_rows, newest_selection_head) = self.layout_selections(
7008 start_anchor,
7009 end_anchor,
7010 &local_selections,
7011 &snapshot,
7012 start_row,
7013 end_row,
7014 window,
7015 cx,
7016 );
7017
7018 let line_numbers = self.layout_line_numbers(
7019 Some(&gutter_hitbox),
7020 gutter_dimensions,
7021 line_height,
7022 scroll_position,
7023 start_row..end_row,
7024 &row_infos,
7025 newest_selection_head,
7026 &snapshot,
7027 window,
7028 cx,
7029 );
7030
7031 let mut crease_toggles =
7032 window.with_element_namespace("crease_toggles", |window| {
7033 self.layout_crease_toggles(
7034 start_row..end_row,
7035 &row_infos,
7036 &active_rows,
7037 &snapshot,
7038 window,
7039 cx,
7040 )
7041 });
7042 let crease_trailers =
7043 window.with_element_namespace("crease_trailers", |window| {
7044 self.layout_crease_trailers(
7045 row_infos.iter().copied(),
7046 &snapshot,
7047 window,
7048 cx,
7049 )
7050 });
7051
7052 let display_hunks = self.layout_gutter_diff_hunks(
7053 line_height,
7054 &gutter_hitbox,
7055 start_row..end_row,
7056 &snapshot,
7057 window,
7058 cx,
7059 );
7060
7061 let mut line_layouts = Self::layout_lines(
7062 start_row..end_row,
7063 &snapshot,
7064 &self.style,
7065 editor_width,
7066 is_row_soft_wrapped,
7067 window,
7068 cx,
7069 );
7070
7071 let longest_line_blame_width = self
7072 .editor
7073 .update(cx, |editor, cx| {
7074 if !editor.show_git_blame_inline {
7075 return None;
7076 }
7077 let blame = editor.blame.as_ref()?;
7078 let blame_entry = blame
7079 .update(cx, |blame, cx| {
7080 let row_infos =
7081 snapshot.row_infos(snapshot.longest_row()).next()?;
7082 blame.blame_for_rows(&[row_infos], cx).next()
7083 })
7084 .flatten()?;
7085 let workspace = editor.workspace.as_ref().map(|(w, _)| w.to_owned());
7086 let mut element = render_inline_blame_entry(
7087 blame,
7088 blame_entry,
7089 &style,
7090 workspace,
7091 cx,
7092 );
7093 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7094 Some(
7095 element
7096 .layout_as_root(AvailableSpace::min_size(), window, cx)
7097 .width
7098 + inline_blame_padding,
7099 )
7100 })
7101 .unwrap_or(Pixels::ZERO);
7102
7103 let longest_line_width = layout_line(
7104 snapshot.longest_row(),
7105 &snapshot,
7106 &style,
7107 editor_width,
7108 is_row_soft_wrapped,
7109 window,
7110 cx,
7111 )
7112 .width;
7113
7114 let scrollbar_range_data = ScrollbarRangeData::new(
7115 scrollbar_bounds,
7116 letter_size,
7117 &snapshot,
7118 longest_line_width,
7119 longest_line_blame_width,
7120 &style,
7121 editor_width,
7122 cx,
7123 );
7124
7125 let scroll_range_bounds = scrollbar_range_data.scroll_range;
7126 let mut scroll_width = scroll_range_bounds.size.width;
7127
7128 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7129 snapshot.sticky_header_excerpt(start_row)
7130 } else {
7131 None
7132 };
7133 let sticky_header_excerpt_id =
7134 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7135
7136 let blocks = window.with_element_namespace("blocks", |window| {
7137 self.render_blocks(
7138 start_row..end_row,
7139 &snapshot,
7140 &hitbox,
7141 &text_hitbox,
7142 editor_width,
7143 &mut scroll_width,
7144 &gutter_dimensions,
7145 em_width,
7146 gutter_dimensions.full_width(),
7147 line_height,
7148 &line_layouts,
7149 &local_selections,
7150 &selected_buffer_ids,
7151 is_row_soft_wrapped,
7152 sticky_header_excerpt_id,
7153 window,
7154 cx,
7155 )
7156 });
7157 let mut blocks = match blocks {
7158 Ok(blocks) => blocks,
7159 Err(resized_blocks) => {
7160 self.editor.update(cx, |editor, cx| {
7161 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7162 });
7163 return self.prepaint(None, bounds, &mut (), window, cx);
7164 }
7165 };
7166
7167 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7168 window.with_element_namespace("blocks", |window| {
7169 self.layout_sticky_buffer_header(
7170 sticky_header_excerpt,
7171 scroll_position.y,
7172 line_height,
7173 &snapshot,
7174 &hitbox,
7175 &selected_buffer_ids,
7176 window,
7177 cx,
7178 )
7179 })
7180 });
7181
7182 let start_buffer_row =
7183 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7184 let end_buffer_row =
7185 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7186
7187 let scroll_max = point(
7188 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7189 max_row.as_f32(),
7190 );
7191
7192 self.editor.update(cx, |editor, cx| {
7193 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7194
7195 let autoscrolled = if autoscroll_horizontally {
7196 editor.autoscroll_horizontally(
7197 start_row,
7198 editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7199 scroll_width,
7200 em_width,
7201 &line_layouts,
7202 cx,
7203 )
7204 } else {
7205 false
7206 };
7207
7208 if clamped || autoscrolled {
7209 snapshot = editor.snapshot(window, cx);
7210 scroll_position = snapshot.scroll_position();
7211 }
7212 });
7213
7214 let scroll_pixel_position = point(
7215 scroll_position.x * em_width,
7216 scroll_position.y * line_height,
7217 );
7218
7219 let indent_guides = self.layout_indent_guides(
7220 content_origin,
7221 text_hitbox.origin,
7222 start_buffer_row..end_buffer_row,
7223 scroll_pixel_position,
7224 line_height,
7225 &snapshot,
7226 window,
7227 cx,
7228 );
7229
7230 let crease_trailers =
7231 window.with_element_namespace("crease_trailers", |window| {
7232 self.prepaint_crease_trailers(
7233 crease_trailers,
7234 &line_layouts,
7235 line_height,
7236 content_origin,
7237 scroll_pixel_position,
7238 em_width,
7239 window,
7240 cx,
7241 )
7242 });
7243
7244 let mut inline_blame = None;
7245 if let Some(newest_selection_head) = newest_selection_head {
7246 let display_row = newest_selection_head.row();
7247 if (start_row..end_row).contains(&display_row) {
7248 let line_ix = display_row.minus(start_row) as usize;
7249 let row_info = &row_infos[line_ix];
7250 let line_layout = &line_layouts[line_ix];
7251 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7252 inline_blame = self.layout_inline_blame(
7253 display_row,
7254 row_info,
7255 line_layout,
7256 crease_trailer_layout,
7257 em_width,
7258 content_origin,
7259 scroll_pixel_position,
7260 line_height,
7261 window,
7262 cx,
7263 );
7264 }
7265 }
7266
7267 let blamed_display_rows = self.layout_blame_entries(
7268 &row_infos,
7269 em_width,
7270 scroll_position,
7271 line_height,
7272 &gutter_hitbox,
7273 gutter_dimensions.git_blame_entries_width,
7274 window,
7275 cx,
7276 );
7277
7278 let scroll_max = point(
7279 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7280 max_scroll_top,
7281 );
7282
7283 self.editor.update(cx, |editor, cx| {
7284 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7285
7286 let autoscrolled = if autoscroll_horizontally {
7287 editor.autoscroll_horizontally(
7288 start_row,
7289 editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7290 scroll_width,
7291 em_width,
7292 &line_layouts,
7293 cx,
7294 )
7295 } else {
7296 false
7297 };
7298
7299 if clamped || autoscrolled {
7300 snapshot = editor.snapshot(window, cx);
7301 scroll_position = snapshot.scroll_position();
7302 }
7303 });
7304
7305 let line_elements = self.prepaint_lines(
7306 start_row,
7307 &mut line_layouts,
7308 line_height,
7309 scroll_pixel_position,
7310 content_origin,
7311 window,
7312 cx,
7313 );
7314
7315 let mut block_start_rows = HashSet::default();
7316
7317 window.with_element_namespace("blocks", |window| {
7318 self.layout_blocks(
7319 &mut blocks,
7320 &mut block_start_rows,
7321 &hitbox,
7322 line_height,
7323 scroll_pixel_position,
7324 window,
7325 cx,
7326 );
7327 });
7328
7329 let cursors = self.collect_cursors(&snapshot, cx);
7330 let visible_row_range = start_row..end_row;
7331 let non_visible_cursors = cursors
7332 .iter()
7333 .any(|c| !visible_row_range.contains(&c.0.row()));
7334
7335 let visible_cursors = self.layout_visible_cursors(
7336 &snapshot,
7337 &selections,
7338 &block_start_rows,
7339 start_row..end_row,
7340 &line_layouts,
7341 &text_hitbox,
7342 content_origin,
7343 scroll_position,
7344 scroll_pixel_position,
7345 line_height,
7346 em_width,
7347 em_advance,
7348 autoscroll_containing_element,
7349 window,
7350 cx,
7351 );
7352
7353 let scrollbars_layout = self.layout_scrollbars(
7354 &snapshot,
7355 scrollbar_range_data,
7356 scroll_position,
7357 non_visible_cursors,
7358 window,
7359 cx,
7360 );
7361
7362 let gutter_settings = EditorSettings::get_global(cx).gutter;
7363
7364 let rows_with_hunk_bounds = display_hunks
7365 .iter()
7366 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7367 .fold(
7368 HashMap::default(),
7369 |mut rows_with_hunk_bounds, (hunk, bounds)| {
7370 match hunk {
7371 DisplayDiffHunk::Folded { display_row } => {
7372 rows_with_hunk_bounds.insert(*display_row, bounds);
7373 }
7374 DisplayDiffHunk::Unfolded {
7375 display_row_range, ..
7376 } => {
7377 for display_row in display_row_range.iter_rows() {
7378 rows_with_hunk_bounds.insert(display_row, bounds);
7379 }
7380 }
7381 }
7382 rows_with_hunk_bounds
7383 },
7384 );
7385 let mut code_actions_indicator = None;
7386 if let Some(newest_selection_head) = newest_selection_head {
7387 let newest_selection_point =
7388 newest_selection_head.to_point(&snapshot.display_snapshot);
7389
7390 if (start_row..end_row).contains(&newest_selection_head.row()) {
7391 self.layout_cursor_popovers(
7392 line_height,
7393 &text_hitbox,
7394 content_origin,
7395 start_row,
7396 scroll_pixel_position,
7397 &line_layouts,
7398 newest_selection_head,
7399 newest_selection_point,
7400 &style,
7401 window,
7402 cx,
7403 );
7404
7405 let show_code_actions = snapshot
7406 .show_code_actions
7407 .unwrap_or(gutter_settings.code_actions);
7408 if show_code_actions {
7409 let newest_selection_point =
7410 newest_selection_head.to_point(&snapshot.display_snapshot);
7411 if !snapshot
7412 .is_line_folded(MultiBufferRow(newest_selection_point.row))
7413 {
7414 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7415 MultiBufferRow(newest_selection_point.row),
7416 );
7417 if let Some((buffer, range)) = buffer {
7418 let buffer_id = buffer.remote_id();
7419 let row = range.start.row;
7420 let has_test_indicator = self
7421 .editor
7422 .read(cx)
7423 .tasks
7424 .contains_key(&(buffer_id, row));
7425
7426 if !has_test_indicator {
7427 code_actions_indicator = self
7428 .layout_code_actions_indicator(
7429 line_height,
7430 newest_selection_head,
7431 scroll_pixel_position,
7432 &gutter_dimensions,
7433 &gutter_hitbox,
7434 &rows_with_hunk_bounds,
7435 window,
7436 cx,
7437 );
7438 }
7439 }
7440 }
7441 }
7442 }
7443 }
7444
7445 self.layout_gutter_menu(
7446 line_height,
7447 &text_hitbox,
7448 content_origin,
7449 scroll_pixel_position,
7450 gutter_dimensions.width - gutter_dimensions.left_padding,
7451 window,
7452 cx,
7453 );
7454
7455 let test_indicators = if gutter_settings.runnables {
7456 self.layout_run_indicators(
7457 line_height,
7458 start_row..end_row,
7459 scroll_pixel_position,
7460 &gutter_dimensions,
7461 &gutter_hitbox,
7462 &rows_with_hunk_bounds,
7463 &snapshot,
7464 window,
7465 cx,
7466 )
7467 } else {
7468 Vec::new()
7469 };
7470
7471 self.layout_signature_help(
7472 &hitbox,
7473 content_origin,
7474 scroll_pixel_position,
7475 newest_selection_head,
7476 start_row,
7477 &line_layouts,
7478 line_height,
7479 em_width,
7480 window,
7481 cx,
7482 );
7483
7484 if !cx.has_active_drag() {
7485 self.layout_hover_popovers(
7486 &snapshot,
7487 &hitbox,
7488 &text_hitbox,
7489 start_row..end_row,
7490 content_origin,
7491 scroll_pixel_position,
7492 &line_layouts,
7493 line_height,
7494 em_width,
7495 window,
7496 cx,
7497 );
7498 }
7499
7500 let inline_completion_popover = self.layout_edit_prediction_popover(
7501 &text_hitbox.bounds,
7502 content_origin,
7503 &snapshot,
7504 start_row..end_row,
7505 scroll_position.y,
7506 scroll_position.y + height_in_lines,
7507 &line_layouts,
7508 line_height,
7509 scroll_pixel_position,
7510 newest_selection_head,
7511 editor_width,
7512 &style,
7513 window,
7514 cx,
7515 );
7516
7517 let mouse_context_menu = self.layout_mouse_context_menu(
7518 &snapshot,
7519 start_row..end_row,
7520 content_origin,
7521 window,
7522 cx,
7523 );
7524
7525 window.with_element_namespace("crease_toggles", |window| {
7526 self.prepaint_crease_toggles(
7527 &mut crease_toggles,
7528 line_height,
7529 &gutter_dimensions,
7530 gutter_settings,
7531 scroll_pixel_position,
7532 &gutter_hitbox,
7533 window,
7534 cx,
7535 )
7536 });
7537
7538 let invisible_symbol_font_size = font_size / 2.;
7539 let tab_invisible = window
7540 .text_system()
7541 .shape_line(
7542 "→".into(),
7543 invisible_symbol_font_size,
7544 &[TextRun {
7545 len: "→".len(),
7546 font: self.style.text.font(),
7547 color: cx.theme().colors().editor_invisible,
7548 background_color: None,
7549 underline: None,
7550 strikethrough: None,
7551 }],
7552 )
7553 .unwrap();
7554 let space_invisible = window
7555 .text_system()
7556 .shape_line(
7557 "•".into(),
7558 invisible_symbol_font_size,
7559 &[TextRun {
7560 len: "•".len(),
7561 font: self.style.text.font(),
7562 color: cx.theme().colors().editor_invisible,
7563 background_color: None,
7564 underline: None,
7565 strikethrough: None,
7566 }],
7567 )
7568 .unwrap();
7569
7570 let mode = snapshot.mode;
7571
7572 let position_map = Rc::new(PositionMap {
7573 size: bounds.size,
7574 visible_row_range,
7575 scroll_pixel_position,
7576 scroll_max,
7577 line_layouts,
7578 line_height,
7579 em_width,
7580 em_advance,
7581 snapshot,
7582 gutter_hitbox: gutter_hitbox.clone(),
7583 text_hitbox: text_hitbox.clone(),
7584 });
7585
7586 self.editor.update(cx, |editor, _| {
7587 editor.last_position_map = Some(position_map.clone())
7588 });
7589
7590 let hunk_controls = self.layout_diff_hunk_controls(
7591 start_row..end_row,
7592 &row_infos,
7593 &text_hitbox,
7594 &position_map,
7595 newest_selection_head,
7596 line_height,
7597 scroll_pixel_position,
7598 &display_hunks,
7599 self.editor.clone(),
7600 window,
7601 cx,
7602 );
7603
7604 EditorLayout {
7605 mode,
7606 position_map,
7607 visible_display_row_range: start_row..end_row,
7608 wrap_guides,
7609 indent_guides,
7610 hitbox,
7611 gutter_hitbox,
7612 display_hunks,
7613 content_origin,
7614 scrollbars_layout,
7615 active_rows,
7616 highlighted_rows,
7617 highlighted_ranges,
7618 highlighted_gutter_ranges,
7619 redacted_ranges,
7620 line_elements,
7621 line_numbers,
7622 blamed_display_rows,
7623 inline_blame,
7624 blocks,
7625 cursors,
7626 visible_cursors,
7627 selections,
7628 inline_completion_popover,
7629 diff_hunk_controls: hunk_controls,
7630 mouse_context_menu,
7631 test_indicators,
7632 code_actions_indicator,
7633 crease_toggles,
7634 crease_trailers,
7635 tab_invisible,
7636 space_invisible,
7637 sticky_buffer_header,
7638 }
7639 })
7640 })
7641 })
7642 }
7643
7644 fn paint(
7645 &mut self,
7646 _: Option<&GlobalElementId>,
7647 bounds: Bounds<gpui::Pixels>,
7648 _: &mut Self::RequestLayoutState,
7649 layout: &mut Self::PrepaintState,
7650 window: &mut Window,
7651 cx: &mut App,
7652 ) {
7653 let focus_handle = self.editor.focus_handle(cx);
7654 let key_context = self
7655 .editor
7656 .update(cx, |editor, cx| editor.key_context(window, cx));
7657
7658 window.set_key_context(key_context);
7659 window.handle_input(
7660 &focus_handle,
7661 ElementInputHandler::new(bounds, self.editor.clone()),
7662 cx,
7663 );
7664 self.register_actions(window, cx);
7665 self.register_key_listeners(window, cx, layout);
7666
7667 let text_style = TextStyleRefinement {
7668 font_size: Some(self.style.text.font_size),
7669 line_height: Some(self.style.text.line_height),
7670 ..Default::default()
7671 };
7672 let rem_size = self.rem_size(cx);
7673 window.with_rem_size(rem_size, |window| {
7674 window.with_text_style(Some(text_style), |window| {
7675 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7676 self.paint_mouse_listeners(layout, window, cx);
7677 self.paint_background(layout, window, cx);
7678 self.paint_indent_guides(layout, window, cx);
7679
7680 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7681 self.paint_blamed_display_rows(layout, window, cx);
7682 self.paint_line_numbers(layout, window, cx);
7683 }
7684
7685 self.paint_text(layout, window, cx);
7686
7687 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7688 self.paint_gutter_highlights(layout, window, cx);
7689 self.paint_gutter_indicators(layout, window, cx);
7690 }
7691
7692 if !layout.blocks.is_empty() {
7693 window.with_element_namespace("blocks", |window| {
7694 self.paint_blocks(layout, window, cx);
7695 });
7696 }
7697
7698 window.with_element_namespace("blocks", |window| {
7699 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7700 sticky_header.paint(window, cx)
7701 }
7702 });
7703
7704 self.paint_scrollbars(layout, window, cx);
7705 self.paint_inline_completion_popover(layout, window, cx);
7706 self.paint_mouse_context_menu(layout, window, cx);
7707 });
7708 })
7709 })
7710 }
7711}
7712
7713pub(super) fn gutter_bounds(
7714 editor_bounds: Bounds<Pixels>,
7715 gutter_dimensions: GutterDimensions,
7716) -> Bounds<Pixels> {
7717 Bounds {
7718 origin: editor_bounds.origin,
7719 size: size(gutter_dimensions.width, editor_bounds.size.height),
7720 }
7721}
7722
7723struct ScrollbarRangeData {
7724 scrollbar_bounds: Bounds<Pixels>,
7725 scroll_range: Bounds<Pixels>,
7726 letter_size: Size<Pixels>,
7727}
7728
7729impl ScrollbarRangeData {
7730 #[allow(clippy::too_many_arguments)]
7731 pub fn new(
7732 scrollbar_bounds: Bounds<Pixels>,
7733 letter_size: Size<Pixels>,
7734 snapshot: &EditorSnapshot,
7735 longest_line_width: Pixels,
7736 longest_line_blame_width: Pixels,
7737 style: &EditorStyle,
7738 editor_width: Pixels,
7739 cx: &mut App,
7740 ) -> ScrollbarRangeData {
7741 // TODO: Simplify this function down, it requires a lot of parameters
7742 let max_row = snapshot.max_point().row();
7743 let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7744
7745 let settings = EditorSettings::get_global(cx);
7746 let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7747 ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7748 ScrollBeyondLastLine::Off => px(1.),
7749 ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7750 };
7751
7752 let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7753 letter_size.width + style.scrollbar_width
7754 } else {
7755 px(0.0)
7756 };
7757
7758 let overscroll = size(
7759 right_margin + longest_line_blame_width,
7760 letter_size.height * scroll_beyond_last_line,
7761 );
7762
7763 let scroll_range = Bounds {
7764 origin: scrollbar_bounds.origin,
7765 size: text_bounds_size + overscroll,
7766 };
7767
7768 ScrollbarRangeData {
7769 scrollbar_bounds,
7770 scroll_range,
7771 letter_size,
7772 }
7773 }
7774}
7775
7776impl IntoElement for EditorElement {
7777 type Element = Self;
7778
7779 fn into_element(self) -> Self::Element {
7780 self
7781 }
7782}
7783
7784pub struct EditorLayout {
7785 position_map: Rc<PositionMap>,
7786 hitbox: Hitbox,
7787 gutter_hitbox: Hitbox,
7788 content_origin: gpui::Point<Pixels>,
7789 scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7790 mode: EditorMode,
7791 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7792 indent_guides: Option<Vec<IndentGuideLayout>>,
7793 visible_display_row_range: Range<DisplayRow>,
7794 active_rows: BTreeMap<DisplayRow, bool>,
7795 highlighted_rows: BTreeMap<DisplayRow, gpui::Background>,
7796 line_elements: SmallVec<[AnyElement; 1]>,
7797 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7798 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7799 blamed_display_rows: Option<Vec<AnyElement>>,
7800 inline_blame: Option<AnyElement>,
7801 blocks: Vec<BlockLayout>,
7802 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7803 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7804 redacted_ranges: Vec<Range<DisplayPoint>>,
7805 cursors: Vec<(DisplayPoint, Hsla)>,
7806 visible_cursors: Vec<CursorLayout>,
7807 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7808 code_actions_indicator: Option<AnyElement>,
7809 test_indicators: Vec<AnyElement>,
7810 crease_toggles: Vec<Option<AnyElement>>,
7811 diff_hunk_controls: Vec<AnyElement>,
7812 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7813 inline_completion_popover: Option<AnyElement>,
7814 mouse_context_menu: Option<AnyElement>,
7815 tab_invisible: ShapedLine,
7816 space_invisible: ShapedLine,
7817 sticky_buffer_header: Option<AnyElement>,
7818}
7819
7820impl EditorLayout {
7821 fn line_end_overshoot(&self) -> Pixels {
7822 0.15 * self.position_map.line_height
7823 }
7824}
7825
7826struct LineNumberLayout {
7827 shaped_line: ShapedLine,
7828 hitbox: Option<Hitbox>,
7829 display_row: DisplayRow,
7830}
7831
7832struct ColoredRange<T> {
7833 start: T,
7834 end: T,
7835 color: Hsla,
7836}
7837
7838#[derive(Clone)]
7839struct ScrollbarLayout {
7840 hitbox: Hitbox,
7841 visible_range: Range<f32>,
7842 visible: bool,
7843 text_unit_size: Pixels,
7844 thumb_size: Pixels,
7845 axis: Axis,
7846}
7847
7848impl ScrollbarLayout {
7849 const BORDER_WIDTH: Pixels = px(1.0);
7850 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7851 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7852 // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7853
7854 fn thumb_bounds(&self) -> Bounds<Pixels> {
7855 match self.axis {
7856 Axis::Vertical => {
7857 let thumb_top = self.y_for_row(self.visible_range.start);
7858 let thumb_bottom = thumb_top + self.thumb_size;
7859 Bounds::from_corners(
7860 point(self.hitbox.left(), thumb_top),
7861 point(self.hitbox.right(), thumb_bottom),
7862 )
7863 }
7864 Axis::Horizontal => {
7865 let thumb_left =
7866 self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7867 let thumb_right = thumb_left + self.thumb_size;
7868 Bounds::from_corners(
7869 point(thumb_left, self.hitbox.top()),
7870 point(thumb_right, self.hitbox.bottom()),
7871 )
7872 }
7873 }
7874 }
7875
7876 fn y_for_row(&self, row: f32) -> Pixels {
7877 self.hitbox.top() + row * self.text_unit_size
7878 }
7879
7880 fn marker_quads_for_ranges(
7881 &self,
7882 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7883 column: Option<usize>,
7884 ) -> Vec<PaintQuad> {
7885 struct MinMax {
7886 min: Pixels,
7887 max: Pixels,
7888 }
7889 let (x_range, height_limit) = if let Some(column) = column {
7890 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7891 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7892 let end = start + column_width;
7893 (
7894 Range { start, end },
7895 MinMax {
7896 min: Self::MIN_MARKER_HEIGHT,
7897 max: px(f32::MAX),
7898 },
7899 )
7900 } else {
7901 (
7902 Range {
7903 start: Self::BORDER_WIDTH,
7904 end: self.hitbox.size.width,
7905 },
7906 MinMax {
7907 min: Self::LINE_MARKER_HEIGHT,
7908 max: Self::LINE_MARKER_HEIGHT,
7909 },
7910 )
7911 };
7912
7913 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7914 let mut pixel_ranges = row_ranges
7915 .into_iter()
7916 .map(|range| {
7917 let start_y = row_to_y(range.start);
7918 let end_y = row_to_y(range.end)
7919 + self
7920 .text_unit_size
7921 .max(height_limit.min)
7922 .min(height_limit.max);
7923 ColoredRange {
7924 start: start_y,
7925 end: end_y,
7926 color: range.color,
7927 }
7928 })
7929 .peekable();
7930
7931 let mut quads = Vec::new();
7932 while let Some(mut pixel_range) = pixel_ranges.next() {
7933 while let Some(next_pixel_range) = pixel_ranges.peek() {
7934 if pixel_range.end >= next_pixel_range.start - px(1.0)
7935 && pixel_range.color == next_pixel_range.color
7936 {
7937 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7938 pixel_ranges.next();
7939 } else {
7940 break;
7941 }
7942 }
7943
7944 let bounds = Bounds::from_corners(
7945 point(x_range.start, pixel_range.start),
7946 point(x_range.end, pixel_range.end),
7947 );
7948 quads.push(quad(
7949 bounds,
7950 Corners::default(),
7951 pixel_range.color,
7952 Edges::default(),
7953 Hsla::transparent_black(),
7954 ));
7955 }
7956
7957 quads
7958 }
7959}
7960
7961struct CreaseTrailerLayout {
7962 element: AnyElement,
7963 bounds: Bounds<Pixels>,
7964}
7965
7966pub(crate) struct PositionMap {
7967 pub size: Size<Pixels>,
7968 pub line_height: Pixels,
7969 pub scroll_pixel_position: gpui::Point<Pixels>,
7970 pub scroll_max: gpui::Point<f32>,
7971 pub em_width: Pixels,
7972 pub em_advance: Pixels,
7973 pub visible_row_range: Range<DisplayRow>,
7974 pub line_layouts: Vec<LineWithInvisibles>,
7975 pub snapshot: EditorSnapshot,
7976 pub text_hitbox: Hitbox,
7977 pub gutter_hitbox: Hitbox,
7978}
7979
7980#[derive(Debug, Copy, Clone)]
7981pub struct PointForPosition {
7982 pub previous_valid: DisplayPoint,
7983 pub next_valid: DisplayPoint,
7984 pub exact_unclipped: DisplayPoint,
7985 pub column_overshoot_after_line_end: u32,
7986}
7987
7988impl PointForPosition {
7989 pub fn as_valid(&self) -> Option<DisplayPoint> {
7990 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
7991 Some(self.previous_valid)
7992 } else {
7993 None
7994 }
7995 }
7996}
7997
7998impl PositionMap {
7999 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8000 let text_bounds = self.text_hitbox.bounds;
8001 let scroll_position = self.snapshot.scroll_position();
8002 let position = position - text_bounds.origin;
8003 let y = position.y.max(px(0.)).min(self.size.height);
8004 let x = position.x + (scroll_position.x * self.em_width);
8005 let row = ((y / self.line_height) + scroll_position.y) as u32;
8006
8007 let (column, x_overshoot_after_line_end) = if let Some(line) = self
8008 .line_layouts
8009 .get(row as usize - scroll_position.y as usize)
8010 {
8011 if let Some(ix) = line.index_for_x(x) {
8012 (ix as u32, px(0.))
8013 } else {
8014 (line.len as u32, px(0.).max(x - line.width))
8015 }
8016 } else {
8017 (0, x)
8018 };
8019
8020 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8021 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8022 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8023
8024 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8025 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8026 PointForPosition {
8027 previous_valid,
8028 next_valid,
8029 exact_unclipped,
8030 column_overshoot_after_line_end,
8031 }
8032 }
8033}
8034
8035struct BlockLayout {
8036 id: BlockId,
8037 row: Option<DisplayRow>,
8038 element: AnyElement,
8039 available_space: Size<AvailableSpace>,
8040 style: BlockStyle,
8041}
8042
8043fn layout_line(
8044 row: DisplayRow,
8045 snapshot: &EditorSnapshot,
8046 style: &EditorStyle,
8047 text_width: Pixels,
8048 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8049 window: &mut Window,
8050 cx: &mut App,
8051) -> LineWithInvisibles {
8052 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8053 LineWithInvisibles::from_chunks(
8054 chunks,
8055 &style,
8056 MAX_LINE_LEN,
8057 1,
8058 snapshot.mode,
8059 text_width,
8060 is_row_soft_wrapped,
8061 window,
8062 cx,
8063 )
8064 .pop()
8065 .unwrap()
8066}
8067
8068#[derive(Debug)]
8069pub struct IndentGuideLayout {
8070 origin: gpui::Point<Pixels>,
8071 length: Pixels,
8072 single_indent_width: Pixels,
8073 depth: u32,
8074 active: bool,
8075 settings: IndentGuideSettings,
8076}
8077
8078pub struct CursorLayout {
8079 origin: gpui::Point<Pixels>,
8080 block_width: Pixels,
8081 line_height: Pixels,
8082 color: Hsla,
8083 shape: CursorShape,
8084 block_text: Option<ShapedLine>,
8085 cursor_name: Option<AnyElement>,
8086}
8087
8088#[derive(Debug)]
8089pub struct CursorName {
8090 string: SharedString,
8091 color: Hsla,
8092 is_top_row: bool,
8093}
8094
8095impl CursorLayout {
8096 pub fn new(
8097 origin: gpui::Point<Pixels>,
8098 block_width: Pixels,
8099 line_height: Pixels,
8100 color: Hsla,
8101 shape: CursorShape,
8102 block_text: Option<ShapedLine>,
8103 ) -> CursorLayout {
8104 CursorLayout {
8105 origin,
8106 block_width,
8107 line_height,
8108 color,
8109 shape,
8110 block_text,
8111 cursor_name: None,
8112 }
8113 }
8114
8115 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8116 Bounds {
8117 origin: self.origin + origin,
8118 size: size(self.block_width, self.line_height),
8119 }
8120 }
8121
8122 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8123 match self.shape {
8124 CursorShape::Bar => Bounds {
8125 origin: self.origin + origin,
8126 size: size(px(2.0), self.line_height),
8127 },
8128 CursorShape::Block | CursorShape::Hollow => Bounds {
8129 origin: self.origin + origin,
8130 size: size(self.block_width, self.line_height),
8131 },
8132 CursorShape::Underline => Bounds {
8133 origin: self.origin
8134 + origin
8135 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8136 size: size(self.block_width, px(2.0)),
8137 },
8138 }
8139 }
8140
8141 pub fn layout(
8142 &mut self,
8143 origin: gpui::Point<Pixels>,
8144 cursor_name: Option<CursorName>,
8145 window: &mut Window,
8146 cx: &mut App,
8147 ) {
8148 if let Some(cursor_name) = cursor_name {
8149 let bounds = self.bounds(origin);
8150 let text_size = self.line_height / 1.5;
8151
8152 let name_origin = if cursor_name.is_top_row {
8153 point(bounds.right() - px(1.), bounds.top())
8154 } else {
8155 match self.shape {
8156 CursorShape::Bar => point(
8157 bounds.right() - px(2.),
8158 bounds.top() - text_size / 2. - px(1.),
8159 ),
8160 _ => point(
8161 bounds.right() - px(1.),
8162 bounds.top() - text_size / 2. - px(1.),
8163 ),
8164 }
8165 };
8166 let mut name_element = div()
8167 .bg(self.color)
8168 .text_size(text_size)
8169 .px_0p5()
8170 .line_height(text_size + px(2.))
8171 .text_color(cursor_name.color)
8172 .child(cursor_name.string.clone())
8173 .into_any_element();
8174
8175 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8176
8177 self.cursor_name = Some(name_element);
8178 }
8179 }
8180
8181 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8182 let bounds = self.bounds(origin);
8183
8184 //Draw background or border quad
8185 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8186 outline(bounds, self.color)
8187 } else {
8188 fill(bounds, self.color)
8189 };
8190
8191 if let Some(name) = &mut self.cursor_name {
8192 name.paint(window, cx);
8193 }
8194
8195 window.paint_quad(cursor);
8196
8197 if let Some(block_text) = &self.block_text {
8198 block_text
8199 .paint(self.origin + origin, self.line_height, window, cx)
8200 .log_err();
8201 }
8202 }
8203
8204 pub fn shape(&self) -> CursorShape {
8205 self.shape
8206 }
8207}
8208
8209#[derive(Debug)]
8210pub struct HighlightedRange {
8211 pub start_y: Pixels,
8212 pub line_height: Pixels,
8213 pub lines: Vec<HighlightedRangeLine>,
8214 pub color: Hsla,
8215 pub corner_radius: Pixels,
8216}
8217
8218#[derive(Debug)]
8219pub struct HighlightedRangeLine {
8220 pub start_x: Pixels,
8221 pub end_x: Pixels,
8222}
8223
8224impl HighlightedRange {
8225 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8226 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8227 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8228 self.paint_lines(
8229 self.start_y + self.line_height,
8230 &self.lines[1..],
8231 bounds,
8232 window,
8233 );
8234 } else {
8235 self.paint_lines(self.start_y, &self.lines, bounds, window);
8236 }
8237 }
8238
8239 fn paint_lines(
8240 &self,
8241 start_y: Pixels,
8242 lines: &[HighlightedRangeLine],
8243 _bounds: Bounds<Pixels>,
8244 window: &mut Window,
8245 ) {
8246 if lines.is_empty() {
8247 return;
8248 }
8249
8250 let first_line = lines.first().unwrap();
8251 let last_line = lines.last().unwrap();
8252
8253 let first_top_left = point(first_line.start_x, start_y);
8254 let first_top_right = point(first_line.end_x, start_y);
8255
8256 let curve_height = point(Pixels::ZERO, self.corner_radius);
8257 let curve_width = |start_x: Pixels, end_x: Pixels| {
8258 let max = (end_x - start_x) / 2.;
8259 let width = if max < self.corner_radius {
8260 max
8261 } else {
8262 self.corner_radius
8263 };
8264
8265 point(width, Pixels::ZERO)
8266 };
8267
8268 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8269 let mut builder = gpui::PathBuilder::fill();
8270 builder.move_to(first_top_right - top_curve_width);
8271 builder.curve_to(first_top_right + curve_height, first_top_right);
8272
8273 let mut iter = lines.iter().enumerate().peekable();
8274 while let Some((ix, line)) = iter.next() {
8275 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8276
8277 if let Some((_, next_line)) = iter.peek() {
8278 let next_top_right = point(next_line.end_x, bottom_right.y);
8279
8280 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8281 Ordering::Equal => {
8282 builder.line_to(bottom_right);
8283 }
8284 Ordering::Less => {
8285 let curve_width = curve_width(next_top_right.x, bottom_right.x);
8286 builder.line_to(bottom_right - curve_height);
8287 if self.corner_radius > Pixels::ZERO {
8288 builder.curve_to(bottom_right - curve_width, bottom_right);
8289 }
8290 builder.line_to(next_top_right + curve_width);
8291 if self.corner_radius > Pixels::ZERO {
8292 builder.curve_to(next_top_right + curve_height, next_top_right);
8293 }
8294 }
8295 Ordering::Greater => {
8296 let curve_width = curve_width(bottom_right.x, next_top_right.x);
8297 builder.line_to(bottom_right - curve_height);
8298 if self.corner_radius > Pixels::ZERO {
8299 builder.curve_to(bottom_right + curve_width, bottom_right);
8300 }
8301 builder.line_to(next_top_right - curve_width);
8302 if self.corner_radius > Pixels::ZERO {
8303 builder.curve_to(next_top_right + curve_height, next_top_right);
8304 }
8305 }
8306 }
8307 } else {
8308 let curve_width = curve_width(line.start_x, line.end_x);
8309 builder.line_to(bottom_right - curve_height);
8310 if self.corner_radius > Pixels::ZERO {
8311 builder.curve_to(bottom_right - curve_width, bottom_right);
8312 }
8313
8314 let bottom_left = point(line.start_x, bottom_right.y);
8315 builder.line_to(bottom_left + curve_width);
8316 if self.corner_radius > Pixels::ZERO {
8317 builder.curve_to(bottom_left - curve_height, bottom_left);
8318 }
8319 }
8320 }
8321
8322 if first_line.start_x > last_line.start_x {
8323 let curve_width = curve_width(last_line.start_x, first_line.start_x);
8324 let second_top_left = point(last_line.start_x, start_y + self.line_height);
8325 builder.line_to(second_top_left + curve_height);
8326 if self.corner_radius > Pixels::ZERO {
8327 builder.curve_to(second_top_left + curve_width, second_top_left);
8328 }
8329 let first_bottom_left = point(first_line.start_x, second_top_left.y);
8330 builder.line_to(first_bottom_left - curve_width);
8331 if self.corner_radius > Pixels::ZERO {
8332 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8333 }
8334 }
8335
8336 builder.line_to(first_top_left + curve_height);
8337 if self.corner_radius > Pixels::ZERO {
8338 builder.curve_to(first_top_left + top_curve_width, first_top_left);
8339 }
8340 builder.line_to(first_top_right - top_curve_width);
8341
8342 if let Ok(path) = builder.build() {
8343 window.paint_path(path, self.color);
8344 }
8345 }
8346}
8347
8348enum CursorPopoverType {
8349 CodeContextMenu,
8350 EditPrediction,
8351}
8352
8353pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8354 (delta.pow(1.5) / 100.0).into()
8355}
8356
8357fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8358 (delta.pow(1.2) / 300.0).into()
8359}
8360
8361pub fn register_action<T: Action>(
8362 editor: &Entity<Editor>,
8363 window: &mut Window,
8364 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8365) {
8366 let editor = editor.clone();
8367 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8368 let action = action.downcast_ref().unwrap();
8369 if phase == DispatchPhase::Bubble {
8370 editor.update(cx, |editor, cx| {
8371 listener(editor, action, window, cx);
8372 })
8373 }
8374 })
8375}
8376
8377fn compute_auto_height_layout(
8378 editor: &mut Editor,
8379 max_lines: usize,
8380 max_line_number_width: Pixels,
8381 known_dimensions: Size<Option<Pixels>>,
8382 available_width: AvailableSpace,
8383 window: &mut Window,
8384 cx: &mut Context<Editor>,
8385) -> Option<Size<Pixels>> {
8386 let width = known_dimensions.width.or({
8387 if let AvailableSpace::Definite(available_width) = available_width {
8388 Some(available_width)
8389 } else {
8390 None
8391 }
8392 })?;
8393 if let Some(height) = known_dimensions.height {
8394 return Some(size(width, height));
8395 }
8396
8397 let style = editor.style.as_ref().unwrap();
8398 let font_id = window.text_system().resolve_font(&style.text.font());
8399 let font_size = style.text.font_size.to_pixels(window.rem_size());
8400 let line_height = style.text.line_height_in_pixels(window.rem_size());
8401 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8402
8403 let mut snapshot = editor.snapshot(window, cx);
8404 let gutter_dimensions = snapshot
8405 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8406 .unwrap_or_default();
8407
8408 editor.gutter_dimensions = gutter_dimensions;
8409 let text_width = width - gutter_dimensions.width;
8410 let overscroll = size(em_width, px(0.));
8411
8412 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8413 if editor.set_wrap_width(Some(editor_width), cx) {
8414 snapshot = editor.snapshot(window, cx);
8415 }
8416
8417 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8418 let height = scroll_height
8419 .max(line_height)
8420 .min(line_height * max_lines as f32);
8421
8422 Some(size(width, height))
8423}
8424
8425#[cfg(test)]
8426mod tests {
8427 use super::*;
8428 use crate::{
8429 display_map::{BlockPlacement, BlockProperties},
8430 editor_tests::{init_test, update_test_language_settings},
8431 Editor, MultiBuffer,
8432 };
8433 use gpui::{TestAppContext, VisualTestContext};
8434 use language::language_settings;
8435 use log::info;
8436 use similar::DiffableStr;
8437 use std::num::NonZeroU32;
8438 use util::test::sample_text;
8439
8440 #[gpui::test]
8441 fn test_shape_line_numbers(cx: &mut TestAppContext) {
8442 init_test(cx, |_| {});
8443 let window = cx.add_window(|window, cx| {
8444 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8445 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8446 });
8447
8448 let editor = window.root(cx).unwrap();
8449 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8450 let line_height = window
8451 .update(cx, |_, window, _| {
8452 style.text.line_height_in_pixels(window.rem_size())
8453 })
8454 .unwrap();
8455 let element = EditorElement::new(&editor, style);
8456 let snapshot = window
8457 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8458 .unwrap();
8459
8460 let layouts = cx
8461 .update_window(*window, |_, window, cx| {
8462 element.layout_line_numbers(
8463 None,
8464 GutterDimensions {
8465 left_padding: Pixels::ZERO,
8466 right_padding: Pixels::ZERO,
8467 width: px(30.0),
8468 margin: Pixels::ZERO,
8469 git_blame_entries_width: None,
8470 },
8471 line_height,
8472 gpui::Point::default(),
8473 DisplayRow(0)..DisplayRow(6),
8474 &(0..6)
8475 .map(|row| RowInfo {
8476 buffer_row: Some(row),
8477 ..Default::default()
8478 })
8479 .collect::<Vec<_>>(),
8480 Some(DisplayPoint::new(DisplayRow(0), 0)),
8481 &snapshot,
8482 window,
8483 cx,
8484 )
8485 })
8486 .unwrap();
8487 assert_eq!(layouts.len(), 6);
8488
8489 let relative_rows = window
8490 .update(cx, |editor, window, cx| {
8491 let snapshot = editor.snapshot(window, cx);
8492 element.calculate_relative_line_numbers(
8493 &snapshot,
8494 &(DisplayRow(0)..DisplayRow(6)),
8495 Some(DisplayRow(3)),
8496 )
8497 })
8498 .unwrap();
8499 assert_eq!(relative_rows[&DisplayRow(0)], 3);
8500 assert_eq!(relative_rows[&DisplayRow(1)], 2);
8501 assert_eq!(relative_rows[&DisplayRow(2)], 1);
8502 // current line has no relative number
8503 assert_eq!(relative_rows[&DisplayRow(4)], 1);
8504 assert_eq!(relative_rows[&DisplayRow(5)], 2);
8505
8506 // works if cursor is before screen
8507 let relative_rows = window
8508 .update(cx, |editor, window, cx| {
8509 let snapshot = editor.snapshot(window, cx);
8510 element.calculate_relative_line_numbers(
8511 &snapshot,
8512 &(DisplayRow(3)..DisplayRow(6)),
8513 Some(DisplayRow(1)),
8514 )
8515 })
8516 .unwrap();
8517 assert_eq!(relative_rows.len(), 3);
8518 assert_eq!(relative_rows[&DisplayRow(3)], 2);
8519 assert_eq!(relative_rows[&DisplayRow(4)], 3);
8520 assert_eq!(relative_rows[&DisplayRow(5)], 4);
8521
8522 // works if cursor is after screen
8523 let relative_rows = window
8524 .update(cx, |editor, window, cx| {
8525 let snapshot = editor.snapshot(window, cx);
8526 element.calculate_relative_line_numbers(
8527 &snapshot,
8528 &(DisplayRow(0)..DisplayRow(3)),
8529 Some(DisplayRow(6)),
8530 )
8531 })
8532 .unwrap();
8533 assert_eq!(relative_rows.len(), 3);
8534 assert_eq!(relative_rows[&DisplayRow(0)], 5);
8535 assert_eq!(relative_rows[&DisplayRow(1)], 4);
8536 assert_eq!(relative_rows[&DisplayRow(2)], 3);
8537 }
8538
8539 #[gpui::test]
8540 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8541 init_test(cx, |_| {});
8542
8543 let window = cx.add_window(|window, cx| {
8544 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8545 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8546 });
8547 let cx = &mut VisualTestContext::from_window(*window, cx);
8548 let editor = window.root(cx).unwrap();
8549 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8550
8551 window
8552 .update(cx, |editor, window, cx| {
8553 editor.cursor_shape = CursorShape::Block;
8554 editor.change_selections(None, window, cx, |s| {
8555 s.select_ranges([
8556 Point::new(0, 0)..Point::new(1, 0),
8557 Point::new(3, 2)..Point::new(3, 3),
8558 Point::new(5, 6)..Point::new(6, 0),
8559 ]);
8560 });
8561 })
8562 .unwrap();
8563
8564 let (_, state) = cx.draw(
8565 point(px(500.), px(500.)),
8566 size(px(500.), px(500.)),
8567 |_, _| EditorElement::new(&editor, style),
8568 );
8569
8570 assert_eq!(state.selections.len(), 1);
8571 let local_selections = &state.selections[0].1;
8572 assert_eq!(local_selections.len(), 3);
8573 // moves cursor back one line
8574 assert_eq!(
8575 local_selections[0].head,
8576 DisplayPoint::new(DisplayRow(0), 6)
8577 );
8578 assert_eq!(
8579 local_selections[0].range,
8580 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8581 );
8582
8583 // moves cursor back one column
8584 assert_eq!(
8585 local_selections[1].range,
8586 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8587 );
8588 assert_eq!(
8589 local_selections[1].head,
8590 DisplayPoint::new(DisplayRow(3), 2)
8591 );
8592
8593 // leaves cursor on the max point
8594 assert_eq!(
8595 local_selections[2].range,
8596 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8597 );
8598 assert_eq!(
8599 local_selections[2].head,
8600 DisplayPoint::new(DisplayRow(6), 0)
8601 );
8602
8603 // active lines does not include 1 (even though the range of the selection does)
8604 assert_eq!(
8605 state.active_rows.keys().cloned().collect::<Vec<_>>(),
8606 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8607 );
8608
8609 // multi-buffer support
8610 // in DisplayPoint coordinates, this is what we're dealing with:
8611 // 0: [[file
8612 // 1: header
8613 // 2: section]]
8614 // 3: aaaaaa
8615 // 4: bbbbbb
8616 // 5: cccccc
8617 // 6:
8618 // 7: [[footer]]
8619 // 8: [[header]]
8620 // 9: ffffff
8621 // 10: gggggg
8622 // 11: hhhhhh
8623 // 12:
8624 // 13: [[footer]]
8625 // 14: [[file
8626 // 15: header
8627 // 16: section]]
8628 // 17: bbbbbb
8629 // 18: cccccc
8630 // 19: dddddd
8631 // 20: [[footer]]
8632 let window = cx.add_window(|window, cx| {
8633 let buffer = MultiBuffer::build_multi(
8634 [
8635 (
8636 &(sample_text(8, 6, 'a') + "\n"),
8637 vec![
8638 Point::new(0, 0)..Point::new(3, 0),
8639 Point::new(4, 0)..Point::new(7, 0),
8640 ],
8641 ),
8642 (
8643 &(sample_text(8, 6, 'a') + "\n"),
8644 vec![Point::new(1, 0)..Point::new(3, 0)],
8645 ),
8646 ],
8647 cx,
8648 );
8649 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8650 });
8651 let editor = window.root(cx).unwrap();
8652 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8653 let _state = window.update(cx, |editor, window, cx| {
8654 editor.cursor_shape = CursorShape::Block;
8655 editor.change_selections(None, window, cx, |s| {
8656 s.select_display_ranges([
8657 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8658 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8659 ]);
8660 });
8661 });
8662
8663 let (_, state) = cx.draw(
8664 point(px(500.), px(500.)),
8665 size(px(500.), px(500.)),
8666 |_, _| EditorElement::new(&editor, style),
8667 );
8668 assert_eq!(state.selections.len(), 1);
8669 let local_selections = &state.selections[0].1;
8670 assert_eq!(local_selections.len(), 2);
8671
8672 // moves cursor on excerpt boundary back a line
8673 // and doesn't allow selection to bleed through
8674 assert_eq!(
8675 local_selections[0].range,
8676 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8677 );
8678 assert_eq!(
8679 local_selections[0].head,
8680 DisplayPoint::new(DisplayRow(6), 0)
8681 );
8682 // moves cursor on buffer boundary back two lines
8683 // and doesn't allow selection to bleed through
8684 assert_eq!(
8685 local_selections[1].range,
8686 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8687 );
8688 assert_eq!(
8689 local_selections[1].head,
8690 DisplayPoint::new(DisplayRow(12), 0)
8691 );
8692 }
8693
8694 #[gpui::test]
8695 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8696 init_test(cx, |_| {});
8697
8698 let window = cx.add_window(|window, cx| {
8699 let buffer = MultiBuffer::build_simple("", cx);
8700 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8701 });
8702 let cx = &mut VisualTestContext::from_window(*window, cx);
8703 let editor = window.root(cx).unwrap();
8704 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8705 window
8706 .update(cx, |editor, window, cx| {
8707 editor.set_placeholder_text("hello", cx);
8708 editor.insert_blocks(
8709 [BlockProperties {
8710 style: BlockStyle::Fixed,
8711 placement: BlockPlacement::Above(Anchor::min()),
8712 height: 3,
8713 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8714 priority: 0,
8715 }],
8716 None,
8717 cx,
8718 );
8719
8720 // Blur the editor so that it displays placeholder text.
8721 window.blur();
8722 })
8723 .unwrap();
8724
8725 let (_, state) = cx.draw(
8726 point(px(500.), px(500.)),
8727 size(px(500.), px(500.)),
8728 |_, _| EditorElement::new(&editor, style),
8729 );
8730 assert_eq!(state.position_map.line_layouts.len(), 4);
8731 assert_eq!(state.line_numbers.len(), 1);
8732 assert_eq!(
8733 state
8734 .line_numbers
8735 .get(&MultiBufferRow(0))
8736 .and_then(|line_number| line_number.shaped_line.text.as_str()),
8737 Some("1")
8738 );
8739 }
8740
8741 #[gpui::test]
8742 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8743 const TAB_SIZE: u32 = 4;
8744
8745 let input_text = "\t \t|\t| a b";
8746 let expected_invisibles = vec![
8747 Invisible::Tab {
8748 line_start_offset: 0,
8749 line_end_offset: TAB_SIZE as usize,
8750 },
8751 Invisible::Whitespace {
8752 line_offset: TAB_SIZE as usize,
8753 },
8754 Invisible::Tab {
8755 line_start_offset: TAB_SIZE as usize + 1,
8756 line_end_offset: TAB_SIZE as usize * 2,
8757 },
8758 Invisible::Tab {
8759 line_start_offset: TAB_SIZE as usize * 2 + 1,
8760 line_end_offset: TAB_SIZE as usize * 3,
8761 },
8762 Invisible::Whitespace {
8763 line_offset: TAB_SIZE as usize * 3 + 1,
8764 },
8765 Invisible::Whitespace {
8766 line_offset: TAB_SIZE as usize * 3 + 3,
8767 },
8768 ];
8769 assert_eq!(
8770 expected_invisibles.len(),
8771 input_text
8772 .chars()
8773 .filter(|initial_char| initial_char.is_whitespace())
8774 .count(),
8775 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8776 );
8777
8778 for show_line_numbers in [true, false] {
8779 init_test(cx, |s| {
8780 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8781 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8782 });
8783
8784 let actual_invisibles = collect_invisibles_from_new_editor(
8785 cx,
8786 EditorMode::Full,
8787 input_text,
8788 px(500.0),
8789 show_line_numbers,
8790 );
8791
8792 assert_eq!(expected_invisibles, actual_invisibles);
8793 }
8794 }
8795
8796 #[gpui::test]
8797 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8798 init_test(cx, |s| {
8799 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8800 s.defaults.tab_size = NonZeroU32::new(4);
8801 });
8802
8803 for editor_mode_without_invisibles in [
8804 EditorMode::SingleLine { auto_width: false },
8805 EditorMode::AutoHeight { max_lines: 100 },
8806 ] {
8807 for show_line_numbers in [true, false] {
8808 let invisibles = collect_invisibles_from_new_editor(
8809 cx,
8810 editor_mode_without_invisibles,
8811 "\t\t\t| | a b",
8812 px(500.0),
8813 show_line_numbers,
8814 );
8815 assert!(invisibles.is_empty(),
8816 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8817 }
8818 }
8819 }
8820
8821 #[gpui::test]
8822 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8823 let tab_size = 4;
8824 let input_text = "a\tbcd ".repeat(9);
8825 let repeated_invisibles = [
8826 Invisible::Tab {
8827 line_start_offset: 1,
8828 line_end_offset: tab_size as usize,
8829 },
8830 Invisible::Whitespace {
8831 line_offset: tab_size as usize + 3,
8832 },
8833 Invisible::Whitespace {
8834 line_offset: tab_size as usize + 4,
8835 },
8836 Invisible::Whitespace {
8837 line_offset: tab_size as usize + 5,
8838 },
8839 Invisible::Whitespace {
8840 line_offset: tab_size as usize + 6,
8841 },
8842 Invisible::Whitespace {
8843 line_offset: tab_size as usize + 7,
8844 },
8845 ];
8846 let expected_invisibles = std::iter::once(repeated_invisibles)
8847 .cycle()
8848 .take(9)
8849 .flatten()
8850 .collect::<Vec<_>>();
8851 assert_eq!(
8852 expected_invisibles.len(),
8853 input_text
8854 .chars()
8855 .filter(|initial_char| initial_char.is_whitespace())
8856 .count(),
8857 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8858 );
8859 info!("Expected invisibles: {expected_invisibles:?}");
8860
8861 init_test(cx, |_| {});
8862
8863 // Put the same string with repeating whitespace pattern into editors of various size,
8864 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8865 let resize_step = 10.0;
8866 let mut editor_width = 200.0;
8867 while editor_width <= 1000.0 {
8868 for show_line_numbers in [true, false] {
8869 update_test_language_settings(cx, |s| {
8870 s.defaults.tab_size = NonZeroU32::new(tab_size);
8871 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8872 s.defaults.preferred_line_length = Some(editor_width as u32);
8873 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8874 });
8875
8876 let actual_invisibles = collect_invisibles_from_new_editor(
8877 cx,
8878 EditorMode::Full,
8879 &input_text,
8880 px(editor_width),
8881 show_line_numbers,
8882 );
8883
8884 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8885 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8886 let mut i = 0;
8887 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8888 i = actual_index;
8889 match expected_invisibles.get(i) {
8890 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8891 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8892 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8893 _ => {
8894 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8895 }
8896 },
8897 None => {
8898 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8899 }
8900 }
8901 }
8902 let missing_expected_invisibles = &expected_invisibles[i + 1..];
8903 assert!(
8904 missing_expected_invisibles.is_empty(),
8905 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8906 );
8907
8908 editor_width += resize_step;
8909 }
8910 }
8911 }
8912
8913 fn collect_invisibles_from_new_editor(
8914 cx: &mut TestAppContext,
8915 editor_mode: EditorMode,
8916 input_text: &str,
8917 editor_width: Pixels,
8918 show_line_numbers: bool,
8919 ) -> Vec<Invisible> {
8920 info!(
8921 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8922 editor_width.0
8923 );
8924 let window = cx.add_window(|window, cx| {
8925 let buffer = MultiBuffer::build_simple(input_text, cx);
8926 Editor::new(editor_mode, buffer, None, true, window, cx)
8927 });
8928 let cx = &mut VisualTestContext::from_window(*window, cx);
8929 let editor = window.root(cx).unwrap();
8930
8931 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8932 window
8933 .update(cx, |editor, _, cx| {
8934 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8935 editor.set_wrap_width(Some(editor_width), cx);
8936 editor.set_show_line_numbers(show_line_numbers, cx);
8937 })
8938 .unwrap();
8939 let (_, state) = cx.draw(
8940 point(px(500.), px(500.)),
8941 size(px(500.), px(500.)),
8942 |_, _| EditorElement::new(&editor, style),
8943 );
8944 state
8945 .position_map
8946 .line_layouts
8947 .iter()
8948 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8949 .cloned()
8950 .collect()
8951 }
8952}
8953
8954fn diff_hunk_controls(
8955 row: u32,
8956 hunk_range: Range<Anchor>,
8957 line_height: Pixels,
8958 editor: &Entity<Editor>,
8959 cx: &mut App,
8960) -> AnyElement {
8961 h_flex()
8962 .h(line_height)
8963 .mr_1()
8964 .gap_1()
8965 .px_1()
8966 .pb_1()
8967 .border_b_1()
8968 .border_color(cx.theme().colors().border_variant)
8969 .rounded_b_lg()
8970 .bg(cx.theme().colors().editor_background)
8971 .gap_1()
8972 .child(
8973 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
8974 .shape(IconButtonShape::Square)
8975 .icon_size(IconSize::Small)
8976 // .disabled(!has_multiple_hunks)
8977 .tooltip({
8978 let focus_handle = editor.focus_handle(cx);
8979 move |window, cx| {
8980 Tooltip::for_action_in("Next Hunk", &GoToHunk, &focus_handle, window, cx)
8981 }
8982 })
8983 .on_click({
8984 let editor = editor.clone();
8985 move |_event, window, cx| {
8986 editor.update(cx, |editor, cx| {
8987 let snapshot = editor.snapshot(window, cx);
8988 let position = hunk_range.end.to_point(&snapshot.buffer_snapshot);
8989 editor.go_to_hunk_after_position(&snapshot, position, window, cx);
8990 editor.expand_selected_diff_hunks(cx);
8991 });
8992 }
8993 }),
8994 )
8995 .child(
8996 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
8997 .shape(IconButtonShape::Square)
8998 .icon_size(IconSize::Small)
8999 // .disabled(!has_multiple_hunks)
9000 .tooltip({
9001 let focus_handle = editor.focus_handle(cx);
9002 move |window, cx| {
9003 Tooltip::for_action_in(
9004 "Previous Hunk",
9005 &GoToPrevHunk,
9006 &focus_handle,
9007 window,
9008 cx,
9009 )
9010 }
9011 })
9012 .on_click({
9013 let editor = editor.clone();
9014 move |_event, window, cx| {
9015 editor.update(cx, |editor, cx| {
9016 let snapshot = editor.snapshot(window, cx);
9017 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9018 editor.go_to_hunk_before_position(&snapshot, point, window, cx);
9019 editor.expand_selected_diff_hunks(cx);
9020 });
9021 }
9022 }),
9023 )
9024 .child(
9025 IconButton::new("discard", IconName::Undo)
9026 .shape(IconButtonShape::Square)
9027 .icon_size(IconSize::Small)
9028 .tooltip({
9029 let focus_handle = editor.focus_handle(cx);
9030 move |window, cx| {
9031 Tooltip::for_action_in(
9032 "Discard Hunk",
9033 &RevertSelectedHunks,
9034 &focus_handle,
9035 window,
9036 cx,
9037 )
9038 }
9039 })
9040 .on_click({
9041 let editor = editor.clone();
9042 move |_event, window, cx| {
9043 editor.update(cx, |editor, cx| {
9044 let snapshot = editor.snapshot(window, cx);
9045 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9046 editor.revert_hunks_in_ranges([point..point].into_iter(), window, cx);
9047 });
9048 }
9049 }),
9050 )
9051 .into_any_element()
9052}