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