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