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