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 )
2735 .map(|binding| binding.into_any_element()),
2736 ),
2737 )
2738 })
2739 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
2740 .on_click(window.listener_for(&self.editor, {
2741 move |editor, e: &ClickEvent, window, cx| {
2742 editor.open_excerpts_common(
2743 Some(jump_data.clone()),
2744 e.down.modifiers.secondary(),
2745 window,
2746 cx,
2747 );
2748 }
2749 })),
2750 ),
2751 )
2752 }
2753
2754 fn render_expand_excerpt_control(
2755 &self,
2756 block_id: BlockId,
2757 direction: ExpandExcerptDirection,
2758 excerpt_id: ExcerptId,
2759 gutter_dimensions: &GutterDimensions,
2760 window: &Window,
2761 cx: &mut App,
2762 ) -> impl IntoElement {
2763 let color = cx.theme().colors().clone();
2764 let hover_color = color.border_variant.opacity(0.5);
2765 let focus_handle = self.editor.focus_handle(cx).clone();
2766
2767 let icon_offset =
2768 gutter_dimensions.width - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2769 let header_height = MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * window.line_height();
2770 let group_name = if direction == ExpandExcerptDirection::Down {
2771 "expand-down"
2772 } else {
2773 "expand-up"
2774 };
2775
2776 let expand_area = |id: SharedString| {
2777 h_flex()
2778 .id(id)
2779 .w_full()
2780 .cursor_pointer()
2781 .block_mouse_down()
2782 .on_mouse_move(|_, _, cx| cx.stop_propagation())
2783 .hover(|style| style.bg(hover_color))
2784 .tooltip({
2785 let focus_handle = focus_handle.clone();
2786 move |window, cx| {
2787 Tooltip::for_action_in(
2788 "Expand Excerpt",
2789 &ExpandExcerpts { lines: 0 },
2790 &focus_handle,
2791 window,
2792 cx,
2793 )
2794 }
2795 })
2796 };
2797
2798 expand_area(
2799 format!(
2800 "block-{}-{}",
2801 block_id,
2802 if direction == ExpandExcerptDirection::Down {
2803 "down"
2804 } else {
2805 "up"
2806 }
2807 )
2808 .into(),
2809 )
2810 .group(group_name)
2811 .child(
2812 h_flex()
2813 .w(icon_offset)
2814 .h(header_height)
2815 .flex_none()
2816 .justify_end()
2817 .child(
2818 ButtonLike::new("expand-icon")
2819 .style(ButtonStyle::Transparent)
2820 .child(
2821 svg()
2822 .path(if direction == ExpandExcerptDirection::Down {
2823 IconName::ArrowDownFromLine.path()
2824 } else {
2825 IconName::ArrowUpFromLine.path()
2826 })
2827 .size(IconSize::XSmall.rems())
2828 .text_color(cx.theme().colors().editor_line_number)
2829 .group_hover(group_name, |style| {
2830 style.text_color(cx.theme().colors().editor_active_line_number)
2831 }),
2832 ),
2833 ),
2834 )
2835 .on_click(window.listener_for(&self.editor, {
2836 move |editor, _, _, cx| {
2837 editor.expand_excerpt(excerpt_id, direction, cx);
2838 cx.stop_propagation();
2839 }
2840 }))
2841 }
2842
2843 #[allow(clippy::too_many_arguments)]
2844 fn render_blocks(
2845 &self,
2846 rows: Range<DisplayRow>,
2847 snapshot: &EditorSnapshot,
2848 hitbox: &Hitbox,
2849 text_hitbox: &Hitbox,
2850 editor_width: Pixels,
2851 scroll_width: &mut Pixels,
2852 gutter_dimensions: &GutterDimensions,
2853 em_width: Pixels,
2854 text_x: Pixels,
2855 line_height: Pixels,
2856 line_layouts: &[LineWithInvisibles],
2857 selections: &[Selection<Point>],
2858 selected_buffer_ids: &Vec<BufferId>,
2859 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2860 sticky_header_excerpt_id: Option<ExcerptId>,
2861 window: &mut Window,
2862 cx: &mut App,
2863 ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2864 let (fixed_blocks, non_fixed_blocks) = snapshot
2865 .blocks_in_range(rows.clone())
2866 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2867
2868 let mut focused_block = self
2869 .editor
2870 .update(cx, |editor, _| editor.take_focused_block());
2871 let mut fixed_block_max_width = Pixels::ZERO;
2872 let mut blocks = Vec::new();
2873 let mut resized_blocks = HashMap::default();
2874
2875 for (row, block) in fixed_blocks {
2876 let block_id = block.id();
2877
2878 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2879 focused_block = None;
2880 }
2881
2882 let (element, element_size) = self.render_block(
2883 block,
2884 AvailableSpace::MinContent,
2885 block_id,
2886 row,
2887 snapshot,
2888 text_x,
2889 &rows,
2890 line_layouts,
2891 gutter_dimensions,
2892 line_height,
2893 em_width,
2894 text_hitbox,
2895 editor_width,
2896 scroll_width,
2897 &mut resized_blocks,
2898 selections,
2899 selected_buffer_ids,
2900 is_row_soft_wrapped,
2901 sticky_header_excerpt_id,
2902 window,
2903 cx,
2904 );
2905 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2906 blocks.push(BlockLayout {
2907 id: block_id,
2908 row: Some(row),
2909 element,
2910 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2911 style: BlockStyle::Fixed,
2912 });
2913 }
2914
2915 for (row, block) in non_fixed_blocks {
2916 let style = block.style();
2917 let width = match style {
2918 BlockStyle::Sticky => hitbox.size.width,
2919 BlockStyle::Flex => hitbox
2920 .size
2921 .width
2922 .max(fixed_block_max_width)
2923 .max(gutter_dimensions.width + *scroll_width),
2924 BlockStyle::Fixed => unreachable!(),
2925 };
2926 let block_id = block.id();
2927
2928 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2929 focused_block = None;
2930 }
2931
2932 let (element, element_size) = self.render_block(
2933 block,
2934 width.into(),
2935 block_id,
2936 row,
2937 snapshot,
2938 text_x,
2939 &rows,
2940 line_layouts,
2941 gutter_dimensions,
2942 line_height,
2943 em_width,
2944 text_hitbox,
2945 editor_width,
2946 scroll_width,
2947 &mut resized_blocks,
2948 selections,
2949 selected_buffer_ids,
2950 is_row_soft_wrapped,
2951 sticky_header_excerpt_id,
2952 window,
2953 cx,
2954 );
2955
2956 blocks.push(BlockLayout {
2957 id: block_id,
2958 row: Some(row),
2959 element,
2960 available_space: size(width.into(), element_size.height.into()),
2961 style,
2962 });
2963 }
2964
2965 if let Some(focused_block) = focused_block {
2966 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2967 if focus_handle.is_focused(window) {
2968 if let Some(block) = snapshot.block_for_id(focused_block.id) {
2969 let style = block.style();
2970 let width = match style {
2971 BlockStyle::Fixed => AvailableSpace::MinContent,
2972 BlockStyle::Flex => AvailableSpace::Definite(
2973 hitbox
2974 .size
2975 .width
2976 .max(fixed_block_max_width)
2977 .max(gutter_dimensions.width + *scroll_width),
2978 ),
2979 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2980 };
2981
2982 let (element, element_size) = self.render_block(
2983 &block,
2984 width,
2985 focused_block.id,
2986 rows.end,
2987 snapshot,
2988 text_x,
2989 &rows,
2990 line_layouts,
2991 gutter_dimensions,
2992 line_height,
2993 em_width,
2994 text_hitbox,
2995 editor_width,
2996 scroll_width,
2997 &mut resized_blocks,
2998 selections,
2999 selected_buffer_ids,
3000 is_row_soft_wrapped,
3001 sticky_header_excerpt_id,
3002 window,
3003 cx,
3004 );
3005
3006 blocks.push(BlockLayout {
3007 id: block.id(),
3008 row: None,
3009 element,
3010 available_space: size(width, element_size.height.into()),
3011 style,
3012 });
3013 }
3014 }
3015 }
3016 }
3017
3018 if resized_blocks.is_empty() {
3019 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
3020 Ok(blocks)
3021 } else {
3022 Err(resized_blocks)
3023 }
3024 }
3025
3026 /// Returns true if any of the blocks changed size since the previous frame. This will trigger
3027 /// a restart of rendering for the editor based on the new sizes.
3028 #[allow(clippy::too_many_arguments)]
3029 fn layout_blocks(
3030 &self,
3031 blocks: &mut Vec<BlockLayout>,
3032 block_starts: &mut HashSet<DisplayRow>,
3033 hitbox: &Hitbox,
3034 line_height: Pixels,
3035 scroll_pixel_position: gpui::Point<Pixels>,
3036 window: &mut Window,
3037 cx: &mut App,
3038 ) {
3039 for block in blocks {
3040 let mut origin = if let Some(row) = block.row {
3041 block_starts.insert(row);
3042 hitbox.origin
3043 + point(
3044 Pixels::ZERO,
3045 row.as_f32() * line_height - scroll_pixel_position.y,
3046 )
3047 } else {
3048 // Position the block outside the visible area
3049 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
3050 };
3051
3052 if !matches!(block.style, BlockStyle::Sticky) {
3053 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
3054 }
3055
3056 let focus_handle =
3057 block
3058 .element
3059 .prepaint_as_root(origin, block.available_space, window, cx);
3060
3061 if let Some(focus_handle) = focus_handle {
3062 self.editor.update(cx, |editor, _cx| {
3063 editor.set_focused_block(FocusedBlock {
3064 id: block.id,
3065 focus_handle: focus_handle.downgrade(),
3066 });
3067 });
3068 }
3069 }
3070 }
3071
3072 #[allow(clippy::too_many_arguments)]
3073 fn layout_sticky_buffer_header(
3074 &self,
3075 StickyHeaderExcerpt {
3076 excerpt,
3077 next_excerpt_controls_present,
3078 next_buffer_row,
3079 }: StickyHeaderExcerpt<'_>,
3080 scroll_position: f32,
3081 line_height: Pixels,
3082 snapshot: &EditorSnapshot,
3083 hitbox: &Hitbox,
3084 selected_buffer_ids: &Vec<BufferId>,
3085 window: &mut Window,
3086 cx: &mut App,
3087 ) -> AnyElement {
3088 let jump_data = header_jump_data(
3089 snapshot,
3090 DisplayRow(scroll_position as u32),
3091 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3092 excerpt,
3093 );
3094
3095 let editor_bg_color = cx.theme().colors().editor_background;
3096
3097 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3098
3099 let mut header = v_flex()
3100 .relative()
3101 .child(
3102 div()
3103 .w(hitbox.bounds.size.width)
3104 .h(FILE_HEADER_HEIGHT as f32 * line_height)
3105 .bg(linear_gradient(
3106 0.,
3107 linear_color_stop(editor_bg_color.opacity(0.), 0.),
3108 linear_color_stop(editor_bg_color, 0.6),
3109 ))
3110 .absolute()
3111 .top_0(),
3112 )
3113 .child(
3114 self.render_buffer_header(excerpt, false, selected, jump_data, window, cx)
3115 .into_any_element(),
3116 )
3117 .into_any_element();
3118
3119 let mut origin = hitbox.origin;
3120
3121 if let Some(next_buffer_row) = next_buffer_row {
3122 // Push up the sticky header when the excerpt is getting close to the top of the viewport
3123
3124 let mut max_row = next_buffer_row - FILE_HEADER_HEIGHT * 2;
3125
3126 if next_excerpt_controls_present {
3127 max_row -= MULTI_BUFFER_EXCERPT_HEADER_HEIGHT;
3128 }
3129
3130 let offset = scroll_position - max_row as f32;
3131
3132 if offset > 0.0 {
3133 origin.y -= Pixels(offset) * line_height;
3134 }
3135 }
3136
3137 let size = size(
3138 AvailableSpace::Definite(hitbox.size.width),
3139 AvailableSpace::MinContent,
3140 );
3141
3142 header.prepaint_as_root(origin, size, window, cx);
3143
3144 header
3145 }
3146
3147 #[allow(clippy::too_many_arguments)]
3148 fn layout_cursor_popovers(
3149 &self,
3150 line_height: Pixels,
3151 text_hitbox: &Hitbox,
3152 content_origin: gpui::Point<Pixels>,
3153 start_row: DisplayRow,
3154 scroll_pixel_position: gpui::Point<Pixels>,
3155 line_layouts: &[LineWithInvisibles],
3156 cursor: DisplayPoint,
3157 cursor_point: Point,
3158 style: &EditorStyle,
3159 window: &mut Window,
3160 cx: &mut App,
3161 ) {
3162 let mut min_menu_height = Pixels::ZERO;
3163 let mut max_menu_height = Pixels::ZERO;
3164 let mut height_above_menu = Pixels::ZERO;
3165 let height_below_menu = Pixels::ZERO;
3166 let mut edit_prediction_popover_visible = false;
3167 let mut context_menu_visible = false;
3168
3169 {
3170 let editor = self.editor.read(cx);
3171 if editor
3172 .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3173 {
3174 height_above_menu +=
3175 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3176 edit_prediction_popover_visible = true;
3177 }
3178
3179 if editor.context_menu_visible() {
3180 if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3181 min_menu_height += line_height * 3. + POPOVER_Y_PADDING;
3182 max_menu_height += line_height * 12. + POPOVER_Y_PADDING;
3183 context_menu_visible = true;
3184 }
3185 }
3186 }
3187
3188 let visible = edit_prediction_popover_visible || context_menu_visible;
3189 if !visible {
3190 return;
3191 }
3192
3193 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3194 let target_position = content_origin
3195 + gpui::Point {
3196 x: cmp::max(
3197 px(0.),
3198 cursor_row_layout.x_for_index(cursor.column() as usize)
3199 - scroll_pixel_position.x,
3200 ),
3201 y: cmp::max(
3202 px(0.),
3203 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3204 ),
3205 };
3206
3207 let viewport_bounds =
3208 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3209 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3210 ..Default::default()
3211 });
3212
3213 let min_height = height_above_menu + min_menu_height + height_below_menu;
3214 let max_height = height_above_menu + max_menu_height + height_below_menu;
3215 let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3216 target_position,
3217 line_height,
3218 min_height,
3219 max_height,
3220 text_hitbox,
3221 viewport_bounds,
3222 window,
3223 cx,
3224 |height, max_width_for_stable_x, y_flipped, window, cx| {
3225 // First layout the menu to get its size - others can be at least this wide.
3226 let context_menu = if context_menu_visible {
3227 let menu_height = if y_flipped {
3228 height - height_below_menu
3229 } else {
3230 height - height_above_menu
3231 };
3232 let mut element = self
3233 .render_context_menu(line_height, menu_height, y_flipped, window, cx)
3234 .expect("Visible context menu should always render.");
3235 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3236 Some((CursorPopoverType::CodeContextMenu, element, size))
3237 } else {
3238 None
3239 };
3240 let min_width = context_menu
3241 .as_ref()
3242 .map_or(px(0.), |(_, _, size)| size.width);
3243 let max_width = max_width_for_stable_x.max(
3244 context_menu
3245 .as_ref()
3246 .map_or(px(0.), |(_, _, size)| size.width),
3247 );
3248
3249 let edit_prediction = if edit_prediction_popover_visible {
3250 self.editor.update(cx, move |editor, cx| {
3251 let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3252 let mut element = editor.render_edit_prediction_cursor_popover(
3253 min_width,
3254 max_width,
3255 cursor_point,
3256 style,
3257 accept_binding.keystroke()?,
3258 window,
3259 cx,
3260 )?;
3261 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3262 Some((CursorPopoverType::EditPrediction, element, size))
3263 })
3264 } else {
3265 None
3266 };
3267 vec![edit_prediction, context_menu]
3268 .into_iter()
3269 .flatten()
3270 .collect::<Vec<_>>()
3271 },
3272 ) else {
3273 return;
3274 };
3275
3276 let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3277 .iter()
3278 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3279 else {
3280 return;
3281 };
3282 let last_ix = laid_out_popovers.len() - 1;
3283 let menu_is_last = menu_ix == last_ix;
3284 let first_popover_bounds = laid_out_popovers[0].1;
3285 let last_popover_bounds = laid_out_popovers[last_ix].1;
3286
3287 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3288 // right, and otherwise it goes below or to the right.
3289 let mut target_bounds = Bounds::from_corners(
3290 first_popover_bounds.origin,
3291 last_popover_bounds.bottom_right(),
3292 );
3293 target_bounds.size.width = menu_bounds.size.width;
3294
3295 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3296 // based on this is preferred for layout stability.
3297 let mut max_target_bounds = target_bounds;
3298 max_target_bounds.size.height = max_height;
3299 if y_flipped {
3300 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3301 }
3302
3303 // Add spacing around `target_bounds` and `max_target_bounds`.
3304 let mut extend_amount = Edges::all(MENU_GAP);
3305 if y_flipped {
3306 extend_amount.bottom = line_height;
3307 } else {
3308 extend_amount.top = line_height;
3309 }
3310 let target_bounds = target_bounds.extend(extend_amount);
3311 let max_target_bounds = max_target_bounds.extend(extend_amount);
3312
3313 let must_place_above_or_below =
3314 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3315 laid_out_popovers[menu_ix + 1..]
3316 .iter()
3317 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3318 } else {
3319 false
3320 };
3321
3322 self.layout_context_menu_aside(
3323 y_flipped,
3324 *menu_bounds,
3325 target_bounds,
3326 max_target_bounds,
3327 max_menu_height,
3328 must_place_above_or_below,
3329 text_hitbox,
3330 viewport_bounds,
3331 window,
3332 cx,
3333 );
3334 }
3335
3336 #[allow(clippy::too_many_arguments)]
3337 fn layout_gutter_menu(
3338 &self,
3339 line_height: Pixels,
3340 text_hitbox: &Hitbox,
3341 content_origin: gpui::Point<Pixels>,
3342 scroll_pixel_position: gpui::Point<Pixels>,
3343 gutter_overshoot: Pixels,
3344 window: &mut Window,
3345 cx: &mut App,
3346 ) {
3347 let editor = self.editor.read(cx);
3348 if !editor.context_menu_visible() {
3349 return;
3350 }
3351 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3352 editor.context_menu_origin()
3353 else {
3354 return;
3355 };
3356 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3357 // indicator than just a plain first column of the text field.
3358 let target_position = content_origin
3359 + gpui::Point {
3360 x: -gutter_overshoot,
3361 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3362 };
3363 let min_height = line_height * 3. + POPOVER_Y_PADDING;
3364 let max_height = line_height * 12. + POPOVER_Y_PADDING;
3365 let viewport_bounds =
3366 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3367 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3368 ..Default::default()
3369 });
3370 self.layout_popovers_above_or_below_line(
3371 target_position,
3372 line_height,
3373 min_height,
3374 max_height,
3375 text_hitbox,
3376 viewport_bounds,
3377 window,
3378 cx,
3379 move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3380 let mut element = self
3381 .render_context_menu(line_height, height, y_flipped, window, cx)
3382 .expect("Visible context menu should always render.");
3383 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3384 vec![(CursorPopoverType::CodeContextMenu, element, size)]
3385 },
3386 );
3387 }
3388
3389 #[allow(clippy::too_many_arguments)]
3390 fn layout_popovers_above_or_below_line(
3391 &self,
3392 target_position: gpui::Point<Pixels>,
3393 line_height: Pixels,
3394 min_height: Pixels,
3395 max_height: Pixels,
3396 text_hitbox: &Hitbox,
3397 viewport_bounds: Bounds<Pixels>,
3398 window: &mut Window,
3399 cx: &mut App,
3400 make_sized_popovers: impl FnOnce(
3401 Pixels,
3402 Pixels,
3403 bool,
3404 &mut Window,
3405 &mut App,
3406 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3407 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3408 // If the max height won't fit below and there is more space above, put it above the line.
3409 let bottom_y_when_flipped = target_position.y - line_height;
3410 let available_above = bottom_y_when_flipped - text_hitbox.top();
3411 let available_below = text_hitbox.bottom() - target_position.y;
3412 let y_overflows_below = max_height > available_below;
3413 let mut y_flipped = y_overflows_below && available_above > available_below;
3414 let mut height = cmp::min(
3415 max_height,
3416 if y_flipped {
3417 available_above
3418 } else {
3419 available_below
3420 },
3421 );
3422
3423 // If the min height doesn't fit within text bounds, instead fit within the window.
3424 if height < min_height {
3425 let available_above = bottom_y_when_flipped;
3426 let available_below = viewport_bounds.bottom() - target_position.y;
3427 if available_below > min_height {
3428 y_flipped = false;
3429 height = min_height;
3430 } else if available_above > min_height {
3431 y_flipped = true;
3432 height = min_height;
3433 } else if available_above > available_below {
3434 y_flipped = true;
3435 height = available_above;
3436 } else {
3437 y_flipped = false;
3438 height = available_below;
3439 }
3440 }
3441
3442 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3443
3444 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3445 // for very narrow windows.
3446 let popovers = make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3447 if popovers.is_empty() {
3448 return None;
3449 }
3450
3451 let max_width = popovers
3452 .iter()
3453 .map(|(_, _, size)| size.width)
3454 .max()
3455 .unwrap_or_default();
3456
3457 let mut current_position = gpui::Point {
3458 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3459 // overflow. Include space for the scrollbar.
3460 x: target_position
3461 .x
3462 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3463 y: if y_flipped {
3464 bottom_y_when_flipped
3465 } else {
3466 target_position.y
3467 },
3468 };
3469
3470 let mut laid_out_popovers = popovers
3471 .into_iter()
3472 .map(|(popover_type, element, size)| {
3473 if y_flipped {
3474 current_position.y -= size.height;
3475 }
3476 let position = current_position;
3477 window.defer_draw(element, current_position, 1);
3478 if !y_flipped {
3479 current_position.y += size.height + MENU_GAP;
3480 } else {
3481 current_position.y -= MENU_GAP;
3482 }
3483 (popover_type, Bounds::new(position, size))
3484 })
3485 .collect::<Vec<_>>();
3486
3487 if y_flipped {
3488 laid_out_popovers.reverse();
3489 }
3490
3491 Some((laid_out_popovers, y_flipped))
3492 }
3493
3494 #[allow(clippy::too_many_arguments)]
3495 fn layout_context_menu_aside(
3496 &self,
3497 y_flipped: bool,
3498 menu_bounds: Bounds<Pixels>,
3499 target_bounds: Bounds<Pixels>,
3500 max_target_bounds: Bounds<Pixels>,
3501 max_height: Pixels,
3502 must_place_above_or_below: bool,
3503 text_hitbox: &Hitbox,
3504 viewport_bounds: Bounds<Pixels>,
3505 window: &mut Window,
3506 cx: &mut App,
3507 ) {
3508 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3509 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3510 && !must_place_above_or_below
3511 {
3512 let max_width = cmp::min(
3513 available_within_viewport.right - px(1.),
3514 MENU_ASIDE_MAX_WIDTH,
3515 );
3516 let Some(mut aside) =
3517 self.render_context_menu_aside(size(max_width, max_height - POPOVER_Y_PADDING), cx)
3518 else {
3519 return;
3520 };
3521 aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3522 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3523 Some((aside, right_position))
3524 } else {
3525 let max_size = size(
3526 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3527 // won't be needed here.
3528 cmp::min(
3529 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3530 viewport_bounds.right(),
3531 ),
3532 cmp::min(
3533 max_height,
3534 cmp::max(
3535 available_within_viewport.top,
3536 available_within_viewport.bottom,
3537 ),
3538 ) - POPOVER_Y_PADDING,
3539 );
3540 let Some(mut aside) = self.render_context_menu_aside(max_size, cx) else {
3541 return;
3542 };
3543 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3544
3545 let top_position = point(
3546 menu_bounds.origin.x,
3547 target_bounds.top() - actual_size.height,
3548 );
3549 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3550
3551 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3552 // Prefer to fit on the same side of the line as the menu, then on the other side of
3553 // the line.
3554 if !y_flipped && wanted.height < available.bottom {
3555 Some(bottom_position)
3556 } else if !y_flipped && wanted.height < available.top {
3557 Some(top_position)
3558 } else if y_flipped && wanted.height < available.top {
3559 Some(top_position)
3560 } else if y_flipped && wanted.height < available.bottom {
3561 Some(bottom_position)
3562 } else {
3563 None
3564 }
3565 };
3566
3567 // Prefer choosing a direction using max sizes rather than actual size for stability.
3568 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3569 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3570 let aside_position = fit_within(available_within_text, wanted)
3571 // Fallback: fit max size in window.
3572 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3573 // Fallback: fit actual size in window.
3574 .or_else(|| fit_within(available_within_viewport, actual_size));
3575
3576 aside_position.map(|position| (aside, position))
3577 };
3578
3579 // Skip drawing if it doesn't fit anywhere.
3580 if let Some((aside, position)) = positioned_aside {
3581 window.defer_draw(aside, position, 1);
3582 }
3583 }
3584
3585 fn render_context_menu(
3586 &self,
3587 line_height: Pixels,
3588 height: Pixels,
3589 y_flipped: bool,
3590 window: &mut Window,
3591 cx: &mut App,
3592 ) -> Option<AnyElement> {
3593 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3594 self.editor.update(cx, |editor, cx| {
3595 editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3596 })
3597 }
3598
3599 fn render_context_menu_aside(
3600 &self,
3601 max_size: Size<Pixels>,
3602
3603 cx: &mut App,
3604 ) -> Option<AnyElement> {
3605 if max_size.width < px(100.) || max_size.height < px(12.) {
3606 None
3607 } else {
3608 self.editor.update(cx, |editor, cx| {
3609 editor.render_context_menu_aside(&self.style, max_size, cx)
3610 })
3611 }
3612 }
3613
3614 #[allow(clippy::too_many_arguments)]
3615 fn layout_edit_prediction_popover(
3616 &self,
3617 text_bounds: &Bounds<Pixels>,
3618 content_origin: gpui::Point<Pixels>,
3619 editor_snapshot: &EditorSnapshot,
3620 visible_row_range: Range<DisplayRow>,
3621 scroll_top: f32,
3622 scroll_bottom: f32,
3623 line_layouts: &[LineWithInvisibles],
3624 line_height: Pixels,
3625 scroll_pixel_position: gpui::Point<Pixels>,
3626 newest_selection_head: Option<DisplayPoint>,
3627 editor_width: Pixels,
3628 style: &EditorStyle,
3629 window: &mut Window,
3630 cx: &mut App,
3631 ) -> Option<AnyElement> {
3632 const PADDING_X: Pixels = Pixels(24.);
3633 const PADDING_Y: Pixels = Pixels(2.);
3634
3635 let editor = self.editor.read(cx);
3636 let active_inline_completion = editor.active_inline_completion.as_ref()?;
3637
3638 if editor.edit_prediction_visible_in_cursor_popover(true) {
3639 return None;
3640 }
3641
3642 // Adjust text origin for horizontal scrolling (in some cases here)
3643 let start_point = content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
3644
3645 // Clamp left offset after extreme scrollings
3646 let clamp_start = |point: gpui::Point<Pixels>| gpui::Point {
3647 x: point.x.max(content_origin.x),
3648 y: point.y,
3649 };
3650
3651 match &active_inline_completion.completion {
3652 InlineCompletion::Move { target, .. } => {
3653 let target_display_point = target.to_display_point(editor_snapshot);
3654
3655 if editor.edit_prediction_requires_modifier() {
3656 if !editor.edit_prediction_preview_is_active() {
3657 return None;
3658 }
3659
3660 if target_display_point.row() < visible_row_range.start {
3661 let mut element = editor
3662 .render_edit_prediction_line_popover(
3663 "Scroll",
3664 Some(IconName::ArrowUp),
3665 window,
3666 cx,
3667 )?
3668 .into_any();
3669
3670 element.layout_as_root(AvailableSpace::min_size(), window, cx);
3671
3672 let cursor = newest_selection_head?;
3673 let cursor_row_layout = line_layouts
3674 .get(cursor.row().minus(visible_row_range.start) as usize)?;
3675 let cursor_column = cursor.column() as usize;
3676
3677 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
3678
3679 const PADDING_Y: Pixels = px(12.);
3680
3681 let origin = start_point + point(cursor_character_x, PADDING_Y);
3682
3683 element.prepaint_at(origin, window, cx);
3684 return Some(element);
3685 } else if target_display_point.row() >= visible_row_range.end {
3686 let mut element = editor
3687 .render_edit_prediction_line_popover(
3688 "Scroll",
3689 Some(IconName::ArrowDown),
3690 window,
3691 cx,
3692 )?
3693 .into_any();
3694
3695 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3696
3697 let cursor = newest_selection_head?;
3698 let cursor_row_layout = line_layouts
3699 .get(cursor.row().minus(visible_row_range.start) as usize)?;
3700 let cursor_column = cursor.column() as usize;
3701
3702 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
3703 const PADDING_Y: Pixels = px(12.);
3704
3705 let origin = start_point
3706 + point(
3707 cursor_character_x,
3708 text_bounds.size.height - size.height - PADDING_Y,
3709 );
3710
3711 element.prepaint_at(origin, window, cx);
3712 return Some(element);
3713 } else {
3714 const POLE_WIDTH: Pixels = px(2.);
3715
3716 let mut element = v_flex()
3717 .child(
3718 editor
3719 .render_edit_prediction_line_popover("Jump", None, window, cx)?
3720 .rounded_br(px(0.))
3721 .rounded_tr(px(0.))
3722 .border_r_2(),
3723 )
3724 .child(
3725 div()
3726 .w(POLE_WIDTH)
3727 .bg(cx.theme().colors().text_accent.opacity(0.8))
3728 .h(line_height),
3729 )
3730 .items_end()
3731 .into_any();
3732
3733 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3734
3735 let line_layout =
3736 line_layouts
3737 .get(target_display_point.row().minus(visible_row_range.start)
3738 as usize)?;
3739 let target_column = target_display_point.column() as usize;
3740
3741 let target_x = line_layout.x_for_index(target_column);
3742 let target_y = (target_display_point.row().as_f32() * line_height)
3743 - scroll_pixel_position.y;
3744
3745 let origin = clamp_start(
3746 start_point + point(target_x, target_y)
3747 - point(size.width - POLE_WIDTH, size.height - line_height),
3748 );
3749
3750 element.prepaint_at(origin, window, cx);
3751
3752 return Some(element);
3753 }
3754 }
3755
3756 if target_display_point.row().as_f32() < scroll_top {
3757 let mut element = editor
3758 .render_edit_prediction_line_popover(
3759 "Jump to Edit",
3760 Some(IconName::ArrowUp),
3761 window,
3762 cx,
3763 )?
3764 .into_any();
3765
3766 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3767 let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
3768
3769 element.prepaint_at(text_bounds.origin + offset, window, cx);
3770 Some(element)
3771 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
3772 let mut element = editor
3773 .render_edit_prediction_line_popover(
3774 "Jump to Edit",
3775 Some(IconName::ArrowDown),
3776 window,
3777 cx,
3778 )?
3779 .into_any();
3780
3781 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3782 let offset = point(
3783 (text_bounds.size.width - size.width) / 2.,
3784 text_bounds.size.height - size.height - PADDING_Y,
3785 );
3786
3787 element.prepaint_at(text_bounds.origin + offset, window, cx);
3788 Some(element)
3789 } else {
3790 let mut element = editor
3791 .render_edit_prediction_line_popover("Jump to Edit", None, window, cx)?
3792 .into_any();
3793 let target_line_end = DisplayPoint::new(
3794 target_display_point.row(),
3795 editor_snapshot.line_len(target_display_point.row()),
3796 );
3797 let origin = self.editor.update(cx, |editor, _cx| {
3798 editor.display_to_pixel_point(target_line_end, editor_snapshot, window)
3799 })?;
3800
3801 element.prepaint_as_root(
3802 clamp_start(start_point + origin + point(PADDING_X, px(0.))),
3803 AvailableSpace::min_size(),
3804 window,
3805 cx,
3806 );
3807 Some(element)
3808 }
3809 }
3810 InlineCompletion::Edit {
3811 edits,
3812 edit_preview,
3813 display_mode,
3814 snapshot,
3815 } => {
3816 if self.editor.read(cx).has_visible_completions_menu() {
3817 return None;
3818 }
3819
3820 let edit_start = edits
3821 .first()
3822 .unwrap()
3823 .0
3824 .start
3825 .to_display_point(editor_snapshot);
3826 let edit_end = edits
3827 .last()
3828 .unwrap()
3829 .0
3830 .end
3831 .to_display_point(editor_snapshot);
3832
3833 let is_visible = visible_row_range.contains(&edit_start.row())
3834 || visible_row_range.contains(&edit_end.row());
3835 if !is_visible {
3836 return None;
3837 }
3838
3839 match display_mode {
3840 EditDisplayMode::TabAccept => {
3841 let range = &edits.first()?.0;
3842 let target_display_point = range.end.to_display_point(editor_snapshot);
3843
3844 let target_line_end = DisplayPoint::new(
3845 target_display_point.row(),
3846 editor_snapshot.line_len(target_display_point.row()),
3847 );
3848 let (mut element, origin) = self.editor.update(cx, |editor, cx| {
3849 Some((
3850 editor
3851 .render_edit_prediction_line_popover(
3852 "Accept", None, window, cx,
3853 )?
3854 .into_any(),
3855 editor.display_to_pixel_point(
3856 target_line_end,
3857 editor_snapshot,
3858 window,
3859 )?,
3860 ))
3861 })?;
3862
3863 element.prepaint_as_root(
3864 clamp_start(start_point + origin + point(PADDING_X, px(0.))),
3865 AvailableSpace::min_size(),
3866 window,
3867 cx,
3868 );
3869 return Some(element);
3870 }
3871 EditDisplayMode::Inline => return None,
3872 EditDisplayMode::DiffPopover => {}
3873 }
3874
3875 let highlighted_edits = crate::inline_completion_edit_text(
3876 &snapshot,
3877 edits,
3878 edit_preview.as_ref()?,
3879 false,
3880 cx,
3881 );
3882
3883 let styled_text = highlighted_edits.to_styled_text(&style.text);
3884 let line_count = highlighted_edits.text.lines().count();
3885
3886 const BORDER_WIDTH: Pixels = px(1.);
3887
3888 let mut element = h_flex()
3889 .items_start()
3890 .child(
3891 h_flex()
3892 .bg(cx.theme().colors().editor_background)
3893 .border(BORDER_WIDTH)
3894 .shadow_sm()
3895 .border_color(cx.theme().colors().border)
3896 .rounded_l_lg()
3897 .when(line_count > 1, |el| el.rounded_br_lg())
3898 .pr_1()
3899 .child(styled_text),
3900 )
3901 .child(
3902 h_flex()
3903 .h(line_height + BORDER_WIDTH * px(2.))
3904 .px_1p5()
3905 .gap_1()
3906 // Workaround: For some reason, there's a gap if we don't do this
3907 .ml(-BORDER_WIDTH)
3908 .shadow(smallvec![gpui::BoxShadow {
3909 color: gpui::black().opacity(0.05),
3910 offset: point(px(1.), px(1.)),
3911 blur_radius: px(2.),
3912 spread_radius: px(0.),
3913 }])
3914 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
3915 .border(BORDER_WIDTH)
3916 .border_color(cx.theme().colors().border)
3917 .rounded_r_lg()
3918 .children(editor.render_edit_prediction_accept_keybind(window, cx)),
3919 )
3920 .into_any();
3921
3922 let longest_row =
3923 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
3924 let longest_line_width = if visible_row_range.contains(&longest_row) {
3925 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
3926 } else {
3927 layout_line(
3928 longest_row,
3929 editor_snapshot,
3930 style,
3931 editor_width,
3932 |_| false,
3933 window,
3934 cx,
3935 )
3936 .width
3937 };
3938
3939 let viewport_bounds = Bounds::new(Default::default(), window.viewport_size())
3940 .extend(Edges {
3941 right: -Self::SCROLLBAR_WIDTH,
3942 ..Default::default()
3943 });
3944
3945 let x_after_longest =
3946 text_bounds.origin.x + longest_line_width + PADDING_X - scroll_pixel_position.x;
3947
3948 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3949
3950 // Fully visible if it can be displayed within the window (allow overlapping other
3951 // panes). However, this is only allowed if the popover starts within text_bounds.
3952 let can_position_to_the_right = x_after_longest < text_bounds.right()
3953 && x_after_longest + element_bounds.width < viewport_bounds.right();
3954
3955 let mut origin = if can_position_to_the_right {
3956 point(
3957 x_after_longest,
3958 text_bounds.origin.y + edit_start.row().as_f32() * line_height
3959 - scroll_pixel_position.y,
3960 )
3961 } else {
3962 let cursor_row = newest_selection_head.map(|head| head.row());
3963 let above_edit = edit_start
3964 .row()
3965 .0
3966 .checked_sub(line_count as u32)
3967 .map(DisplayRow);
3968 let below_edit = Some(edit_end.row() + 1);
3969 let above_cursor = cursor_row
3970 .and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
3971 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
3972
3973 // Place the edit popover adjacent to the edit if there is a location
3974 // available that is onscreen and does not obscure the cursor. Otherwise,
3975 // place it adjacent to the cursor.
3976 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
3977 .into_iter()
3978 .flatten()
3979 .find(|&start_row| {
3980 let end_row = start_row + line_count as u32;
3981 visible_row_range.contains(&start_row)
3982 && visible_row_range.contains(&end_row)
3983 && cursor_row.map_or(true, |cursor_row| {
3984 !((start_row..end_row).contains(&cursor_row))
3985 })
3986 })?;
3987
3988 content_origin
3989 + point(
3990 -scroll_pixel_position.x,
3991 row_target.as_f32() * line_height - scroll_pixel_position.y,
3992 )
3993 };
3994
3995 origin.x -= BORDER_WIDTH;
3996
3997 window.defer_draw(element, origin, 1);
3998
3999 // Do not return an element, since it will already be drawn due to defer_draw.
4000 None
4001 }
4002 }
4003 }
4004
4005 fn layout_mouse_context_menu(
4006 &self,
4007 editor_snapshot: &EditorSnapshot,
4008 visible_range: Range<DisplayRow>,
4009 content_origin: gpui::Point<Pixels>,
4010 window: &mut Window,
4011 cx: &mut App,
4012 ) -> Option<AnyElement> {
4013 let position = self.editor.update(cx, |editor, _cx| {
4014 let visible_start_point = editor.display_to_pixel_point(
4015 DisplayPoint::new(visible_range.start, 0),
4016 editor_snapshot,
4017 window,
4018 )?;
4019 let visible_end_point = editor.display_to_pixel_point(
4020 DisplayPoint::new(visible_range.end, 0),
4021 editor_snapshot,
4022 window,
4023 )?;
4024
4025 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4026 let (source_display_point, position) = match mouse_context_menu.position {
4027 MenuPosition::PinnedToScreen(point) => (None, point),
4028 MenuPosition::PinnedToEditor { source, offset } => {
4029 let source_display_point = source.to_display_point(editor_snapshot);
4030 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
4031 let position = content_origin + source_point + offset;
4032 (Some(source_display_point), position)
4033 }
4034 };
4035
4036 let source_included = source_display_point.map_or(true, |source_display_point| {
4037 visible_range
4038 .to_inclusive()
4039 .contains(&source_display_point.row())
4040 });
4041 let position_included =
4042 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
4043 if !source_included && !position_included {
4044 None
4045 } else {
4046 Some(position)
4047 }
4048 })?;
4049
4050 let mut element = self.editor.update(cx, |editor, _| {
4051 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4052 let context_menu = mouse_context_menu.context_menu.clone();
4053
4054 Some(
4055 deferred(
4056 anchored()
4057 .position(position)
4058 .child(context_menu)
4059 .anchor(Corner::TopLeft)
4060 .snap_to_window_with_margin(px(8.)),
4061 )
4062 .with_priority(1)
4063 .into_any(),
4064 )
4065 })?;
4066
4067 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
4068 Some(element)
4069 }
4070
4071 #[allow(clippy::too_many_arguments)]
4072 fn layout_hover_popovers(
4073 &self,
4074 snapshot: &EditorSnapshot,
4075 hitbox: &Hitbox,
4076 text_hitbox: &Hitbox,
4077 visible_display_row_range: Range<DisplayRow>,
4078 content_origin: gpui::Point<Pixels>,
4079 scroll_pixel_position: gpui::Point<Pixels>,
4080 line_layouts: &[LineWithInvisibles],
4081 line_height: Pixels,
4082 em_width: Pixels,
4083 window: &mut Window,
4084 cx: &mut App,
4085 ) {
4086 struct MeasuredHoverPopover {
4087 element: AnyElement,
4088 size: Size<Pixels>,
4089 horizontal_offset: Pixels,
4090 }
4091
4092 let max_size = size(
4093 (120. * em_width) // Default size
4094 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4095 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4096 (16. * line_height) // Default size
4097 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4098 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4099 );
4100
4101 let hover_popovers = self.editor.update(cx, |editor, cx| {
4102 editor
4103 .hover_state
4104 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
4105 });
4106 let Some((position, hover_popovers)) = hover_popovers else {
4107 return;
4108 };
4109
4110 // This is safe because we check on layout whether the required row is available
4111 let hovered_row_layout =
4112 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
4113
4114 // Compute Hovered Point
4115 let x =
4116 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
4117 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
4118 let hovered_point = content_origin + point(x, y);
4119
4120 let mut overall_height = Pixels::ZERO;
4121 let mut measured_hover_popovers = Vec::new();
4122 for mut hover_popover in hover_popovers {
4123 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
4124 let horizontal_offset =
4125 (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
4126
4127 overall_height += HOVER_POPOVER_GAP + size.height;
4128
4129 measured_hover_popovers.push(MeasuredHoverPopover {
4130 element: hover_popover,
4131 size,
4132 horizontal_offset,
4133 });
4134 }
4135 overall_height += HOVER_POPOVER_GAP;
4136
4137 fn draw_occluder(
4138 width: Pixels,
4139 origin: gpui::Point<Pixels>,
4140 window: &mut Window,
4141 cx: &mut App,
4142 ) {
4143 let mut occlusion = div()
4144 .size_full()
4145 .occlude()
4146 .on_mouse_move(|_, _, cx| cx.stop_propagation())
4147 .into_any_element();
4148 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4149 window.defer_draw(occlusion, origin, 2);
4150 }
4151
4152 if hovered_point.y > overall_height {
4153 // There is enough space above. Render popovers above the hovered point
4154 let mut current_y = hovered_point.y;
4155 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4156 let size = popover.size;
4157 let popover_origin = point(
4158 hovered_point.x + popover.horizontal_offset,
4159 current_y - size.height,
4160 );
4161
4162 window.defer_draw(popover.element, popover_origin, 2);
4163 if position != itertools::Position::Last {
4164 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4165 draw_occluder(size.width, origin, window, cx);
4166 }
4167
4168 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4169 }
4170 } else {
4171 // There is not enough space above. Render popovers below the hovered point
4172 let mut current_y = hovered_point.y + line_height;
4173 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4174 let size = popover.size;
4175 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4176
4177 window.defer_draw(popover.element, popover_origin, 2);
4178 if position != itertools::Position::Last {
4179 let origin = point(popover_origin.x, popover_origin.y + size.height);
4180 draw_occluder(size.width, origin, window, cx);
4181 }
4182
4183 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4184 }
4185 }
4186 }
4187
4188 #[allow(clippy::too_many_arguments)]
4189 fn layout_diff_hunk_controls(
4190 &self,
4191 row_range: Range<DisplayRow>,
4192 row_infos: &[RowInfo],
4193 text_hitbox: &Hitbox,
4194 position_map: &PositionMap,
4195 newest_cursor_position: Option<DisplayPoint>,
4196 line_height: Pixels,
4197 scroll_pixel_position: gpui::Point<Pixels>,
4198 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4199 editor: Entity<Editor>,
4200 window: &mut Window,
4201 cx: &mut App,
4202 ) -> Vec<AnyElement> {
4203 let point_for_position = position_map.point_for_position(window.mouse_position());
4204
4205 let mut controls = vec![];
4206
4207 let active_positions = [
4208 Some(point_for_position.previous_valid),
4209 newest_cursor_position,
4210 ];
4211
4212 let mut display_hunks = display_hunks.iter().peekable();
4213 while let Some((hunk, _)) = display_hunks.next() {
4214 if let DisplayDiffHunk::Unfolded {
4215 display_row_range,
4216 multi_buffer_range,
4217 status,
4218 is_primary: true,
4219 ..
4220 } = &hunk
4221 {
4222 let mut display_row_range = display_row_range.clone();
4223 if let Some((
4224 DisplayDiffHunk::Unfolded {
4225 display_row_range: secondary_display_row_range,
4226 is_primary: false,
4227 ..
4228 },
4229 _,
4230 )) = display_hunks.peek()
4231 {
4232 display_row_range.end = secondary_display_row_range.end;
4233 }
4234
4235 if display_row_range.start < row_range.start
4236 || display_row_range.start >= row_range.end
4237 {
4238 continue;
4239 }
4240 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4241 if row_infos[row_ix].diff_status.is_none() {
4242 continue;
4243 }
4244 if matches!(
4245 row_infos[row_ix].diff_status,
4246 Some(DiffHunkStatus::Added(_))
4247 ) && !matches!(*status, DiffHunkStatus::Added(_))
4248 {
4249 continue;
4250 }
4251 if active_positions
4252 .iter()
4253 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4254 {
4255 let y = display_row_range.start.as_f32() * line_height
4256 + text_hitbox.bounds.top()
4257 - scroll_pixel_position.y;
4258 let x = text_hitbox.bounds.right()
4259 - rems(6.).to_pixels(window.rem_size())
4260 - px(33.);
4261
4262 let mut element = diff_hunk_controls(
4263 display_row_range.start.0,
4264 multi_buffer_range.clone(),
4265 line_height,
4266 &editor,
4267 window,
4268 cx,
4269 );
4270 element.prepaint_as_root(
4271 gpui::Point::new(x, y),
4272 size(px(100.0), line_height).into(),
4273 window,
4274 cx,
4275 );
4276 controls.push(element);
4277 }
4278 }
4279 }
4280
4281 controls
4282 }
4283
4284 #[allow(clippy::too_many_arguments)]
4285 fn layout_signature_help(
4286 &self,
4287 hitbox: &Hitbox,
4288 content_origin: gpui::Point<Pixels>,
4289 scroll_pixel_position: gpui::Point<Pixels>,
4290 newest_selection_head: Option<DisplayPoint>,
4291 start_row: DisplayRow,
4292 line_layouts: &[LineWithInvisibles],
4293 line_height: Pixels,
4294 em_width: Pixels,
4295 window: &mut Window,
4296 cx: &mut App,
4297 ) {
4298 if !self.editor.focus_handle(cx).is_focused(window) {
4299 return;
4300 }
4301 let Some(newest_selection_head) = newest_selection_head else {
4302 return;
4303 };
4304 let selection_row = newest_selection_head.row();
4305 if selection_row < start_row {
4306 return;
4307 }
4308 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4309 else {
4310 return;
4311 };
4312
4313 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4314 - scroll_pixel_position.x
4315 + content_origin.x;
4316 let start_y =
4317 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4318
4319 let max_size = size(
4320 (120. * em_width) // Default size
4321 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4322 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4323 (16. * line_height) // Default size
4324 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4325 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4326 );
4327
4328 let maybe_element = self.editor.update(cx, |editor, cx| {
4329 if let Some(popover) = editor.signature_help_state.popover_mut() {
4330 let element = popover.render(
4331 &self.style,
4332 max_size,
4333 editor.workspace.as_ref().map(|(w, _)| w.clone()),
4334 cx,
4335 );
4336 Some(element)
4337 } else {
4338 None
4339 }
4340 });
4341 if let Some(mut element) = maybe_element {
4342 let window_size = window.viewport_size();
4343 let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4344 let mut point = point(start_x, start_y - size.height);
4345
4346 // Adjusting to ensure the popover does not overflow in the X-axis direction.
4347 if point.x + size.width >= window_size.width {
4348 point.x = window_size.width - size.width;
4349 }
4350
4351 window.defer_draw(element, point, 1)
4352 }
4353 }
4354
4355 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4356 window.paint_layer(layout.hitbox.bounds, |window| {
4357 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4358 let gutter_bg = cx.theme().colors().editor_gutter_background;
4359 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4360 window.paint_quad(fill(
4361 layout.position_map.text_hitbox.bounds,
4362 self.style.background,
4363 ));
4364
4365 if let EditorMode::Full = layout.mode {
4366 let mut active_rows = layout.active_rows.iter().peekable();
4367 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4368 let mut end_row = start_row.0;
4369 while active_rows
4370 .peek()
4371 .map_or(false, |(active_row, has_selection)| {
4372 active_row.0 == end_row + 1
4373 && *has_selection == contains_non_empty_selection
4374 })
4375 {
4376 active_rows.next().unwrap();
4377 end_row += 1;
4378 }
4379
4380 if !contains_non_empty_selection {
4381 let highlight_h_range =
4382 match layout.position_map.snapshot.current_line_highlight {
4383 CurrentLineHighlight::Gutter => Some(Range {
4384 start: layout.hitbox.left(),
4385 end: layout.gutter_hitbox.right(),
4386 }),
4387 CurrentLineHighlight::Line => Some(Range {
4388 start: layout.position_map.text_hitbox.bounds.left(),
4389 end: layout.position_map.text_hitbox.bounds.right(),
4390 }),
4391 CurrentLineHighlight::All => Some(Range {
4392 start: layout.hitbox.left(),
4393 end: layout.hitbox.right(),
4394 }),
4395 CurrentLineHighlight::None => None,
4396 };
4397 if let Some(range) = highlight_h_range {
4398 let active_line_bg = cx.theme().colors().editor_active_line_background;
4399 let bounds = Bounds {
4400 origin: point(
4401 range.start,
4402 layout.hitbox.origin.y
4403 + (start_row.as_f32() - scroll_top)
4404 * layout.position_map.line_height,
4405 ),
4406 size: size(
4407 range.end - range.start,
4408 layout.position_map.line_height
4409 * (end_row - start_row.0 + 1) as f32,
4410 ),
4411 };
4412 window.paint_quad(fill(bounds, active_line_bg));
4413 }
4414 }
4415 }
4416
4417 let mut paint_highlight =
4418 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4419 let origin = point(
4420 layout.hitbox.origin.x,
4421 layout.hitbox.origin.y
4422 + (highlight_row_start.as_f32() - scroll_top)
4423 * layout.position_map.line_height,
4424 );
4425 let size = size(
4426 layout.hitbox.size.width,
4427 layout.position_map.line_height
4428 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4429 );
4430 window.paint_quad(fill(Bounds { origin, size }, color));
4431 };
4432
4433 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
4434 for (&new_row, &new_background) in &layout.highlighted_rows {
4435 match &mut current_paint {
4436 Some((current_background, current_range)) => {
4437 let current_background = *current_background;
4438 let new_range_started = current_background != new_background
4439 || current_range.end.next_row() != new_row;
4440 if new_range_started {
4441 paint_highlight(
4442 current_range.start,
4443 current_range.end,
4444 current_background,
4445 );
4446 current_paint = Some((new_background, new_row..new_row));
4447 continue;
4448 } else {
4449 current_range.end = current_range.end.next_row();
4450 }
4451 }
4452 None => current_paint = Some((new_background, new_row..new_row)),
4453 };
4454 }
4455 if let Some((color, range)) = current_paint {
4456 paint_highlight(range.start, range.end, color);
4457 }
4458
4459 let scroll_left =
4460 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4461
4462 for (wrap_position, active) in layout.wrap_guides.iter() {
4463 let x = (layout.position_map.text_hitbox.origin.x
4464 + *wrap_position
4465 + layout.position_map.em_width / 2.)
4466 - scroll_left;
4467
4468 let show_scrollbars = {
4469 let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4470
4471 scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4472 || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4473 };
4474
4475 if x < layout.position_map.text_hitbox.origin.x
4476 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4477 {
4478 continue;
4479 }
4480
4481 let color = if *active {
4482 cx.theme().colors().editor_active_wrap_guide
4483 } else {
4484 cx.theme().colors().editor_wrap_guide
4485 };
4486 window.paint_quad(fill(
4487 Bounds {
4488 origin: point(x, layout.position_map.text_hitbox.origin.y),
4489 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4490 },
4491 color,
4492 ));
4493 }
4494 }
4495 })
4496 }
4497
4498 fn paint_indent_guides(
4499 &mut self,
4500 layout: &mut EditorLayout,
4501 window: &mut Window,
4502 cx: &mut App,
4503 ) {
4504 let Some(indent_guides) = &layout.indent_guides else {
4505 return;
4506 };
4507
4508 let faded_color = |color: Hsla, alpha: f32| {
4509 let mut faded = color;
4510 faded.a = alpha;
4511 faded
4512 };
4513
4514 for indent_guide in indent_guides {
4515 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4516 let settings = indent_guide.settings;
4517
4518 // TODO fixed for now, expose them through themes later
4519 const INDENT_AWARE_ALPHA: f32 = 0.2;
4520 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4521 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4522 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4523
4524 let line_color = match (settings.coloring, indent_guide.active) {
4525 (IndentGuideColoring::Disabled, _) => None,
4526 (IndentGuideColoring::Fixed, false) => {
4527 Some(cx.theme().colors().editor_indent_guide)
4528 }
4529 (IndentGuideColoring::Fixed, true) => {
4530 Some(cx.theme().colors().editor_indent_guide_active)
4531 }
4532 (IndentGuideColoring::IndentAware, false) => {
4533 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4534 }
4535 (IndentGuideColoring::IndentAware, true) => {
4536 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4537 }
4538 };
4539
4540 let background_color = match (settings.background_coloring, indent_guide.active) {
4541 (IndentGuideBackgroundColoring::Disabled, _) => None,
4542 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4543 indent_accent_colors,
4544 INDENT_AWARE_BACKGROUND_ALPHA,
4545 )),
4546 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4547 indent_accent_colors,
4548 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4549 )),
4550 };
4551
4552 let requested_line_width = if indent_guide.active {
4553 settings.active_line_width
4554 } else {
4555 settings.line_width
4556 }
4557 .clamp(1, 10);
4558 let mut line_indicator_width = 0.;
4559 if let Some(color) = line_color {
4560 window.paint_quad(fill(
4561 Bounds {
4562 origin: indent_guide.origin,
4563 size: size(px(requested_line_width as f32), indent_guide.length),
4564 },
4565 color,
4566 ));
4567 line_indicator_width = requested_line_width as f32;
4568 }
4569
4570 if let Some(color) = background_color {
4571 let width = indent_guide.single_indent_width - px(line_indicator_width);
4572 window.paint_quad(fill(
4573 Bounds {
4574 origin: point(
4575 indent_guide.origin.x + px(line_indicator_width),
4576 indent_guide.origin.y,
4577 ),
4578 size: size(width, indent_guide.length),
4579 },
4580 color,
4581 ));
4582 }
4583 }
4584 }
4585
4586 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4587 let is_singleton = self.editor.read(cx).is_singleton(cx);
4588
4589 let line_height = layout.position_map.line_height;
4590 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4591
4592 for LineNumberLayout {
4593 shaped_line,
4594 hitbox,
4595 display_row,
4596 } in layout.line_numbers.values()
4597 {
4598 let Some(hitbox) = hitbox else {
4599 continue;
4600 };
4601
4602 let is_active = layout.active_rows.contains_key(&display_row);
4603
4604 let color = if is_active {
4605 cx.theme().colors().editor_active_line_number
4606 } else if !is_singleton && hitbox.is_hovered(window) {
4607 cx.theme().colors().editor_hover_line_number
4608 } else {
4609 cx.theme().colors().editor_line_number
4610 };
4611
4612 let Some(line) = self
4613 .shape_line_number(shaped_line.text.clone(), color, window)
4614 .log_err()
4615 else {
4616 continue;
4617 };
4618 let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4619 continue;
4620 };
4621 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4622 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4623 if is_singleton {
4624 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4625 } else {
4626 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4627 }
4628 }
4629 }
4630
4631 fn paint_diff_hunk_gutter_indicators(
4632 layout: &mut EditorLayout,
4633 window: &mut Window,
4634 cx: &mut App,
4635 ) {
4636 if layout.display_hunks.is_empty() {
4637 return;
4638 }
4639
4640 let corners = Corners::all(px(0.));
4641
4642 let line_height = layout.position_map.line_height;
4643 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4644 for (hunk, hitbox) in &layout.display_hunks {
4645 let hunk_to_paint = match hunk {
4646 DisplayDiffHunk::Folded { .. } => {
4647 let hunk_bounds = Self::diff_hunk_bounds(
4648 &layout.position_map.snapshot,
4649 line_height,
4650 layout.gutter_hitbox.bounds,
4651 hunk,
4652 );
4653 Some((
4654 hunk_bounds,
4655 cx.theme().colors().version_control_modified.opacity(0.7),
4656 corners,
4657 &DiffHunkSecondaryStatus::None,
4658 false,
4659 ))
4660 }
4661 DisplayDiffHunk::Unfolded {
4662 status,
4663 display_row_range,
4664 expanded,
4665 ..
4666 } => hitbox.as_ref().map(|hunk_hitbox| match status {
4667 DiffHunkStatus::Added(secondary_status) => (
4668 hunk_hitbox.bounds,
4669 cx.theme().colors().version_control_added.opacity(0.7),
4670 corners,
4671 secondary_status,
4672 *expanded,
4673 ),
4674 DiffHunkStatus::Modified(secondary_status) => (
4675 hunk_hitbox.bounds,
4676 cx.theme().colors().version_control_modified.opacity(0.7),
4677 corners,
4678 secondary_status,
4679 *expanded,
4680 ),
4681 DiffHunkStatus::Removed(secondary_status)
4682 if !display_row_range.is_empty() =>
4683 {
4684 (
4685 hunk_hitbox.bounds,
4686 cx.theme().colors().version_control_deleted.opacity(0.7),
4687 corners,
4688 secondary_status,
4689 *expanded,
4690 )
4691 }
4692 DiffHunkStatus::Removed(secondary_status) => (
4693 Bounds::new(
4694 point(
4695 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4696 hunk_hitbox.origin.y,
4697 ),
4698 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4699 ),
4700 cx.theme().colors().version_control_deleted.opacity(0.7),
4701 Corners::all(1. * line_height),
4702 secondary_status,
4703 *expanded,
4704 ),
4705 }),
4706 };
4707
4708 if let Some((
4709 hunk_bounds,
4710 background_color,
4711 corner_radii,
4712 secondary_status,
4713 expanded,
4714 )) = hunk_to_paint
4715 {
4716 let background =
4717 if *secondary_status != DiffHunkSecondaryStatus::None && expanded {
4718 pattern_slash(background_color, line_height.0 / 2.5)
4719 } else {
4720 solid_color(background_color)
4721 };
4722
4723 window.paint_quad(quad(
4724 hunk_bounds,
4725 corner_radii,
4726 background,
4727 Edges::default(),
4728 transparent_black(),
4729 ));
4730 }
4731 }
4732 });
4733 }
4734
4735 fn diff_hunk_bounds(
4736 snapshot: &EditorSnapshot,
4737 line_height: Pixels,
4738 gutter_bounds: Bounds<Pixels>,
4739 hunk: &DisplayDiffHunk,
4740 ) -> Bounds<Pixels> {
4741 let scroll_position = snapshot.scroll_position();
4742 let scroll_top = scroll_position.y * line_height;
4743 let gutter_strip_width = (0.275 * line_height).floor();
4744
4745 match hunk {
4746 DisplayDiffHunk::Folded { display_row, .. } => {
4747 let start_y = display_row.as_f32() * line_height - scroll_top;
4748 let end_y = start_y + line_height;
4749 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4750 let highlight_size = size(gutter_strip_width, end_y - start_y);
4751 Bounds::new(highlight_origin, highlight_size)
4752 }
4753 DisplayDiffHunk::Unfolded {
4754 display_row_range,
4755 status,
4756 ..
4757 } => {
4758 if status.is_removed() && display_row_range.is_empty() {
4759 let row = display_row_range.start;
4760
4761 let offset = line_height / 2.;
4762 let start_y = row.as_f32() * line_height - offset - scroll_top;
4763 let end_y = start_y + line_height;
4764
4765 let width = (0.35 * line_height).floor();
4766 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4767 let highlight_size = size(width, end_y - start_y);
4768 Bounds::new(highlight_origin, highlight_size)
4769 } else {
4770 let start_row = display_row_range.start;
4771 let end_row = display_row_range.end;
4772 // If we're in a multibuffer, row range span might include an
4773 // excerpt header, so if we were to draw the marker straight away,
4774 // the hunk might include the rows of that header.
4775 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4776 // Instead, we simply check whether the range we're dealing with includes
4777 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4778 let end_row_in_current_excerpt = snapshot
4779 .blocks_in_range(start_row..end_row)
4780 .find_map(|(start_row, block)| {
4781 if matches!(block, Block::ExcerptBoundary { .. }) {
4782 Some(start_row)
4783 } else {
4784 None
4785 }
4786 })
4787 .unwrap_or(end_row);
4788
4789 let start_y = start_row.as_f32() * line_height - scroll_top;
4790 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4791
4792 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4793 let highlight_size = size(gutter_strip_width, end_y - start_y);
4794 Bounds::new(highlight_origin, highlight_size)
4795 }
4796 }
4797 }
4798 }
4799
4800 fn paint_gutter_indicators(
4801 &self,
4802 layout: &mut EditorLayout,
4803 window: &mut Window,
4804 cx: &mut App,
4805 ) {
4806 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4807 window.with_element_namespace("crease_toggles", |window| {
4808 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4809 crease_toggle.paint(window, cx);
4810 }
4811 });
4812
4813 for test_indicator in layout.test_indicators.iter_mut() {
4814 test_indicator.paint(window, cx);
4815 }
4816
4817 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4818 indicator.paint(window, cx);
4819 }
4820 });
4821 }
4822
4823 fn paint_gutter_highlights(
4824 &self,
4825 layout: &mut EditorLayout,
4826 window: &mut Window,
4827 cx: &mut App,
4828 ) {
4829 for (_, hunk_hitbox) in &layout.display_hunks {
4830 if let Some(hunk_hitbox) = hunk_hitbox {
4831 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4832 }
4833 }
4834
4835 let show_git_gutter = layout
4836 .position_map
4837 .snapshot
4838 .show_git_diff_gutter
4839 .unwrap_or_else(|| {
4840 matches!(
4841 ProjectSettings::get_global(cx).git.git_gutter,
4842 Some(GitGutterSetting::TrackedFiles)
4843 )
4844 });
4845 if show_git_gutter {
4846 Self::paint_diff_hunk_gutter_indicators(layout, window, cx)
4847 }
4848
4849 let highlight_width = 0.275 * layout.position_map.line_height;
4850 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4851 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4852 for (range, color) in &layout.highlighted_gutter_ranges {
4853 let start_row = if range.start.row() < layout.visible_display_row_range.start {
4854 layout.visible_display_row_range.start - DisplayRow(1)
4855 } else {
4856 range.start.row()
4857 };
4858 let end_row = if range.end.row() > layout.visible_display_row_range.end {
4859 layout.visible_display_row_range.end + DisplayRow(1)
4860 } else {
4861 range.end.row()
4862 };
4863
4864 let start_y = layout.gutter_hitbox.top()
4865 + start_row.0 as f32 * layout.position_map.line_height
4866 - layout.position_map.scroll_pixel_position.y;
4867 let end_y = layout.gutter_hitbox.top()
4868 + (end_row.0 + 1) as f32 * layout.position_map.line_height
4869 - layout.position_map.scroll_pixel_position.y;
4870 let bounds = Bounds::from_corners(
4871 point(layout.gutter_hitbox.left(), start_y),
4872 point(layout.gutter_hitbox.left() + highlight_width, end_y),
4873 );
4874 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4875 }
4876 });
4877 }
4878
4879 fn paint_blamed_display_rows(
4880 &self,
4881 layout: &mut EditorLayout,
4882 window: &mut Window,
4883 cx: &mut App,
4884 ) {
4885 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4886 return;
4887 };
4888
4889 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4890 for mut blame_element in blamed_display_rows.into_iter() {
4891 blame_element.paint(window, cx);
4892 }
4893 })
4894 }
4895
4896 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4897 window.with_content_mask(
4898 Some(ContentMask {
4899 bounds: layout.position_map.text_hitbox.bounds,
4900 }),
4901 |window| {
4902 let cursor_style = if self
4903 .editor
4904 .read(cx)
4905 .hovered_link_state
4906 .as_ref()
4907 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4908 {
4909 CursorStyle::PointingHand
4910 } else {
4911 CursorStyle::IBeam
4912 };
4913 window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4914
4915 let invisible_display_ranges = self.paint_highlights(layout, window);
4916 self.paint_lines(&invisible_display_ranges, layout, window, cx);
4917 self.paint_redactions(layout, window);
4918 self.paint_cursors(layout, window, cx);
4919 self.paint_inline_blame(layout, window, cx);
4920 self.paint_diff_hunk_controls(layout, window, cx);
4921 window.with_element_namespace("crease_trailers", |window| {
4922 for trailer in layout.crease_trailers.iter_mut().flatten() {
4923 trailer.element.paint(window, cx);
4924 }
4925 });
4926 },
4927 )
4928 }
4929
4930 fn paint_highlights(
4931 &mut self,
4932 layout: &mut EditorLayout,
4933 window: &mut Window,
4934 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4935 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4936 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4937 let line_end_overshoot = 0.15 * layout.position_map.line_height;
4938 for (range, color) in &layout.highlighted_ranges {
4939 self.paint_highlighted_range(
4940 range.clone(),
4941 *color,
4942 Pixels::ZERO,
4943 line_end_overshoot,
4944 layout,
4945 window,
4946 );
4947 }
4948
4949 let corner_radius = 0.15 * layout.position_map.line_height;
4950
4951 for (player_color, selections) in &layout.selections {
4952 for selection in selections.iter() {
4953 self.paint_highlighted_range(
4954 selection.range.clone(),
4955 player_color.selection,
4956 corner_radius,
4957 corner_radius * 2.,
4958 layout,
4959 window,
4960 );
4961
4962 if selection.is_local && !selection.range.is_empty() {
4963 invisible_display_ranges.push(selection.range.clone());
4964 }
4965 }
4966 }
4967 invisible_display_ranges
4968 })
4969 }
4970
4971 fn paint_lines(
4972 &mut self,
4973 invisible_display_ranges: &[Range<DisplayPoint>],
4974 layout: &mut EditorLayout,
4975 window: &mut Window,
4976 cx: &mut App,
4977 ) {
4978 let whitespace_setting = self
4979 .editor
4980 .read(cx)
4981 .buffer
4982 .read(cx)
4983 .settings_at(0, cx)
4984 .show_whitespaces;
4985
4986 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4987 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4988 line_with_invisibles.draw(
4989 layout,
4990 row,
4991 layout.content_origin,
4992 whitespace_setting,
4993 invisible_display_ranges,
4994 window,
4995 cx,
4996 )
4997 }
4998
4999 for line_element in &mut layout.line_elements {
5000 line_element.paint(window, cx);
5001 }
5002 }
5003
5004 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
5005 if layout.redacted_ranges.is_empty() {
5006 return;
5007 }
5008
5009 let line_end_overshoot = layout.line_end_overshoot();
5010
5011 // A softer than perfect black
5012 let redaction_color = gpui::rgb(0x0e1111);
5013
5014 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5015 for range in layout.redacted_ranges.iter() {
5016 self.paint_highlighted_range(
5017 range.clone(),
5018 redaction_color.into(),
5019 Pixels::ZERO,
5020 line_end_overshoot,
5021 layout,
5022 window,
5023 );
5024 }
5025 });
5026 }
5027
5028 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5029 for cursor in &mut layout.visible_cursors {
5030 cursor.paint(layout.content_origin, window, cx);
5031 }
5032 }
5033
5034 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5035 let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
5036
5037 if let Some(scrollbar_layout) = scrollbar_x {
5038 let hitbox = scrollbar_layout.hitbox.clone();
5039 let text_unit_size = scrollbar_layout.text_unit_size;
5040 let visible_range = scrollbar_layout.visible_range.clone();
5041 let thumb_bounds = scrollbar_layout.thumb_bounds();
5042
5043 if scrollbar_layout.visible {
5044 window.paint_layer(hitbox.bounds, |window| {
5045 window.paint_quad(quad(
5046 hitbox.bounds,
5047 Corners::default(),
5048 cx.theme().colors().scrollbar_track_background,
5049 Edges {
5050 top: Pixels::ZERO,
5051 right: Pixels::ZERO,
5052 bottom: Pixels::ZERO,
5053 left: Pixels::ZERO,
5054 },
5055 cx.theme().colors().scrollbar_track_border,
5056 ));
5057
5058 window.paint_quad(quad(
5059 thumb_bounds,
5060 Corners::default(),
5061 cx.theme().colors().scrollbar_thumb_background,
5062 Edges {
5063 top: Pixels::ZERO,
5064 right: Pixels::ZERO,
5065 bottom: Pixels::ZERO,
5066 left: ScrollbarLayout::BORDER_WIDTH,
5067 },
5068 cx.theme().colors().scrollbar_thumb_border,
5069 ));
5070 })
5071 }
5072
5073 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5074
5075 window.on_mouse_event({
5076 let editor = self.editor.clone();
5077
5078 // there may be a way to avoid this clone
5079 let hitbox = hitbox.clone();
5080
5081 let mut mouse_position = window.mouse_position();
5082 move |event: &MouseMoveEvent, phase, window, cx| {
5083 if phase == DispatchPhase::Capture {
5084 return;
5085 }
5086
5087 editor.update(cx, |editor, cx| {
5088 if event.pressed_button == Some(MouseButton::Left)
5089 && editor
5090 .scroll_manager
5091 .is_dragging_scrollbar(Axis::Horizontal)
5092 {
5093 let x = mouse_position.x;
5094 let new_x = event.position.x;
5095 if (hitbox.left()..hitbox.right()).contains(&x) {
5096 let mut position = editor.scroll_position(cx);
5097
5098 position.x += (new_x - x) / text_unit_size;
5099 if position.x < 0.0 {
5100 position.x = 0.0;
5101 }
5102 editor.set_scroll_position(position, window, cx);
5103 }
5104
5105 cx.stop_propagation();
5106 } else {
5107 editor.scroll_manager.set_is_dragging_scrollbar(
5108 Axis::Horizontal,
5109 false,
5110 cx,
5111 );
5112
5113 if hitbox.is_hovered(window) {
5114 editor.scroll_manager.show_scrollbar(window, cx);
5115 }
5116 }
5117 mouse_position = event.position;
5118 })
5119 }
5120 });
5121
5122 if self
5123 .editor
5124 .read(cx)
5125 .scroll_manager
5126 .is_dragging_scrollbar(Axis::Horizontal)
5127 {
5128 window.on_mouse_event({
5129 let editor = self.editor.clone();
5130 move |_: &MouseUpEvent, phase, _, cx| {
5131 if phase == DispatchPhase::Capture {
5132 return;
5133 }
5134
5135 editor.update(cx, |editor, cx| {
5136 editor.scroll_manager.set_is_dragging_scrollbar(
5137 Axis::Horizontal,
5138 false,
5139 cx,
5140 );
5141 cx.stop_propagation();
5142 });
5143 }
5144 });
5145 } else {
5146 window.on_mouse_event({
5147 let editor = self.editor.clone();
5148
5149 move |event: &MouseDownEvent, phase, window, cx| {
5150 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5151 return;
5152 }
5153
5154 editor.update(cx, |editor, cx| {
5155 editor.scroll_manager.set_is_dragging_scrollbar(
5156 Axis::Horizontal,
5157 true,
5158 cx,
5159 );
5160
5161 let x = event.position.x;
5162
5163 if x < thumb_bounds.left() || thumb_bounds.right() < x {
5164 let center_row =
5165 ((x - hitbox.left()) / text_unit_size).round() as u32;
5166 let top_row = center_row.saturating_sub(
5167 (visible_range.end - visible_range.start) as u32 / 2,
5168 );
5169
5170 let mut position = editor.scroll_position(cx);
5171 position.x = top_row as f32;
5172
5173 editor.set_scroll_position(position, window, cx);
5174 } else {
5175 editor.scroll_manager.show_scrollbar(window, cx);
5176 }
5177
5178 cx.stop_propagation();
5179 });
5180 }
5181 });
5182 }
5183 }
5184
5185 if let Some(scrollbar_layout) = scrollbar_y {
5186 let hitbox = scrollbar_layout.hitbox.clone();
5187 let text_unit_size = scrollbar_layout.text_unit_size;
5188 let visible_range = scrollbar_layout.visible_range.clone();
5189 let thumb_bounds = scrollbar_layout.thumb_bounds();
5190
5191 if scrollbar_layout.visible {
5192 window.paint_layer(hitbox.bounds, |window| {
5193 window.paint_quad(quad(
5194 hitbox.bounds,
5195 Corners::default(),
5196 cx.theme().colors().scrollbar_track_background,
5197 Edges {
5198 top: Pixels::ZERO,
5199 right: Pixels::ZERO,
5200 bottom: Pixels::ZERO,
5201 left: ScrollbarLayout::BORDER_WIDTH,
5202 },
5203 cx.theme().colors().scrollbar_track_border,
5204 ));
5205
5206 let fast_markers =
5207 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5208 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5209 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5210
5211 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5212 for marker in markers.iter().chain(&fast_markers) {
5213 let mut marker = marker.clone();
5214 marker.bounds.origin += hitbox.origin;
5215 window.paint_quad(marker);
5216 }
5217
5218 window.paint_quad(quad(
5219 thumb_bounds,
5220 Corners::default(),
5221 cx.theme().colors().scrollbar_thumb_background,
5222 Edges {
5223 top: Pixels::ZERO,
5224 right: Pixels::ZERO,
5225 bottom: Pixels::ZERO,
5226 left: ScrollbarLayout::BORDER_WIDTH,
5227 },
5228 cx.theme().colors().scrollbar_thumb_border,
5229 ));
5230 });
5231 }
5232
5233 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5234
5235 window.on_mouse_event({
5236 let editor = self.editor.clone();
5237
5238 let hitbox = hitbox.clone();
5239
5240 let mut mouse_position = window.mouse_position();
5241 move |event: &MouseMoveEvent, phase, window, cx| {
5242 if phase == DispatchPhase::Capture {
5243 return;
5244 }
5245
5246 editor.update(cx, |editor, cx| {
5247 if event.pressed_button == Some(MouseButton::Left)
5248 && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5249 {
5250 let y = mouse_position.y;
5251 let new_y = event.position.y;
5252 if (hitbox.top()..hitbox.bottom()).contains(&y) {
5253 let mut position = editor.scroll_position(cx);
5254 position.y += (new_y - y) / text_unit_size;
5255 if position.y < 0.0 {
5256 position.y = 0.0;
5257 }
5258 editor.set_scroll_position(position, window, cx);
5259 }
5260 } else {
5261 editor.scroll_manager.set_is_dragging_scrollbar(
5262 Axis::Vertical,
5263 false,
5264 cx,
5265 );
5266
5267 if hitbox.is_hovered(window) {
5268 editor.scroll_manager.show_scrollbar(window, cx);
5269 }
5270 }
5271 mouse_position = event.position;
5272 })
5273 }
5274 });
5275
5276 if self
5277 .editor
5278 .read(cx)
5279 .scroll_manager
5280 .is_dragging_scrollbar(Axis::Vertical)
5281 {
5282 window.on_mouse_event({
5283 let editor = self.editor.clone();
5284 move |_: &MouseUpEvent, phase, _, cx| {
5285 if phase == DispatchPhase::Capture {
5286 return;
5287 }
5288
5289 editor.update(cx, |editor, cx| {
5290 editor.scroll_manager.set_is_dragging_scrollbar(
5291 Axis::Vertical,
5292 false,
5293 cx,
5294 );
5295 cx.stop_propagation();
5296 });
5297 }
5298 });
5299 } else {
5300 window.on_mouse_event({
5301 let editor = self.editor.clone();
5302
5303 move |event: &MouseDownEvent, phase, window, cx| {
5304 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5305 return;
5306 }
5307
5308 editor.update(cx, |editor, cx| {
5309 editor.scroll_manager.set_is_dragging_scrollbar(
5310 Axis::Vertical,
5311 true,
5312 cx,
5313 );
5314
5315 let y = event.position.y;
5316 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5317 let center_row =
5318 ((y - hitbox.top()) / text_unit_size).round() as u32;
5319 let top_row = center_row.saturating_sub(
5320 (visible_range.end - visible_range.start) as u32 / 2,
5321 );
5322 let mut position = editor.scroll_position(cx);
5323 position.y = top_row as f32;
5324 editor.set_scroll_position(position, window, cx);
5325 } else {
5326 editor.scroll_manager.show_scrollbar(window, cx);
5327 }
5328
5329 cx.stop_propagation();
5330 });
5331 }
5332 });
5333 }
5334 }
5335 }
5336
5337 fn collect_fast_scrollbar_markers(
5338 &self,
5339 layout: &EditorLayout,
5340 scrollbar_layout: &ScrollbarLayout,
5341 cx: &mut App,
5342 ) -> Vec<PaintQuad> {
5343 const LIMIT: usize = 100;
5344 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5345 return vec![];
5346 }
5347 let cursor_ranges = layout
5348 .cursors
5349 .iter()
5350 .map(|(point, color)| ColoredRange {
5351 start: point.row(),
5352 end: point.row(),
5353 color: *color,
5354 })
5355 .collect_vec();
5356 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5357 }
5358
5359 fn refresh_slow_scrollbar_markers(
5360 &self,
5361 layout: &EditorLayout,
5362 scrollbar_layout: &ScrollbarLayout,
5363 window: &mut Window,
5364 cx: &mut App,
5365 ) {
5366 self.editor.update(cx, |editor, cx| {
5367 if !editor.is_singleton(cx)
5368 || !editor
5369 .scrollbar_marker_state
5370 .should_refresh(scrollbar_layout.hitbox.size)
5371 {
5372 return;
5373 }
5374
5375 let scrollbar_layout = scrollbar_layout.clone();
5376 let background_highlights = editor.background_highlights.clone();
5377 let snapshot = layout.position_map.snapshot.clone();
5378 let theme = cx.theme().clone();
5379 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5380
5381 editor.scrollbar_marker_state.dirty = false;
5382 editor.scrollbar_marker_state.pending_refresh =
5383 Some(cx.spawn_in(window, |editor, mut cx| async move {
5384 let scrollbar_size = scrollbar_layout.hitbox.size;
5385 let scrollbar_markers = cx
5386 .background_executor()
5387 .spawn(async move {
5388 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5389 let mut marker_quads = Vec::new();
5390 if scrollbar_settings.git_diff {
5391 let marker_row_ranges =
5392 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5393 let start_display_row =
5394 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5395 .to_display_point(&snapshot.display_snapshot)
5396 .row();
5397 let mut end_display_row =
5398 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5399 .to_display_point(&snapshot.display_snapshot)
5400 .row();
5401 if end_display_row != start_display_row {
5402 end_display_row.0 -= 1;
5403 }
5404 let color = match &hunk.status() {
5405 DiffHunkStatus::Added(_) => {
5406 theme.colors().version_control_added
5407 }
5408 DiffHunkStatus::Modified(_) => {
5409 theme.colors().version_control_modified
5410 }
5411 DiffHunkStatus::Removed(_) => {
5412 theme.colors().version_control_deleted
5413 }
5414 };
5415 ColoredRange {
5416 start: start_display_row,
5417 end: end_display_row,
5418 color,
5419 }
5420 });
5421
5422 marker_quads.extend(
5423 scrollbar_layout
5424 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5425 );
5426 }
5427
5428 for (background_highlight_id, (_, background_ranges)) in
5429 background_highlights.iter()
5430 {
5431 let is_search_highlights = *background_highlight_id
5432 == TypeId::of::<BufferSearchHighlights>();
5433 let is_symbol_occurrences = *background_highlight_id
5434 == TypeId::of::<DocumentHighlightRead>()
5435 || *background_highlight_id
5436 == TypeId::of::<DocumentHighlightWrite>();
5437 if (is_search_highlights && scrollbar_settings.search_results)
5438 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5439 {
5440 let mut color = theme.status().info;
5441 if is_symbol_occurrences {
5442 color.fade_out(0.5);
5443 }
5444 let marker_row_ranges = background_ranges.iter().map(|range| {
5445 let display_start = range
5446 .start
5447 .to_display_point(&snapshot.display_snapshot);
5448 let display_end =
5449 range.end.to_display_point(&snapshot.display_snapshot);
5450 ColoredRange {
5451 start: display_start.row(),
5452 end: display_end.row(),
5453 color,
5454 }
5455 });
5456 marker_quads.extend(
5457 scrollbar_layout
5458 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5459 );
5460 }
5461 }
5462
5463 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5464 let diagnostics = snapshot
5465 .buffer_snapshot
5466 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5467 // Don't show diagnostics the user doesn't care about
5468 .filter(|diagnostic| {
5469 match (
5470 scrollbar_settings.diagnostics,
5471 diagnostic.diagnostic.severity,
5472 ) {
5473 (ScrollbarDiagnostics::All, _) => true,
5474 (
5475 ScrollbarDiagnostics::Error,
5476 DiagnosticSeverity::ERROR,
5477 ) => true,
5478 (
5479 ScrollbarDiagnostics::Warning,
5480 DiagnosticSeverity::ERROR
5481 | DiagnosticSeverity::WARNING,
5482 ) => true,
5483 (
5484 ScrollbarDiagnostics::Information,
5485 DiagnosticSeverity::ERROR
5486 | DiagnosticSeverity::WARNING
5487 | DiagnosticSeverity::INFORMATION,
5488 ) => true,
5489 (_, _) => false,
5490 }
5491 })
5492 // We want to sort by severity, in order to paint the most severe diagnostics last.
5493 .sorted_by_key(|diagnostic| {
5494 std::cmp::Reverse(diagnostic.diagnostic.severity)
5495 });
5496
5497 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5498 let start_display = diagnostic
5499 .range
5500 .start
5501 .to_display_point(&snapshot.display_snapshot);
5502 let end_display = diagnostic
5503 .range
5504 .end
5505 .to_display_point(&snapshot.display_snapshot);
5506 let color = match diagnostic.diagnostic.severity {
5507 DiagnosticSeverity::ERROR => theme.status().error,
5508 DiagnosticSeverity::WARNING => theme.status().warning,
5509 DiagnosticSeverity::INFORMATION => theme.status().info,
5510 _ => theme.status().hint,
5511 };
5512 ColoredRange {
5513 start: start_display.row(),
5514 end: end_display.row(),
5515 color,
5516 }
5517 });
5518 marker_quads.extend(
5519 scrollbar_layout
5520 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5521 );
5522 }
5523
5524 Arc::from(marker_quads)
5525 })
5526 .await;
5527
5528 editor.update(&mut cx, |editor, cx| {
5529 editor.scrollbar_marker_state.markers = scrollbar_markers;
5530 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5531 editor.scrollbar_marker_state.pending_refresh = None;
5532 cx.notify();
5533 })?;
5534
5535 Ok(())
5536 }));
5537 });
5538 }
5539
5540 #[allow(clippy::too_many_arguments)]
5541 fn paint_highlighted_range(
5542 &self,
5543 range: Range<DisplayPoint>,
5544 color: Hsla,
5545 corner_radius: Pixels,
5546 line_end_overshoot: Pixels,
5547 layout: &EditorLayout,
5548 window: &mut Window,
5549 ) {
5550 let start_row = layout.visible_display_row_range.start;
5551 let end_row = layout.visible_display_row_range.end;
5552 if range.start != range.end {
5553 let row_range = if range.end.column() == 0 {
5554 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5555 } else {
5556 cmp::max(range.start.row(), start_row)
5557 ..cmp::min(range.end.row().next_row(), end_row)
5558 };
5559
5560 let highlighted_range = HighlightedRange {
5561 color,
5562 line_height: layout.position_map.line_height,
5563 corner_radius,
5564 start_y: layout.content_origin.y
5565 + row_range.start.as_f32() * layout.position_map.line_height
5566 - layout.position_map.scroll_pixel_position.y,
5567 lines: row_range
5568 .iter_rows()
5569 .map(|row| {
5570 let line_layout =
5571 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5572 HighlightedRangeLine {
5573 start_x: if row == range.start.row() {
5574 layout.content_origin.x
5575 + line_layout.x_for_index(range.start.column() as usize)
5576 - layout.position_map.scroll_pixel_position.x
5577 } else {
5578 layout.content_origin.x
5579 - layout.position_map.scroll_pixel_position.x
5580 },
5581 end_x: if row == range.end.row() {
5582 layout.content_origin.x
5583 + line_layout.x_for_index(range.end.column() as usize)
5584 - layout.position_map.scroll_pixel_position.x
5585 } else {
5586 layout.content_origin.x + line_layout.width + line_end_overshoot
5587 - layout.position_map.scroll_pixel_position.x
5588 },
5589 }
5590 })
5591 .collect(),
5592 };
5593
5594 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5595 }
5596 }
5597
5598 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5599 if let Some(mut inline_blame) = layout.inline_blame.take() {
5600 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5601 inline_blame.paint(window, cx);
5602 })
5603 }
5604 }
5605
5606 fn paint_diff_hunk_controls(
5607 &mut self,
5608 layout: &mut EditorLayout,
5609 window: &mut Window,
5610 cx: &mut App,
5611 ) {
5612 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5613 diff_hunk_control.paint(window, cx);
5614 }
5615 }
5616
5617 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5618 for mut block in layout.blocks.drain(..) {
5619 block.element.paint(window, cx);
5620 }
5621 }
5622
5623 fn paint_inline_completion_popover(
5624 &mut self,
5625 layout: &mut EditorLayout,
5626 window: &mut Window,
5627 cx: &mut App,
5628 ) {
5629 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5630 inline_completion_popover.paint(window, cx);
5631 }
5632 }
5633
5634 fn paint_mouse_context_menu(
5635 &mut self,
5636 layout: &mut EditorLayout,
5637 window: &mut Window,
5638 cx: &mut App,
5639 ) {
5640 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5641 mouse_context_menu.paint(window, cx);
5642 }
5643 }
5644
5645 fn paint_scroll_wheel_listener(
5646 &mut self,
5647 layout: &EditorLayout,
5648 window: &mut Window,
5649 cx: &mut App,
5650 ) {
5651 window.on_mouse_event({
5652 let position_map = layout.position_map.clone();
5653 let editor = self.editor.clone();
5654 let hitbox = layout.hitbox.clone();
5655 let mut delta = ScrollDelta::default();
5656
5657 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5658 // accidentally turn off their scrolling.
5659 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5660
5661 move |event: &ScrollWheelEvent, phase, window, cx| {
5662 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5663 delta = delta.coalesce(event.delta);
5664 editor.update(cx, |editor, cx| {
5665 let position_map: &PositionMap = &position_map;
5666
5667 let line_height = position_map.line_height;
5668 let max_glyph_width = position_map.em_width;
5669 let (delta, axis) = match delta {
5670 gpui::ScrollDelta::Pixels(mut pixels) => {
5671 //Trackpad
5672 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5673 (pixels, axis)
5674 }
5675
5676 gpui::ScrollDelta::Lines(lines) => {
5677 //Not trackpad
5678 let pixels =
5679 point(lines.x * max_glyph_width, lines.y * line_height);
5680 (pixels, None)
5681 }
5682 };
5683
5684 let current_scroll_position = position_map.snapshot.scroll_position();
5685 let x = (current_scroll_position.x * max_glyph_width
5686 - (delta.x * scroll_sensitivity))
5687 / max_glyph_width;
5688 let y = (current_scroll_position.y * line_height
5689 - (delta.y * scroll_sensitivity))
5690 / line_height;
5691 let mut scroll_position =
5692 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5693 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5694 if forbid_vertical_scroll {
5695 scroll_position.y = current_scroll_position.y;
5696 }
5697
5698 if scroll_position != current_scroll_position {
5699 editor.scroll(scroll_position, axis, window, cx);
5700 cx.stop_propagation();
5701 } else if y < 0. {
5702 // Due to clamping, we may fail to detect cases of overscroll to the top;
5703 // We want the scroll manager to get an update in such cases and detect the change of direction
5704 // on the next frame.
5705 cx.notify();
5706 }
5707 });
5708 }
5709 }
5710 });
5711 }
5712
5713 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5714 self.paint_scroll_wheel_listener(layout, window, cx);
5715
5716 window.on_mouse_event({
5717 let position_map = layout.position_map.clone();
5718 let editor = self.editor.clone();
5719 let multi_buffer_range =
5720 layout
5721 .display_hunks
5722 .iter()
5723 .find_map(|(hunk, hunk_hitbox)| match hunk {
5724 DisplayDiffHunk::Folded { .. } => None,
5725 DisplayDiffHunk::Unfolded {
5726 multi_buffer_range, ..
5727 } => {
5728 if hunk_hitbox
5729 .as_ref()
5730 .map(|hitbox| hitbox.is_hovered(window))
5731 .unwrap_or(false)
5732 {
5733 Some(multi_buffer_range.clone())
5734 } else {
5735 None
5736 }
5737 }
5738 });
5739 let line_numbers = layout.line_numbers.clone();
5740
5741 move |event: &MouseDownEvent, phase, window, cx| {
5742 if phase == DispatchPhase::Bubble {
5743 match event.button {
5744 MouseButton::Left => editor.update(cx, |editor, cx| {
5745 let pending_mouse_down = editor
5746 .pending_mouse_down
5747 .get_or_insert_with(Default::default)
5748 .clone();
5749
5750 *pending_mouse_down.borrow_mut() = Some(event.clone());
5751
5752 Self::mouse_left_down(
5753 editor,
5754 event,
5755 multi_buffer_range.clone(),
5756 &position_map,
5757 line_numbers.as_ref(),
5758 window,
5759 cx,
5760 );
5761 }),
5762 MouseButton::Right => editor.update(cx, |editor, cx| {
5763 Self::mouse_right_down(editor, event, &position_map, window, cx);
5764 }),
5765 MouseButton::Middle => editor.update(cx, |editor, cx| {
5766 Self::mouse_middle_down(editor, event, &position_map, window, cx);
5767 }),
5768 _ => {}
5769 };
5770 }
5771 }
5772 });
5773
5774 window.on_mouse_event({
5775 let editor = self.editor.clone();
5776 let position_map = layout.position_map.clone();
5777
5778 move |event: &MouseUpEvent, phase, window, cx| {
5779 if phase == DispatchPhase::Bubble {
5780 editor.update(cx, |editor, cx| {
5781 Self::mouse_up(editor, event, &position_map, window, cx)
5782 });
5783 }
5784 }
5785 });
5786
5787 window.on_mouse_event({
5788 let editor = self.editor.clone();
5789 let position_map = layout.position_map.clone();
5790 let mut captured_mouse_down = None;
5791
5792 move |event: &MouseUpEvent, phase, window, cx| match phase {
5793 // Clear the pending mouse down during the capture phase,
5794 // so that it happens even if another event handler stops
5795 // propagation.
5796 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5797 let pending_mouse_down = editor
5798 .pending_mouse_down
5799 .get_or_insert_with(Default::default)
5800 .clone();
5801
5802 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5803 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5804 captured_mouse_down = pending_mouse_down.take();
5805 window.refresh();
5806 }
5807 }),
5808 // Fire click handlers during the bubble phase.
5809 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5810 if let Some(mouse_down) = captured_mouse_down.take() {
5811 let event = ClickEvent {
5812 down: mouse_down,
5813 up: event.clone(),
5814 };
5815 Self::click(editor, &event, &position_map, window, cx);
5816 }
5817 }),
5818 }
5819 });
5820
5821 window.on_mouse_event({
5822 let position_map = layout.position_map.clone();
5823 let editor = self.editor.clone();
5824
5825 move |event: &MouseMoveEvent, phase, window, cx| {
5826 if phase == DispatchPhase::Bubble {
5827 editor.update(cx, |editor, cx| {
5828 if editor.hover_state.focused(window, cx) {
5829 return;
5830 }
5831 if event.pressed_button == Some(MouseButton::Left)
5832 || event.pressed_button == Some(MouseButton::Middle)
5833 {
5834 Self::mouse_dragged(editor, event, &position_map, window, cx)
5835 }
5836
5837 Self::mouse_moved(editor, event, &position_map, window, cx)
5838 });
5839 }
5840 }
5841 });
5842 }
5843
5844 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5845 bounds.top_right().x - self.style.scrollbar_width
5846 }
5847
5848 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5849 let style = &self.style;
5850 let font_size = style.text.font_size.to_pixels(window.rem_size());
5851 let layout = window
5852 .text_system()
5853 .shape_line(
5854 SharedString::from(" ".repeat(column)),
5855 font_size,
5856 &[TextRun {
5857 len: column,
5858 font: style.text.font(),
5859 color: Hsla::default(),
5860 background_color: None,
5861 underline: None,
5862 strikethrough: None,
5863 }],
5864 )
5865 .unwrap();
5866
5867 layout.width
5868 }
5869
5870 fn max_line_number_width(
5871 &self,
5872 snapshot: &EditorSnapshot,
5873 window: &mut Window,
5874 cx: &mut App,
5875 ) -> Pixels {
5876 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5877 self.column_pixels(digit_count, window, cx)
5878 }
5879
5880 fn shape_line_number(
5881 &self,
5882 text: SharedString,
5883 color: Hsla,
5884 window: &mut Window,
5885 ) -> anyhow::Result<ShapedLine> {
5886 let run = TextRun {
5887 len: text.len(),
5888 font: self.style.text.font(),
5889 color,
5890 background_color: None,
5891 underline: None,
5892 strikethrough: None,
5893 };
5894 window.text_system().shape_line(
5895 text,
5896 self.style.text.font_size.to_pixels(window.rem_size()),
5897 &[run],
5898 )
5899 }
5900}
5901
5902fn header_jump_data(
5903 snapshot: &EditorSnapshot,
5904 block_row_start: DisplayRow,
5905 height: u32,
5906 for_excerpt: &ExcerptInfo,
5907) -> JumpData {
5908 let range = &for_excerpt.range;
5909 let buffer = &for_excerpt.buffer;
5910 let jump_anchor = range
5911 .primary
5912 .as_ref()
5913 .map_or(range.context.start, |primary| primary.start);
5914
5915 let excerpt_start = range.context.start;
5916 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5917 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5918 0
5919 } else {
5920 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5921 jump_position.row.saturating_sub(excerpt_start_point.row)
5922 };
5923
5924 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5925 .saturating_sub(
5926 snapshot
5927 .scroll_anchor
5928 .scroll_position(&snapshot.display_snapshot)
5929 .y as u32,
5930 );
5931
5932 JumpData::MultiBufferPoint {
5933 excerpt_id: for_excerpt.id,
5934 anchor: jump_anchor,
5935 position: jump_position,
5936 line_offset_from_top,
5937 }
5938}
5939
5940pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5941
5942impl AcceptEditPredictionBinding {
5943 pub fn keystroke(&self) -> Option<&Keystroke> {
5944 if let Some(binding) = self.0.as_ref() {
5945 match &binding.keystrokes() {
5946 [keystroke] => Some(keystroke),
5947 _ => None,
5948 }
5949 } else {
5950 None
5951 }
5952 }
5953}
5954
5955#[allow(clippy::too_many_arguments)]
5956fn prepaint_gutter_button(
5957 button: IconButton,
5958 row: DisplayRow,
5959 line_height: Pixels,
5960 gutter_dimensions: &GutterDimensions,
5961 scroll_pixel_position: gpui::Point<Pixels>,
5962 gutter_hitbox: &Hitbox,
5963 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5964 window: &mut Window,
5965 cx: &mut App,
5966) -> AnyElement {
5967 let mut button = button.into_any_element();
5968 let available_space = size(
5969 AvailableSpace::MinContent,
5970 AvailableSpace::Definite(line_height),
5971 );
5972 let indicator_size = button.layout_as_root(available_space, window, cx);
5973
5974 let blame_width = gutter_dimensions.git_blame_entries_width;
5975 let gutter_width = rows_with_hunk_bounds
5976 .get(&row)
5977 .map(|bounds| bounds.size.width);
5978 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5979
5980 let mut x = left_offset;
5981 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5982 - indicator_size.width
5983 - left_offset;
5984 x += available_width / 2.;
5985
5986 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5987 y += (line_height - indicator_size.height) / 2.;
5988
5989 button.prepaint_as_root(
5990 gutter_hitbox.origin + point(x, y),
5991 available_space,
5992 window,
5993 cx,
5994 );
5995 button
5996}
5997
5998fn render_inline_blame_entry(
5999 blame: &gpui::Entity<GitBlame>,
6000 blame_entry: BlameEntry,
6001 style: &EditorStyle,
6002 workspace: Option<WeakEntity<Workspace>>,
6003 cx: &mut App,
6004) -> AnyElement {
6005 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
6006
6007 let author = blame_entry.author.as_deref().unwrap_or_default();
6008 let summary_enabled = ProjectSettings::get_global(cx)
6009 .git
6010 .show_inline_commit_summary();
6011
6012 let text = match blame_entry.summary.as_ref() {
6013 Some(summary) if summary_enabled => {
6014 format!("{}, {} - {}", author, relative_timestamp, summary)
6015 }
6016 _ => format!("{}, {}", author, relative_timestamp),
6017 };
6018
6019 let details = blame.read(cx).details_for_entry(&blame_entry);
6020
6021 let tooltip =
6022 cx.new(|_| CommitTooltip::blame_entry(blame_entry, details, style.clone(), workspace));
6023
6024 h_flex()
6025 .id("inline-blame")
6026 .w_full()
6027 .font_family(style.text.font().family)
6028 .text_color(cx.theme().status().hint)
6029 .line_height(style.text.line_height)
6030 .child(Icon::new(IconName::FileGit).color(Color::Hint))
6031 .child(text)
6032 .gap_2()
6033 .hoverable_tooltip(move |_, _| tooltip.clone().into())
6034 .into_any()
6035}
6036
6037fn render_blame_entry(
6038 ix: usize,
6039 blame: &gpui::Entity<GitBlame>,
6040 blame_entry: BlameEntry,
6041 style: &EditorStyle,
6042 last_used_color: &mut Option<(PlayerColor, Oid)>,
6043 editor: Entity<Editor>,
6044 cx: &mut App,
6045) -> AnyElement {
6046 let mut sha_color = cx
6047 .theme()
6048 .players()
6049 .color_for_participant(blame_entry.sha.into());
6050 // If the last color we used is the same as the one we get for this line, but
6051 // the commit SHAs are different, then we try again to get a different color.
6052 match *last_used_color {
6053 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
6054 let index: u32 = blame_entry.sha.into();
6055 sha_color = cx.theme().players().color_for_participant(index + 1);
6056 }
6057 _ => {}
6058 };
6059 last_used_color.replace((sha_color, blame_entry.sha));
6060
6061 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
6062
6063 let short_commit_id = blame_entry.sha.display_short();
6064
6065 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
6066 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
6067
6068 let details = blame.read(cx).details_for_entry(&blame_entry);
6069
6070 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
6071
6072 let tooltip = cx.new(|_| {
6073 CommitTooltip::blame_entry(
6074 blame_entry.clone(),
6075 details.clone(),
6076 style.clone(),
6077 workspace,
6078 )
6079 });
6080
6081 h_flex()
6082 .w_full()
6083 .justify_between()
6084 .font_family(style.text.font().family)
6085 .line_height(style.text.line_height)
6086 .id(("blame", ix))
6087 .text_color(cx.theme().status().hint)
6088 .pr_2()
6089 .gap_2()
6090 .child(
6091 h_flex()
6092 .items_center()
6093 .gap_2()
6094 .child(div().text_color(sha_color.cursor).child(short_commit_id))
6095 .child(name),
6096 )
6097 .child(relative_timestamp)
6098 .on_mouse_down(MouseButton::Right, {
6099 let blame_entry = blame_entry.clone();
6100 let details = details.clone();
6101 move |event, window, cx| {
6102 deploy_blame_entry_context_menu(
6103 &blame_entry,
6104 details.as_ref(),
6105 editor.clone(),
6106 event.position,
6107 window,
6108 cx,
6109 );
6110 }
6111 })
6112 .hover(|style| style.bg(cx.theme().colors().element_hover))
6113 .when_some(
6114 details.and_then(|details| details.permalink),
6115 |this, url| {
6116 let url = url.clone();
6117 this.cursor_pointer().on_click(move |_, _, cx| {
6118 cx.stop_propagation();
6119 cx.open_url(url.as_str())
6120 })
6121 },
6122 )
6123 .hoverable_tooltip(move |_, _| tooltip.clone().into())
6124 .into_any()
6125}
6126
6127fn deploy_blame_entry_context_menu(
6128 blame_entry: &BlameEntry,
6129 details: Option<&ParsedCommitMessage>,
6130 editor: Entity<Editor>,
6131 position: gpui::Point<Pixels>,
6132 window: &mut Window,
6133 cx: &mut App,
6134) {
6135 let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
6136 let sha = format!("{}", blame_entry.sha);
6137 menu.on_blur_subscription(Subscription::new(|| {}))
6138 .entry("Copy commit SHA", None, move |_, cx| {
6139 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
6140 })
6141 .when_some(
6142 details.and_then(|details| details.permalink.clone()),
6143 |this, url| {
6144 this.entry("Open permalink", None, move |_, cx| {
6145 cx.open_url(url.as_str())
6146 })
6147 },
6148 )
6149 });
6150
6151 editor.update(cx, move |editor, cx| {
6152 editor.mouse_context_menu = Some(MouseContextMenu::new(
6153 MenuPosition::PinnedToScreen(position),
6154 context_menu,
6155 window,
6156 cx,
6157 ));
6158 cx.notify();
6159 });
6160}
6161
6162#[derive(Debug)]
6163pub(crate) struct LineWithInvisibles {
6164 fragments: SmallVec<[LineFragment; 1]>,
6165 invisibles: Vec<Invisible>,
6166 len: usize,
6167 width: Pixels,
6168 font_size: Pixels,
6169}
6170
6171#[allow(clippy::large_enum_variant)]
6172enum LineFragment {
6173 Text(ShapedLine),
6174 Element {
6175 element: Option<AnyElement>,
6176 size: Size<Pixels>,
6177 len: usize,
6178 },
6179}
6180
6181impl fmt::Debug for LineFragment {
6182 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6183 match self {
6184 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6185 LineFragment::Element { size, len, .. } => f
6186 .debug_struct("Element")
6187 .field("size", size)
6188 .field("len", len)
6189 .finish(),
6190 }
6191 }
6192}
6193
6194impl LineWithInvisibles {
6195 #[allow(clippy::too_many_arguments)]
6196 fn from_chunks<'a>(
6197 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6198 editor_style: &EditorStyle,
6199 max_line_len: usize,
6200 max_line_count: usize,
6201 editor_mode: EditorMode,
6202 text_width: Pixels,
6203 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6204 window: &mut Window,
6205 cx: &mut App,
6206 ) -> Vec<Self> {
6207 let text_style = &editor_style.text;
6208 let mut layouts = Vec::with_capacity(max_line_count);
6209 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6210 let mut line = String::new();
6211 let mut invisibles = Vec::new();
6212 let mut width = Pixels::ZERO;
6213 let mut len = 0;
6214 let mut styles = Vec::new();
6215 let mut non_whitespace_added = false;
6216 let mut row = 0;
6217 let mut line_exceeded_max_len = false;
6218 let font_size = text_style.font_size.to_pixels(window.rem_size());
6219
6220 let ellipsis = SharedString::from("⋯");
6221
6222 for highlighted_chunk in chunks.chain([HighlightedChunk {
6223 text: "\n",
6224 style: None,
6225 is_tab: false,
6226 replacement: None,
6227 }]) {
6228 if let Some(replacement) = highlighted_chunk.replacement {
6229 if !line.is_empty() {
6230 let shaped_line = window
6231 .text_system()
6232 .shape_line(line.clone().into(), font_size, &styles)
6233 .unwrap();
6234 width += shaped_line.width;
6235 len += shaped_line.len;
6236 fragments.push(LineFragment::Text(shaped_line));
6237 line.clear();
6238 styles.clear();
6239 }
6240
6241 match replacement {
6242 ChunkReplacement::Renderer(renderer) => {
6243 let available_width = if renderer.constrain_width {
6244 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6245 ellipsis.clone()
6246 } else {
6247 SharedString::from(Arc::from(highlighted_chunk.text))
6248 };
6249 let shaped_line = window
6250 .text_system()
6251 .shape_line(
6252 chunk,
6253 font_size,
6254 &[text_style.to_run(highlighted_chunk.text.len())],
6255 )
6256 .unwrap();
6257 AvailableSpace::Definite(shaped_line.width)
6258 } else {
6259 AvailableSpace::MinContent
6260 };
6261
6262 let mut element = (renderer.render)(&mut ChunkRendererContext {
6263 context: cx,
6264 window,
6265 max_width: text_width,
6266 });
6267 let line_height = text_style.line_height_in_pixels(window.rem_size());
6268 let size = element.layout_as_root(
6269 size(available_width, AvailableSpace::Definite(line_height)),
6270 window,
6271 cx,
6272 );
6273
6274 width += size.width;
6275 len += highlighted_chunk.text.len();
6276 fragments.push(LineFragment::Element {
6277 element: Some(element),
6278 size,
6279 len: highlighted_chunk.text.len(),
6280 });
6281 }
6282 ChunkReplacement::Str(x) => {
6283 let text_style = if let Some(style) = highlighted_chunk.style {
6284 Cow::Owned(text_style.clone().highlight(style))
6285 } else {
6286 Cow::Borrowed(text_style)
6287 };
6288
6289 let run = TextRun {
6290 len: x.len(),
6291 font: text_style.font(),
6292 color: text_style.color,
6293 background_color: text_style.background_color,
6294 underline: text_style.underline,
6295 strikethrough: text_style.strikethrough,
6296 };
6297 let line_layout = window
6298 .text_system()
6299 .shape_line(x, font_size, &[run])
6300 .unwrap()
6301 .with_len(highlighted_chunk.text.len());
6302
6303 width += line_layout.width;
6304 len += highlighted_chunk.text.len();
6305 fragments.push(LineFragment::Text(line_layout))
6306 }
6307 }
6308 } else {
6309 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6310 if ix > 0 {
6311 let shaped_line = window
6312 .text_system()
6313 .shape_line(line.clone().into(), font_size, &styles)
6314 .unwrap();
6315 width += shaped_line.width;
6316 len += shaped_line.len;
6317 fragments.push(LineFragment::Text(shaped_line));
6318 layouts.push(Self {
6319 width: mem::take(&mut width),
6320 len: mem::take(&mut len),
6321 fragments: mem::take(&mut fragments),
6322 invisibles: std::mem::take(&mut invisibles),
6323 font_size,
6324 });
6325
6326 line.clear();
6327 styles.clear();
6328 row += 1;
6329 line_exceeded_max_len = false;
6330 non_whitespace_added = false;
6331 if row == max_line_count {
6332 return layouts;
6333 }
6334 }
6335
6336 if !line_chunk.is_empty() && !line_exceeded_max_len {
6337 let text_style = if let Some(style) = highlighted_chunk.style {
6338 Cow::Owned(text_style.clone().highlight(style))
6339 } else {
6340 Cow::Borrowed(text_style)
6341 };
6342
6343 if line.len() + line_chunk.len() > max_line_len {
6344 let mut chunk_len = max_line_len - line.len();
6345 while !line_chunk.is_char_boundary(chunk_len) {
6346 chunk_len -= 1;
6347 }
6348 line_chunk = &line_chunk[..chunk_len];
6349 line_exceeded_max_len = true;
6350 }
6351
6352 styles.push(TextRun {
6353 len: line_chunk.len(),
6354 font: text_style.font(),
6355 color: text_style.color,
6356 background_color: text_style.background_color,
6357 underline: text_style.underline,
6358 strikethrough: text_style.strikethrough,
6359 });
6360
6361 if editor_mode == EditorMode::Full {
6362 // Line wrap pads its contents with fake whitespaces,
6363 // avoid printing them
6364 let is_soft_wrapped = is_row_soft_wrapped(row);
6365 if highlighted_chunk.is_tab {
6366 if non_whitespace_added || !is_soft_wrapped {
6367 invisibles.push(Invisible::Tab {
6368 line_start_offset: line.len(),
6369 line_end_offset: line.len() + line_chunk.len(),
6370 });
6371 }
6372 } else {
6373 invisibles.extend(line_chunk.char_indices().filter_map(
6374 |(index, c)| {
6375 let is_whitespace = c.is_whitespace();
6376 non_whitespace_added |= !is_whitespace;
6377 if is_whitespace
6378 && (non_whitespace_added || !is_soft_wrapped)
6379 {
6380 Some(Invisible::Whitespace {
6381 line_offset: line.len() + index,
6382 })
6383 } else {
6384 None
6385 }
6386 },
6387 ))
6388 }
6389 }
6390
6391 line.push_str(line_chunk);
6392 }
6393 }
6394 }
6395 }
6396
6397 layouts
6398 }
6399
6400 #[allow(clippy::too_many_arguments)]
6401 fn prepaint(
6402 &mut self,
6403 line_height: Pixels,
6404 scroll_pixel_position: gpui::Point<Pixels>,
6405 row: DisplayRow,
6406 content_origin: gpui::Point<Pixels>,
6407 line_elements: &mut SmallVec<[AnyElement; 1]>,
6408 window: &mut Window,
6409 cx: &mut App,
6410 ) {
6411 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6412 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6413 for fragment in &mut self.fragments {
6414 match fragment {
6415 LineFragment::Text(line) => {
6416 fragment_origin.x += line.width;
6417 }
6418 LineFragment::Element { element, size, .. } => {
6419 let mut element = element
6420 .take()
6421 .expect("you can't prepaint LineWithInvisibles twice");
6422
6423 // Center the element vertically within the line.
6424 let mut element_origin = fragment_origin;
6425 element_origin.y += (line_height - size.height) / 2.;
6426 element.prepaint_at(element_origin, window, cx);
6427 line_elements.push(element);
6428
6429 fragment_origin.x += size.width;
6430 }
6431 }
6432 }
6433 }
6434
6435 #[allow(clippy::too_many_arguments)]
6436 fn draw(
6437 &self,
6438 layout: &EditorLayout,
6439 row: DisplayRow,
6440 content_origin: gpui::Point<Pixels>,
6441 whitespace_setting: ShowWhitespaceSetting,
6442 selection_ranges: &[Range<DisplayPoint>],
6443 window: &mut Window,
6444 cx: &mut App,
6445 ) {
6446 let line_height = layout.position_map.line_height;
6447 let line_y = line_height
6448 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6449
6450 let mut fragment_origin =
6451 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6452
6453 for fragment in &self.fragments {
6454 match fragment {
6455 LineFragment::Text(line) => {
6456 line.paint(fragment_origin, line_height, window, cx)
6457 .log_err();
6458 fragment_origin.x += line.width;
6459 }
6460 LineFragment::Element { size, .. } => {
6461 fragment_origin.x += size.width;
6462 }
6463 }
6464 }
6465
6466 self.draw_invisibles(
6467 selection_ranges,
6468 layout,
6469 content_origin,
6470 line_y,
6471 row,
6472 line_height,
6473 whitespace_setting,
6474 window,
6475 cx,
6476 );
6477 }
6478
6479 #[allow(clippy::too_many_arguments)]
6480 fn draw_invisibles(
6481 &self,
6482 selection_ranges: &[Range<DisplayPoint>],
6483 layout: &EditorLayout,
6484 content_origin: gpui::Point<Pixels>,
6485 line_y: Pixels,
6486 row: DisplayRow,
6487 line_height: Pixels,
6488 whitespace_setting: ShowWhitespaceSetting,
6489 window: &mut Window,
6490 cx: &mut App,
6491 ) {
6492 let extract_whitespace_info = |invisible: &Invisible| {
6493 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6494 Invisible::Tab {
6495 line_start_offset,
6496 line_end_offset,
6497 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6498 Invisible::Whitespace { line_offset } => {
6499 (*line_offset, line_offset + 1, &layout.space_invisible)
6500 }
6501 };
6502
6503 let x_offset = self.x_for_index(token_offset);
6504 let invisible_offset =
6505 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6506 let origin = content_origin
6507 + gpui::point(
6508 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6509 line_y,
6510 );
6511
6512 (
6513 [token_offset, token_end_offset],
6514 Box::new(move |window: &mut Window, cx: &mut App| {
6515 invisible_symbol
6516 .paint(origin, line_height, window, cx)
6517 .log_err();
6518 }),
6519 )
6520 };
6521
6522 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6523 match whitespace_setting {
6524 ShowWhitespaceSetting::None => (),
6525 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6526 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6527 let invisible_point = DisplayPoint::new(row, start as u32);
6528 if !selection_ranges
6529 .iter()
6530 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6531 {
6532 return;
6533 }
6534
6535 paint(window, cx);
6536 }),
6537
6538 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6539 // - It is a tab
6540 // - It is adjacent to an edge (start or end)
6541 // - It is adjacent to a whitespace (left or right)
6542 ShowWhitespaceSetting::Boundary => {
6543 // 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
6544 // the above cases.
6545 // Note: We zip in the original `invisibles` to check for tab equality
6546 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6547 for (([start, end], paint), invisible) in
6548 invisible_iter.zip_eq(self.invisibles.iter())
6549 {
6550 let should_render = match (&last_seen, invisible) {
6551 (_, Invisible::Tab { .. }) => true,
6552 (Some((_, last_end, _)), _) => *last_end == start,
6553 _ => false,
6554 };
6555
6556 if should_render || start == 0 || end == self.len {
6557 paint(window, cx);
6558
6559 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6560 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6561 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6562 // Note that we need to make sure that the last one is actually adjacent
6563 if !should_render_last && last_end == start {
6564 paint_last(window, cx);
6565 }
6566 }
6567 }
6568
6569 // Manually render anything within a selection
6570 let invisible_point = DisplayPoint::new(row, start as u32);
6571 if selection_ranges.iter().any(|region| {
6572 region.start <= invisible_point && invisible_point < region.end
6573 }) {
6574 paint(window, cx);
6575 }
6576
6577 last_seen = Some((should_render, end, paint));
6578 }
6579 }
6580 }
6581 }
6582
6583 pub fn x_for_index(&self, index: usize) -> Pixels {
6584 let mut fragment_start_x = Pixels::ZERO;
6585 let mut fragment_start_index = 0;
6586
6587 for fragment in &self.fragments {
6588 match fragment {
6589 LineFragment::Text(shaped_line) => {
6590 let fragment_end_index = fragment_start_index + shaped_line.len;
6591 if index < fragment_end_index {
6592 return fragment_start_x
6593 + shaped_line.x_for_index(index - fragment_start_index);
6594 }
6595 fragment_start_x += shaped_line.width;
6596 fragment_start_index = fragment_end_index;
6597 }
6598 LineFragment::Element { len, size, .. } => {
6599 let fragment_end_index = fragment_start_index + len;
6600 if index < fragment_end_index {
6601 return fragment_start_x;
6602 }
6603 fragment_start_x += size.width;
6604 fragment_start_index = fragment_end_index;
6605 }
6606 }
6607 }
6608
6609 fragment_start_x
6610 }
6611
6612 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6613 let mut fragment_start_x = Pixels::ZERO;
6614 let mut fragment_start_index = 0;
6615
6616 for fragment in &self.fragments {
6617 match fragment {
6618 LineFragment::Text(shaped_line) => {
6619 let fragment_end_x = fragment_start_x + shaped_line.width;
6620 if x < fragment_end_x {
6621 return Some(
6622 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6623 );
6624 }
6625 fragment_start_x = fragment_end_x;
6626 fragment_start_index += shaped_line.len;
6627 }
6628 LineFragment::Element { len, size, .. } => {
6629 let fragment_end_x = fragment_start_x + size.width;
6630 if x < fragment_end_x {
6631 return Some(fragment_start_index);
6632 }
6633 fragment_start_index += len;
6634 fragment_start_x = fragment_end_x;
6635 }
6636 }
6637 }
6638
6639 None
6640 }
6641
6642 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6643 let mut fragment_start_index = 0;
6644
6645 for fragment in &self.fragments {
6646 match fragment {
6647 LineFragment::Text(shaped_line) => {
6648 let fragment_end_index = fragment_start_index + shaped_line.len;
6649 if index < fragment_end_index {
6650 return shaped_line.font_id_for_index(index - fragment_start_index);
6651 }
6652 fragment_start_index = fragment_end_index;
6653 }
6654 LineFragment::Element { len, .. } => {
6655 let fragment_end_index = fragment_start_index + len;
6656 if index < fragment_end_index {
6657 return None;
6658 }
6659 fragment_start_index = fragment_end_index;
6660 }
6661 }
6662 }
6663
6664 None
6665 }
6666}
6667
6668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6669enum Invisible {
6670 /// A tab character
6671 ///
6672 /// A tab character is internally represented by spaces (configured by the user's tab width)
6673 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6674 /// adjacency checks.
6675 Tab {
6676 line_start_offset: usize,
6677 line_end_offset: usize,
6678 },
6679 Whitespace {
6680 line_offset: usize,
6681 },
6682}
6683
6684impl EditorElement {
6685 /// Returns the rem size to use when rendering the [`EditorElement`].
6686 ///
6687 /// This allows UI elements to scale based on the `buffer_font_size`.
6688 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6689 match self.editor.read(cx).mode {
6690 EditorMode::Full => {
6691 let buffer_font_size = self.style.text.font_size;
6692 match buffer_font_size {
6693 AbsoluteLength::Pixels(pixels) => {
6694 let rem_size_scale = {
6695 // Our default UI font size is 14px on a 16px base scale.
6696 // This means the default UI font size is 0.875rems.
6697 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6698
6699 // We then determine the delta between a single rem and the default font
6700 // size scale.
6701 let default_font_size_delta = 1. - default_font_size_scale;
6702
6703 // Finally, we add this delta to 1rem to get the scale factor that
6704 // should be used to scale up the UI.
6705 1. + default_font_size_delta
6706 };
6707
6708 Some(pixels * rem_size_scale)
6709 }
6710 AbsoluteLength::Rems(rems) => {
6711 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6712 }
6713 }
6714 }
6715 // We currently use single-line and auto-height editors in UI contexts,
6716 // so we don't want to scale everything with the buffer font size, as it
6717 // ends up looking off.
6718 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6719 }
6720 }
6721}
6722
6723impl Element for EditorElement {
6724 type RequestLayoutState = ();
6725 type PrepaintState = EditorLayout;
6726
6727 fn id(&self) -> Option<ElementId> {
6728 None
6729 }
6730
6731 fn request_layout(
6732 &mut self,
6733 _: Option<&GlobalElementId>,
6734 window: &mut Window,
6735 cx: &mut App,
6736 ) -> (gpui::LayoutId, ()) {
6737 let rem_size = self.rem_size(cx);
6738 window.with_rem_size(rem_size, |window| {
6739 self.editor.update(cx, |editor, cx| {
6740 editor.set_style(self.style.clone(), window, cx);
6741
6742 let layout_id = match editor.mode {
6743 EditorMode::SingleLine { auto_width } => {
6744 let rem_size = window.rem_size();
6745
6746 let height = self.style.text.line_height_in_pixels(rem_size);
6747 if auto_width {
6748 let editor_handle = cx.entity().clone();
6749 let style = self.style.clone();
6750 window.request_measured_layout(
6751 Style::default(),
6752 move |_, _, window, cx| {
6753 let editor_snapshot = editor_handle
6754 .update(cx, |editor, cx| editor.snapshot(window, cx));
6755 let line = Self::layout_lines(
6756 DisplayRow(0)..DisplayRow(1),
6757 &editor_snapshot,
6758 &style,
6759 px(f32::MAX),
6760 |_| false, // Single lines never soft wrap
6761 window,
6762 cx,
6763 )
6764 .pop()
6765 .unwrap();
6766
6767 let font_id =
6768 window.text_system().resolve_font(&style.text.font());
6769 let font_size =
6770 style.text.font_size.to_pixels(window.rem_size());
6771 let em_width =
6772 window.text_system().em_width(font_id, font_size).unwrap();
6773
6774 size(line.width + em_width, height)
6775 },
6776 )
6777 } else {
6778 let mut style = Style::default();
6779 style.size.height = height.into();
6780 style.size.width = relative(1.).into();
6781 window.request_layout(style, None, cx)
6782 }
6783 }
6784 EditorMode::AutoHeight { max_lines } => {
6785 let editor_handle = cx.entity().clone();
6786 let max_line_number_width =
6787 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6788 window.request_measured_layout(
6789 Style::default(),
6790 move |known_dimensions, available_space, window, cx| {
6791 editor_handle
6792 .update(cx, |editor, cx| {
6793 compute_auto_height_layout(
6794 editor,
6795 max_lines,
6796 max_line_number_width,
6797 known_dimensions,
6798 available_space.width,
6799 window,
6800 cx,
6801 )
6802 })
6803 .unwrap_or_default()
6804 },
6805 )
6806 }
6807 EditorMode::Full => {
6808 let mut style = Style::default();
6809 style.size.width = relative(1.).into();
6810 style.size.height = relative(1.).into();
6811 window.request_layout(style, None, cx)
6812 }
6813 };
6814
6815 (layout_id, ())
6816 })
6817 })
6818 }
6819
6820 fn prepaint(
6821 &mut self,
6822 _: Option<&GlobalElementId>,
6823 bounds: Bounds<Pixels>,
6824 _: &mut Self::RequestLayoutState,
6825 window: &mut Window,
6826 cx: &mut App,
6827 ) -> Self::PrepaintState {
6828 let text_style = TextStyleRefinement {
6829 font_size: Some(self.style.text.font_size),
6830 line_height: Some(self.style.text.line_height),
6831 ..Default::default()
6832 };
6833 let focus_handle = self.editor.focus_handle(cx);
6834 window.set_view_id(self.editor.entity_id());
6835 window.set_focus_handle(&focus_handle, cx);
6836
6837 let rem_size = self.rem_size(cx);
6838 window.with_rem_size(rem_size, |window| {
6839 window.with_text_style(Some(text_style), |window| {
6840 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6841 let mut snapshot = self
6842 .editor
6843 .update(cx, |editor, cx| editor.snapshot(window, cx));
6844 let style = self.style.clone();
6845
6846 let font_id = window.text_system().resolve_font(&style.text.font());
6847 let font_size = style.text.font_size.to_pixels(window.rem_size());
6848 let line_height = style.text.line_height_in_pixels(window.rem_size());
6849 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6850 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6851
6852 let letter_size = size(em_width, line_height);
6853
6854 let gutter_dimensions = snapshot
6855 .gutter_dimensions(
6856 font_id,
6857 font_size,
6858 self.max_line_number_width(&snapshot, window, cx),
6859 cx,
6860 )
6861 .unwrap_or_default();
6862 let text_width = bounds.size.width - gutter_dimensions.width;
6863
6864 let editor_width =
6865 text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6866
6867 snapshot = self.editor.update(cx, |editor, cx| {
6868 editor.last_bounds = Some(bounds);
6869 editor.gutter_dimensions = gutter_dimensions;
6870 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6871
6872 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6873 snapshot
6874 } else {
6875 let wrap_width = match editor.soft_wrap_mode(cx) {
6876 SoftWrap::GitDiff => None,
6877 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6878 SoftWrap::EditorWidth => Some(editor_width),
6879 SoftWrap::Column(column) => Some(column as f32 * em_advance),
6880 SoftWrap::Bounded(column) => {
6881 Some(editor_width.min(column as f32 * em_advance))
6882 }
6883 };
6884
6885 if editor.set_wrap_width(wrap_width, cx) {
6886 editor.snapshot(window, cx)
6887 } else {
6888 snapshot
6889 }
6890 }
6891 });
6892
6893 let wrap_guides = self
6894 .editor
6895 .read(cx)
6896 .wrap_guides(cx)
6897 .iter()
6898 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6899 .collect::<SmallVec<[_; 2]>>();
6900
6901 let hitbox = window.insert_hitbox(bounds, false);
6902 let gutter_hitbox =
6903 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6904 let text_hitbox = window.insert_hitbox(
6905 Bounds {
6906 origin: gutter_hitbox.top_right(),
6907 size: size(text_width, bounds.size.height),
6908 },
6909 false,
6910 );
6911 // Offset the content_bounds from the text_bounds by the gutter margin (which
6912 // is roughly half a character wide) to make hit testing work more like how we want.
6913 let content_origin =
6914 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6915
6916 let scrollbar_bounds =
6917 Bounds::from_corners(content_origin, bounds.bottom_right());
6918
6919 let height_in_lines = scrollbar_bounds.size.height / line_height;
6920
6921 // NOTE: The max row number in the current file, minus one
6922 let max_row = snapshot.max_point().row().as_f32();
6923
6924 // NOTE: The max scroll position for the top of the window
6925 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6926 (max_row - height_in_lines + 1.).max(0.)
6927 } else {
6928 let settings = EditorSettings::get_global(cx);
6929 match settings.scroll_beyond_last_line {
6930 ScrollBeyondLastLine::OnePage => max_row,
6931 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6932 ScrollBeyondLastLine::VerticalScrollMargin => {
6933 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6934 .max(0.)
6935 }
6936 }
6937 };
6938
6939 // TODO: Autoscrolling for both axes
6940 let mut autoscroll_request = None;
6941 let mut autoscroll_containing_element = false;
6942 let mut autoscroll_horizontally = false;
6943 self.editor.update(cx, |editor, cx| {
6944 autoscroll_request = editor.autoscroll_request();
6945 autoscroll_containing_element =
6946 autoscroll_request.is_some() || editor.has_pending_selection();
6947 // TODO: Is this horizontal or vertical?!
6948 autoscroll_horizontally = editor.autoscroll_vertically(
6949 bounds,
6950 line_height,
6951 max_scroll_top,
6952 window,
6953 cx,
6954 );
6955 snapshot = editor.snapshot(window, cx);
6956 });
6957
6958 let mut scroll_position = snapshot.scroll_position();
6959 // The scroll position is a fractional point, the whole number of which represents
6960 // the top of the window in terms of display rows.
6961 let start_row = DisplayRow(scroll_position.y as u32);
6962 let max_row = snapshot.max_point().row();
6963 let end_row = cmp::min(
6964 (scroll_position.y + height_in_lines).ceil() as u32,
6965 max_row.next_row().0,
6966 );
6967 let end_row = DisplayRow(end_row);
6968
6969 let row_infos = snapshot
6970 .row_infos(start_row)
6971 .take((start_row..end_row).len())
6972 .collect::<Vec<RowInfo>>();
6973 let is_row_soft_wrapped = |row: usize| {
6974 row_infos
6975 .get(row)
6976 .map_or(true, |info| info.buffer_row.is_none())
6977 };
6978
6979 let start_anchor = if start_row == Default::default() {
6980 Anchor::min()
6981 } else {
6982 snapshot.buffer_snapshot.anchor_before(
6983 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6984 )
6985 };
6986 let end_anchor = if end_row > max_row {
6987 Anchor::max()
6988 } else {
6989 snapshot.buffer_snapshot.anchor_before(
6990 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6991 )
6992 };
6993
6994 let mut highlighted_rows = self
6995 .editor
6996 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6997
6998 for (ix, row_info) in row_infos.iter().enumerate() {
6999 let background = match row_info.diff_status {
7000 Some(DiffHunkStatus::Added(_)) => {
7001 cx.theme().colors().version_control_added_background
7002 }
7003 Some(DiffHunkStatus::Removed(_)) => {
7004 cx.theme().colors().version_control_deleted_background
7005 }
7006 _ => continue,
7007 };
7008
7009 highlighted_rows
7010 .entry(start_row + DisplayRow(ix as u32))
7011 .or_insert(background);
7012 }
7013
7014 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
7015 start_anchor..end_anchor,
7016 &snapshot.display_snapshot,
7017 cx.theme().colors(),
7018 );
7019 let highlighted_gutter_ranges =
7020 self.editor.read(cx).gutter_highlights_in_range(
7021 start_anchor..end_anchor,
7022 &snapshot.display_snapshot,
7023 cx,
7024 );
7025
7026 let redacted_ranges = self.editor.read(cx).redacted_ranges(
7027 start_anchor..end_anchor,
7028 &snapshot.display_snapshot,
7029 cx,
7030 );
7031
7032 let (local_selections, selected_buffer_ids): (
7033 Vec<Selection<Point>>,
7034 Vec<BufferId>,
7035 ) = self.editor.update(cx, |editor, cx| {
7036 let all_selections = editor.selections.all::<Point>(cx);
7037 let selected_buffer_ids = if editor.is_singleton(cx) {
7038 Vec::new()
7039 } else {
7040 let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
7041
7042 for selection in all_selections {
7043 for buffer_id in snapshot
7044 .buffer_snapshot
7045 .buffer_ids_for_range(selection.range())
7046 {
7047 if selected_buffer_ids.last() != Some(&buffer_id) {
7048 selected_buffer_ids.push(buffer_id);
7049 }
7050 }
7051 }
7052
7053 selected_buffer_ids
7054 };
7055
7056 let mut selections = editor
7057 .selections
7058 .disjoint_in_range(start_anchor..end_anchor, cx);
7059 selections.extend(editor.selections.pending(cx));
7060
7061 (selections, selected_buffer_ids)
7062 });
7063
7064 let (selections, active_rows, newest_selection_head) = self.layout_selections(
7065 start_anchor,
7066 end_anchor,
7067 &local_selections,
7068 &snapshot,
7069 start_row,
7070 end_row,
7071 window,
7072 cx,
7073 );
7074
7075 let line_numbers = self.layout_line_numbers(
7076 Some(&gutter_hitbox),
7077 gutter_dimensions,
7078 line_height,
7079 scroll_position,
7080 start_row..end_row,
7081 &row_infos,
7082 newest_selection_head,
7083 &snapshot,
7084 window,
7085 cx,
7086 );
7087
7088 let mut crease_toggles =
7089 window.with_element_namespace("crease_toggles", |window| {
7090 self.layout_crease_toggles(
7091 start_row..end_row,
7092 &row_infos,
7093 &active_rows,
7094 &snapshot,
7095 window,
7096 cx,
7097 )
7098 });
7099 let crease_trailers =
7100 window.with_element_namespace("crease_trailers", |window| {
7101 self.layout_crease_trailers(
7102 row_infos.iter().copied(),
7103 &snapshot,
7104 window,
7105 cx,
7106 )
7107 });
7108
7109 let display_hunks = self.layout_gutter_diff_hunks(
7110 line_height,
7111 &gutter_hitbox,
7112 start_row..end_row,
7113 &snapshot,
7114 window,
7115 cx,
7116 );
7117
7118 let mut line_layouts = Self::layout_lines(
7119 start_row..end_row,
7120 &snapshot,
7121 &self.style,
7122 editor_width,
7123 is_row_soft_wrapped,
7124 window,
7125 cx,
7126 );
7127
7128 let longest_line_blame_width = self
7129 .editor
7130 .update(cx, |editor, cx| {
7131 if !editor.show_git_blame_inline {
7132 return None;
7133 }
7134 let blame = editor.blame.as_ref()?;
7135 let blame_entry = blame
7136 .update(cx, |blame, cx| {
7137 let row_infos =
7138 snapshot.row_infos(snapshot.longest_row()).next()?;
7139 blame.blame_for_rows(&[row_infos], cx).next()
7140 })
7141 .flatten()?;
7142 let workspace = editor.workspace.as_ref().map(|(w, _)| w.to_owned());
7143 let mut element = render_inline_blame_entry(
7144 blame,
7145 blame_entry,
7146 &style,
7147 workspace,
7148 cx,
7149 );
7150 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7151 Some(
7152 element
7153 .layout_as_root(AvailableSpace::min_size(), window, cx)
7154 .width
7155 + inline_blame_padding,
7156 )
7157 })
7158 .unwrap_or(Pixels::ZERO);
7159
7160 let longest_line_width = layout_line(
7161 snapshot.longest_row(),
7162 &snapshot,
7163 &style,
7164 editor_width,
7165 is_row_soft_wrapped,
7166 window,
7167 cx,
7168 )
7169 .width;
7170
7171 let scrollbar_range_data = ScrollbarRangeData::new(
7172 scrollbar_bounds,
7173 letter_size,
7174 &snapshot,
7175 longest_line_width,
7176 longest_line_blame_width,
7177 &style,
7178 editor_width,
7179 cx,
7180 );
7181
7182 let scroll_range_bounds = scrollbar_range_data.scroll_range;
7183 let mut scroll_width = scroll_range_bounds.size.width;
7184
7185 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7186 snapshot.sticky_header_excerpt(start_row)
7187 } else {
7188 None
7189 };
7190 let sticky_header_excerpt_id =
7191 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7192
7193 let blocks = window.with_element_namespace("blocks", |window| {
7194 self.render_blocks(
7195 start_row..end_row,
7196 &snapshot,
7197 &hitbox,
7198 &text_hitbox,
7199 editor_width,
7200 &mut scroll_width,
7201 &gutter_dimensions,
7202 em_width,
7203 gutter_dimensions.full_width(),
7204 line_height,
7205 &line_layouts,
7206 &local_selections,
7207 &selected_buffer_ids,
7208 is_row_soft_wrapped,
7209 sticky_header_excerpt_id,
7210 window,
7211 cx,
7212 )
7213 });
7214 let mut blocks = match blocks {
7215 Ok(blocks) => blocks,
7216 Err(resized_blocks) => {
7217 self.editor.update(cx, |editor, cx| {
7218 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7219 });
7220 return self.prepaint(None, bounds, &mut (), window, cx);
7221 }
7222 };
7223
7224 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7225 window.with_element_namespace("blocks", |window| {
7226 self.layout_sticky_buffer_header(
7227 sticky_header_excerpt,
7228 scroll_position.y,
7229 line_height,
7230 &snapshot,
7231 &hitbox,
7232 &selected_buffer_ids,
7233 window,
7234 cx,
7235 )
7236 })
7237 });
7238
7239 let start_buffer_row =
7240 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7241 let end_buffer_row =
7242 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7243
7244 let scroll_max = point(
7245 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7246 max_row.as_f32(),
7247 );
7248
7249 self.editor.update(cx, |editor, cx| {
7250 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7251
7252 let autoscrolled = if autoscroll_horizontally {
7253 editor.autoscroll_horizontally(
7254 start_row,
7255 editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7256 scroll_width,
7257 em_width,
7258 &line_layouts,
7259 cx,
7260 )
7261 } else {
7262 false
7263 };
7264
7265 if clamped || autoscrolled {
7266 snapshot = editor.snapshot(window, cx);
7267 scroll_position = snapshot.scroll_position();
7268 }
7269 });
7270
7271 let scroll_pixel_position = point(
7272 scroll_position.x * em_width,
7273 scroll_position.y * line_height,
7274 );
7275
7276 let indent_guides = self.layout_indent_guides(
7277 content_origin,
7278 text_hitbox.origin,
7279 start_buffer_row..end_buffer_row,
7280 scroll_pixel_position,
7281 line_height,
7282 &snapshot,
7283 window,
7284 cx,
7285 );
7286
7287 let crease_trailers =
7288 window.with_element_namespace("crease_trailers", |window| {
7289 self.prepaint_crease_trailers(
7290 crease_trailers,
7291 &line_layouts,
7292 line_height,
7293 content_origin,
7294 scroll_pixel_position,
7295 em_width,
7296 window,
7297 cx,
7298 )
7299 });
7300
7301 let mut inline_blame = None;
7302 if let Some(newest_selection_head) = newest_selection_head {
7303 let display_row = newest_selection_head.row();
7304 if (start_row..end_row).contains(&display_row) {
7305 let line_ix = display_row.minus(start_row) as usize;
7306 let row_info = &row_infos[line_ix];
7307 let line_layout = &line_layouts[line_ix];
7308 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7309 inline_blame = self.layout_inline_blame(
7310 display_row,
7311 row_info,
7312 line_layout,
7313 crease_trailer_layout,
7314 em_width,
7315 content_origin,
7316 scroll_pixel_position,
7317 line_height,
7318 window,
7319 cx,
7320 );
7321 }
7322 }
7323
7324 let blamed_display_rows = self.layout_blame_entries(
7325 &row_infos,
7326 em_width,
7327 scroll_position,
7328 line_height,
7329 &gutter_hitbox,
7330 gutter_dimensions.git_blame_entries_width,
7331 window,
7332 cx,
7333 );
7334
7335 let scroll_max = point(
7336 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7337 max_scroll_top,
7338 );
7339
7340 self.editor.update(cx, |editor, cx| {
7341 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7342
7343 let autoscrolled = if autoscroll_horizontally {
7344 editor.autoscroll_horizontally(
7345 start_row,
7346 editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7347 scroll_width,
7348 em_width,
7349 &line_layouts,
7350 cx,
7351 )
7352 } else {
7353 false
7354 };
7355
7356 if clamped || autoscrolled {
7357 snapshot = editor.snapshot(window, cx);
7358 scroll_position = snapshot.scroll_position();
7359 }
7360 });
7361
7362 let line_elements = self.prepaint_lines(
7363 start_row,
7364 &mut line_layouts,
7365 line_height,
7366 scroll_pixel_position,
7367 content_origin,
7368 window,
7369 cx,
7370 );
7371
7372 let mut block_start_rows = HashSet::default();
7373
7374 window.with_element_namespace("blocks", |window| {
7375 self.layout_blocks(
7376 &mut blocks,
7377 &mut block_start_rows,
7378 &hitbox,
7379 line_height,
7380 scroll_pixel_position,
7381 window,
7382 cx,
7383 );
7384 });
7385
7386 let cursors = self.collect_cursors(&snapshot, cx);
7387 let visible_row_range = start_row..end_row;
7388 let non_visible_cursors = cursors
7389 .iter()
7390 .any(|c| !visible_row_range.contains(&c.0.row()));
7391
7392 let visible_cursors = self.layout_visible_cursors(
7393 &snapshot,
7394 &selections,
7395 &block_start_rows,
7396 start_row..end_row,
7397 &line_layouts,
7398 &text_hitbox,
7399 content_origin,
7400 scroll_position,
7401 scroll_pixel_position,
7402 line_height,
7403 em_width,
7404 em_advance,
7405 autoscroll_containing_element,
7406 window,
7407 cx,
7408 );
7409
7410 let scrollbars_layout = self.layout_scrollbars(
7411 &snapshot,
7412 scrollbar_range_data,
7413 scroll_position,
7414 non_visible_cursors,
7415 window,
7416 cx,
7417 );
7418
7419 let gutter_settings = EditorSettings::get_global(cx).gutter;
7420
7421 let rows_with_hunk_bounds = display_hunks
7422 .iter()
7423 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7424 .fold(
7425 HashMap::default(),
7426 |mut rows_with_hunk_bounds, (hunk, bounds)| {
7427 match hunk {
7428 DisplayDiffHunk::Folded { display_row } => {
7429 rows_with_hunk_bounds.insert(*display_row, bounds);
7430 }
7431 DisplayDiffHunk::Unfolded {
7432 display_row_range, ..
7433 } => {
7434 for display_row in display_row_range.iter_rows() {
7435 rows_with_hunk_bounds.insert(display_row, bounds);
7436 }
7437 }
7438 }
7439 rows_with_hunk_bounds
7440 },
7441 );
7442 let mut code_actions_indicator = None;
7443 if let Some(newest_selection_head) = newest_selection_head {
7444 let newest_selection_point =
7445 newest_selection_head.to_point(&snapshot.display_snapshot);
7446
7447 if (start_row..end_row).contains(&newest_selection_head.row()) {
7448 self.layout_cursor_popovers(
7449 line_height,
7450 &text_hitbox,
7451 content_origin,
7452 start_row,
7453 scroll_pixel_position,
7454 &line_layouts,
7455 newest_selection_head,
7456 newest_selection_point,
7457 &style,
7458 window,
7459 cx,
7460 );
7461
7462 let show_code_actions = snapshot
7463 .show_code_actions
7464 .unwrap_or(gutter_settings.code_actions);
7465 if show_code_actions {
7466 let newest_selection_point =
7467 newest_selection_head.to_point(&snapshot.display_snapshot);
7468 if !snapshot
7469 .is_line_folded(MultiBufferRow(newest_selection_point.row))
7470 {
7471 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7472 MultiBufferRow(newest_selection_point.row),
7473 );
7474 if let Some((buffer, range)) = buffer {
7475 let buffer_id = buffer.remote_id();
7476 let row = range.start.row;
7477 let has_test_indicator = self
7478 .editor
7479 .read(cx)
7480 .tasks
7481 .contains_key(&(buffer_id, row));
7482
7483 if !has_test_indicator {
7484 code_actions_indicator = self
7485 .layout_code_actions_indicator(
7486 line_height,
7487 newest_selection_head,
7488 scroll_pixel_position,
7489 &gutter_dimensions,
7490 &gutter_hitbox,
7491 &rows_with_hunk_bounds,
7492 window,
7493 cx,
7494 );
7495 }
7496 }
7497 }
7498 }
7499 }
7500 }
7501
7502 self.layout_gutter_menu(
7503 line_height,
7504 &text_hitbox,
7505 content_origin,
7506 scroll_pixel_position,
7507 gutter_dimensions.width - gutter_dimensions.left_padding,
7508 window,
7509 cx,
7510 );
7511
7512 let test_indicators = if gutter_settings.runnables {
7513 self.layout_run_indicators(
7514 line_height,
7515 start_row..end_row,
7516 scroll_pixel_position,
7517 &gutter_dimensions,
7518 &gutter_hitbox,
7519 &rows_with_hunk_bounds,
7520 &snapshot,
7521 window,
7522 cx,
7523 )
7524 } else {
7525 Vec::new()
7526 };
7527
7528 self.layout_signature_help(
7529 &hitbox,
7530 content_origin,
7531 scroll_pixel_position,
7532 newest_selection_head,
7533 start_row,
7534 &line_layouts,
7535 line_height,
7536 em_width,
7537 window,
7538 cx,
7539 );
7540
7541 if !cx.has_active_drag() {
7542 self.layout_hover_popovers(
7543 &snapshot,
7544 &hitbox,
7545 &text_hitbox,
7546 start_row..end_row,
7547 content_origin,
7548 scroll_pixel_position,
7549 &line_layouts,
7550 line_height,
7551 em_width,
7552 window,
7553 cx,
7554 );
7555 }
7556
7557 let inline_completion_popover = self.layout_edit_prediction_popover(
7558 &text_hitbox.bounds,
7559 content_origin,
7560 &snapshot,
7561 start_row..end_row,
7562 scroll_position.y,
7563 scroll_position.y + height_in_lines,
7564 &line_layouts,
7565 line_height,
7566 scroll_pixel_position,
7567 newest_selection_head,
7568 editor_width,
7569 &style,
7570 window,
7571 cx,
7572 );
7573
7574 let mouse_context_menu = self.layout_mouse_context_menu(
7575 &snapshot,
7576 start_row..end_row,
7577 content_origin,
7578 window,
7579 cx,
7580 );
7581
7582 window.with_element_namespace("crease_toggles", |window| {
7583 self.prepaint_crease_toggles(
7584 &mut crease_toggles,
7585 line_height,
7586 &gutter_dimensions,
7587 gutter_settings,
7588 scroll_pixel_position,
7589 &gutter_hitbox,
7590 window,
7591 cx,
7592 )
7593 });
7594
7595 let invisible_symbol_font_size = font_size / 2.;
7596 let tab_invisible = window
7597 .text_system()
7598 .shape_line(
7599 "→".into(),
7600 invisible_symbol_font_size,
7601 &[TextRun {
7602 len: "→".len(),
7603 font: self.style.text.font(),
7604 color: cx.theme().colors().editor_invisible,
7605 background_color: None,
7606 underline: None,
7607 strikethrough: None,
7608 }],
7609 )
7610 .unwrap();
7611 let space_invisible = window
7612 .text_system()
7613 .shape_line(
7614 "•".into(),
7615 invisible_symbol_font_size,
7616 &[TextRun {
7617 len: "•".len(),
7618 font: self.style.text.font(),
7619 color: cx.theme().colors().editor_invisible,
7620 background_color: None,
7621 underline: None,
7622 strikethrough: None,
7623 }],
7624 )
7625 .unwrap();
7626
7627 let mode = snapshot.mode;
7628
7629 let position_map = Rc::new(PositionMap {
7630 size: bounds.size,
7631 visible_row_range,
7632 scroll_pixel_position,
7633 scroll_max,
7634 line_layouts,
7635 line_height,
7636 em_width,
7637 em_advance,
7638 snapshot,
7639 gutter_hitbox: gutter_hitbox.clone(),
7640 text_hitbox: text_hitbox.clone(),
7641 });
7642
7643 self.editor.update(cx, |editor, _| {
7644 editor.last_position_map = Some(position_map.clone())
7645 });
7646
7647 let hunk_controls = self.layout_diff_hunk_controls(
7648 start_row..end_row,
7649 &row_infos,
7650 &text_hitbox,
7651 &position_map,
7652 newest_selection_head,
7653 line_height,
7654 scroll_pixel_position,
7655 &display_hunks,
7656 self.editor.clone(),
7657 window,
7658 cx,
7659 );
7660
7661 EditorLayout {
7662 mode,
7663 position_map,
7664 visible_display_row_range: start_row..end_row,
7665 wrap_guides,
7666 indent_guides,
7667 hitbox,
7668 gutter_hitbox,
7669 display_hunks,
7670 content_origin,
7671 scrollbars_layout,
7672 active_rows,
7673 highlighted_rows,
7674 highlighted_ranges,
7675 highlighted_gutter_ranges,
7676 redacted_ranges,
7677 line_elements,
7678 line_numbers,
7679 blamed_display_rows,
7680 inline_blame,
7681 blocks,
7682 cursors,
7683 visible_cursors,
7684 selections,
7685 inline_completion_popover,
7686 diff_hunk_controls: hunk_controls,
7687 mouse_context_menu,
7688 test_indicators,
7689 code_actions_indicator,
7690 crease_toggles,
7691 crease_trailers,
7692 tab_invisible,
7693 space_invisible,
7694 sticky_buffer_header,
7695 }
7696 })
7697 })
7698 })
7699 }
7700
7701 fn paint(
7702 &mut self,
7703 _: Option<&GlobalElementId>,
7704 bounds: Bounds<gpui::Pixels>,
7705 _: &mut Self::RequestLayoutState,
7706 layout: &mut Self::PrepaintState,
7707 window: &mut Window,
7708 cx: &mut App,
7709 ) {
7710 let focus_handle = self.editor.focus_handle(cx);
7711 let key_context = self
7712 .editor
7713 .update(cx, |editor, cx| editor.key_context(window, cx));
7714
7715 window.set_key_context(key_context);
7716 window.handle_input(
7717 &focus_handle,
7718 ElementInputHandler::new(bounds, self.editor.clone()),
7719 cx,
7720 );
7721 self.register_actions(window, cx);
7722 self.register_key_listeners(window, cx, layout);
7723
7724 let text_style = TextStyleRefinement {
7725 font_size: Some(self.style.text.font_size),
7726 line_height: Some(self.style.text.line_height),
7727 ..Default::default()
7728 };
7729 let rem_size = self.rem_size(cx);
7730 window.with_rem_size(rem_size, |window| {
7731 window.with_text_style(Some(text_style), |window| {
7732 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7733 self.paint_mouse_listeners(layout, window, cx);
7734 self.paint_background(layout, window, cx);
7735 self.paint_indent_guides(layout, window, cx);
7736
7737 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7738 self.paint_blamed_display_rows(layout, window, cx);
7739 self.paint_line_numbers(layout, window, cx);
7740 }
7741
7742 self.paint_text(layout, window, cx);
7743
7744 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7745 self.paint_gutter_highlights(layout, window, cx);
7746 self.paint_gutter_indicators(layout, window, cx);
7747 }
7748
7749 if !layout.blocks.is_empty() {
7750 window.with_element_namespace("blocks", |window| {
7751 self.paint_blocks(layout, window, cx);
7752 });
7753 }
7754
7755 window.with_element_namespace("blocks", |window| {
7756 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7757 sticky_header.paint(window, cx)
7758 }
7759 });
7760
7761 self.paint_scrollbars(layout, window, cx);
7762 self.paint_inline_completion_popover(layout, window, cx);
7763 self.paint_mouse_context_menu(layout, window, cx);
7764 });
7765 })
7766 })
7767 }
7768}
7769
7770pub(super) fn gutter_bounds(
7771 editor_bounds: Bounds<Pixels>,
7772 gutter_dimensions: GutterDimensions,
7773) -> Bounds<Pixels> {
7774 Bounds {
7775 origin: editor_bounds.origin,
7776 size: size(gutter_dimensions.width, editor_bounds.size.height),
7777 }
7778}
7779
7780struct ScrollbarRangeData {
7781 scrollbar_bounds: Bounds<Pixels>,
7782 scroll_range: Bounds<Pixels>,
7783 letter_size: Size<Pixels>,
7784}
7785
7786impl ScrollbarRangeData {
7787 #[allow(clippy::too_many_arguments)]
7788 pub fn new(
7789 scrollbar_bounds: Bounds<Pixels>,
7790 letter_size: Size<Pixels>,
7791 snapshot: &EditorSnapshot,
7792 longest_line_width: Pixels,
7793 longest_line_blame_width: Pixels,
7794 style: &EditorStyle,
7795 editor_width: Pixels,
7796 cx: &mut App,
7797 ) -> ScrollbarRangeData {
7798 // TODO: Simplify this function down, it requires a lot of parameters
7799 let max_row = snapshot.max_point().row();
7800 let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7801
7802 let settings = EditorSettings::get_global(cx);
7803 let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7804 ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7805 ScrollBeyondLastLine::Off => px(1.),
7806 ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7807 };
7808
7809 let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7810 letter_size.width + style.scrollbar_width
7811 } else {
7812 px(0.0)
7813 };
7814
7815 let overscroll = size(
7816 right_margin + longest_line_blame_width,
7817 letter_size.height * scroll_beyond_last_line,
7818 );
7819
7820 let scroll_range = Bounds {
7821 origin: scrollbar_bounds.origin,
7822 size: text_bounds_size + overscroll,
7823 };
7824
7825 ScrollbarRangeData {
7826 scrollbar_bounds,
7827 scroll_range,
7828 letter_size,
7829 }
7830 }
7831}
7832
7833impl IntoElement for EditorElement {
7834 type Element = Self;
7835
7836 fn into_element(self) -> Self::Element {
7837 self
7838 }
7839}
7840
7841pub struct EditorLayout {
7842 position_map: Rc<PositionMap>,
7843 hitbox: Hitbox,
7844 gutter_hitbox: Hitbox,
7845 content_origin: gpui::Point<Pixels>,
7846 scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7847 mode: EditorMode,
7848 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7849 indent_guides: Option<Vec<IndentGuideLayout>>,
7850 visible_display_row_range: Range<DisplayRow>,
7851 active_rows: BTreeMap<DisplayRow, bool>,
7852 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
7853 line_elements: SmallVec<[AnyElement; 1]>,
7854 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7855 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7856 blamed_display_rows: Option<Vec<AnyElement>>,
7857 inline_blame: Option<AnyElement>,
7858 blocks: Vec<BlockLayout>,
7859 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7860 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7861 redacted_ranges: Vec<Range<DisplayPoint>>,
7862 cursors: Vec<(DisplayPoint, Hsla)>,
7863 visible_cursors: Vec<CursorLayout>,
7864 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7865 code_actions_indicator: Option<AnyElement>,
7866 test_indicators: Vec<AnyElement>,
7867 crease_toggles: Vec<Option<AnyElement>>,
7868 diff_hunk_controls: Vec<AnyElement>,
7869 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7870 inline_completion_popover: Option<AnyElement>,
7871 mouse_context_menu: Option<AnyElement>,
7872 tab_invisible: ShapedLine,
7873 space_invisible: ShapedLine,
7874 sticky_buffer_header: Option<AnyElement>,
7875}
7876
7877impl EditorLayout {
7878 fn line_end_overshoot(&self) -> Pixels {
7879 0.15 * self.position_map.line_height
7880 }
7881}
7882
7883struct LineNumberLayout {
7884 shaped_line: ShapedLine,
7885 hitbox: Option<Hitbox>,
7886 display_row: DisplayRow,
7887}
7888
7889struct ColoredRange<T> {
7890 start: T,
7891 end: T,
7892 color: Hsla,
7893}
7894
7895#[derive(Clone)]
7896struct ScrollbarLayout {
7897 hitbox: Hitbox,
7898 visible_range: Range<f32>,
7899 visible: bool,
7900 text_unit_size: Pixels,
7901 thumb_size: Pixels,
7902 axis: Axis,
7903}
7904
7905impl ScrollbarLayout {
7906 const BORDER_WIDTH: Pixels = px(1.0);
7907 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7908 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7909 // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7910
7911 fn thumb_bounds(&self) -> Bounds<Pixels> {
7912 match self.axis {
7913 Axis::Vertical => {
7914 let thumb_top = self.y_for_row(self.visible_range.start);
7915 let thumb_bottom = thumb_top + self.thumb_size;
7916 Bounds::from_corners(
7917 point(self.hitbox.left(), thumb_top),
7918 point(self.hitbox.right(), thumb_bottom),
7919 )
7920 }
7921 Axis::Horizontal => {
7922 let thumb_left =
7923 self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7924 let thumb_right = thumb_left + self.thumb_size;
7925 Bounds::from_corners(
7926 point(thumb_left, self.hitbox.top()),
7927 point(thumb_right, self.hitbox.bottom()),
7928 )
7929 }
7930 }
7931 }
7932
7933 fn y_for_row(&self, row: f32) -> Pixels {
7934 self.hitbox.top() + row * self.text_unit_size
7935 }
7936
7937 fn marker_quads_for_ranges(
7938 &self,
7939 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7940 column: Option<usize>,
7941 ) -> Vec<PaintQuad> {
7942 struct MinMax {
7943 min: Pixels,
7944 max: Pixels,
7945 }
7946 let (x_range, height_limit) = if let Some(column) = column {
7947 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7948 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7949 let end = start + column_width;
7950 (
7951 Range { start, end },
7952 MinMax {
7953 min: Self::MIN_MARKER_HEIGHT,
7954 max: px(f32::MAX),
7955 },
7956 )
7957 } else {
7958 (
7959 Range {
7960 start: Self::BORDER_WIDTH,
7961 end: self.hitbox.size.width,
7962 },
7963 MinMax {
7964 min: Self::LINE_MARKER_HEIGHT,
7965 max: Self::LINE_MARKER_HEIGHT,
7966 },
7967 )
7968 };
7969
7970 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7971 let mut pixel_ranges = row_ranges
7972 .into_iter()
7973 .map(|range| {
7974 let start_y = row_to_y(range.start);
7975 let end_y = row_to_y(range.end)
7976 + self
7977 .text_unit_size
7978 .max(height_limit.min)
7979 .min(height_limit.max);
7980 ColoredRange {
7981 start: start_y,
7982 end: end_y,
7983 color: range.color,
7984 }
7985 })
7986 .peekable();
7987
7988 let mut quads = Vec::new();
7989 while let Some(mut pixel_range) = pixel_ranges.next() {
7990 while let Some(next_pixel_range) = pixel_ranges.peek() {
7991 if pixel_range.end >= next_pixel_range.start - px(1.0)
7992 && pixel_range.color == next_pixel_range.color
7993 {
7994 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7995 pixel_ranges.next();
7996 } else {
7997 break;
7998 }
7999 }
8000
8001 let bounds = Bounds::from_corners(
8002 point(x_range.start, pixel_range.start),
8003 point(x_range.end, pixel_range.end),
8004 );
8005 quads.push(quad(
8006 bounds,
8007 Corners::default(),
8008 pixel_range.color,
8009 Edges::default(),
8010 Hsla::transparent_black(),
8011 ));
8012 }
8013
8014 quads
8015 }
8016}
8017
8018struct CreaseTrailerLayout {
8019 element: AnyElement,
8020 bounds: Bounds<Pixels>,
8021}
8022
8023pub(crate) struct PositionMap {
8024 pub size: Size<Pixels>,
8025 pub line_height: Pixels,
8026 pub scroll_pixel_position: gpui::Point<Pixels>,
8027 pub scroll_max: gpui::Point<f32>,
8028 pub em_width: Pixels,
8029 pub em_advance: Pixels,
8030 pub visible_row_range: Range<DisplayRow>,
8031 pub line_layouts: Vec<LineWithInvisibles>,
8032 pub snapshot: EditorSnapshot,
8033 pub text_hitbox: Hitbox,
8034 pub gutter_hitbox: Hitbox,
8035}
8036
8037#[derive(Debug, Copy, Clone)]
8038pub struct PointForPosition {
8039 pub previous_valid: DisplayPoint,
8040 pub next_valid: DisplayPoint,
8041 pub exact_unclipped: DisplayPoint,
8042 pub column_overshoot_after_line_end: u32,
8043}
8044
8045impl PointForPosition {
8046 pub fn as_valid(&self) -> Option<DisplayPoint> {
8047 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8048 Some(self.previous_valid)
8049 } else {
8050 None
8051 }
8052 }
8053}
8054
8055impl PositionMap {
8056 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8057 let text_bounds = self.text_hitbox.bounds;
8058 let scroll_position = self.snapshot.scroll_position();
8059 let position = position - text_bounds.origin;
8060 let y = position.y.max(px(0.)).min(self.size.height);
8061 let x = position.x + (scroll_position.x * self.em_width);
8062 let row = ((y / self.line_height) + scroll_position.y) as u32;
8063
8064 let (column, x_overshoot_after_line_end) = if let Some(line) = self
8065 .line_layouts
8066 .get(row as usize - scroll_position.y as usize)
8067 {
8068 if let Some(ix) = line.index_for_x(x) {
8069 (ix as u32, px(0.))
8070 } else {
8071 (line.len as u32, px(0.).max(x - line.width))
8072 }
8073 } else {
8074 (0, x)
8075 };
8076
8077 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8078 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8079 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8080
8081 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8082 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8083 PointForPosition {
8084 previous_valid,
8085 next_valid,
8086 exact_unclipped,
8087 column_overshoot_after_line_end,
8088 }
8089 }
8090}
8091
8092struct BlockLayout {
8093 id: BlockId,
8094 row: Option<DisplayRow>,
8095 element: AnyElement,
8096 available_space: Size<AvailableSpace>,
8097 style: BlockStyle,
8098}
8099
8100fn layout_line(
8101 row: DisplayRow,
8102 snapshot: &EditorSnapshot,
8103 style: &EditorStyle,
8104 text_width: Pixels,
8105 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8106 window: &mut Window,
8107 cx: &mut App,
8108) -> LineWithInvisibles {
8109 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8110 LineWithInvisibles::from_chunks(
8111 chunks,
8112 &style,
8113 MAX_LINE_LEN,
8114 1,
8115 snapshot.mode,
8116 text_width,
8117 is_row_soft_wrapped,
8118 window,
8119 cx,
8120 )
8121 .pop()
8122 .unwrap()
8123}
8124
8125#[derive(Debug)]
8126pub struct IndentGuideLayout {
8127 origin: gpui::Point<Pixels>,
8128 length: Pixels,
8129 single_indent_width: Pixels,
8130 depth: u32,
8131 active: bool,
8132 settings: IndentGuideSettings,
8133}
8134
8135pub struct CursorLayout {
8136 origin: gpui::Point<Pixels>,
8137 block_width: Pixels,
8138 line_height: Pixels,
8139 color: Hsla,
8140 shape: CursorShape,
8141 block_text: Option<ShapedLine>,
8142 cursor_name: Option<AnyElement>,
8143}
8144
8145#[derive(Debug)]
8146pub struct CursorName {
8147 string: SharedString,
8148 color: Hsla,
8149 is_top_row: bool,
8150}
8151
8152impl CursorLayout {
8153 pub fn new(
8154 origin: gpui::Point<Pixels>,
8155 block_width: Pixels,
8156 line_height: Pixels,
8157 color: Hsla,
8158 shape: CursorShape,
8159 block_text: Option<ShapedLine>,
8160 ) -> CursorLayout {
8161 CursorLayout {
8162 origin,
8163 block_width,
8164 line_height,
8165 color,
8166 shape,
8167 block_text,
8168 cursor_name: None,
8169 }
8170 }
8171
8172 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8173 Bounds {
8174 origin: self.origin + origin,
8175 size: size(self.block_width, self.line_height),
8176 }
8177 }
8178
8179 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8180 match self.shape {
8181 CursorShape::Bar => Bounds {
8182 origin: self.origin + origin,
8183 size: size(px(2.0), self.line_height),
8184 },
8185 CursorShape::Block | CursorShape::Hollow => Bounds {
8186 origin: self.origin + origin,
8187 size: size(self.block_width, self.line_height),
8188 },
8189 CursorShape::Underline => Bounds {
8190 origin: self.origin
8191 + origin
8192 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8193 size: size(self.block_width, px(2.0)),
8194 },
8195 }
8196 }
8197
8198 pub fn layout(
8199 &mut self,
8200 origin: gpui::Point<Pixels>,
8201 cursor_name: Option<CursorName>,
8202 window: &mut Window,
8203 cx: &mut App,
8204 ) {
8205 if let Some(cursor_name) = cursor_name {
8206 let bounds = self.bounds(origin);
8207 let text_size = self.line_height / 1.5;
8208
8209 let name_origin = if cursor_name.is_top_row {
8210 point(bounds.right() - px(1.), bounds.top())
8211 } else {
8212 match self.shape {
8213 CursorShape::Bar => point(
8214 bounds.right() - px(2.),
8215 bounds.top() - text_size / 2. - px(1.),
8216 ),
8217 _ => point(
8218 bounds.right() - px(1.),
8219 bounds.top() - text_size / 2. - px(1.),
8220 ),
8221 }
8222 };
8223 let mut name_element = div()
8224 .bg(self.color)
8225 .text_size(text_size)
8226 .px_0p5()
8227 .line_height(text_size + px(2.))
8228 .text_color(cursor_name.color)
8229 .child(cursor_name.string.clone())
8230 .into_any_element();
8231
8232 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8233
8234 self.cursor_name = Some(name_element);
8235 }
8236 }
8237
8238 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8239 let bounds = self.bounds(origin);
8240
8241 //Draw background or border quad
8242 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8243 outline(bounds, self.color)
8244 } else {
8245 fill(bounds, self.color)
8246 };
8247
8248 if let Some(name) = &mut self.cursor_name {
8249 name.paint(window, cx);
8250 }
8251
8252 window.paint_quad(cursor);
8253
8254 if let Some(block_text) = &self.block_text {
8255 block_text
8256 .paint(self.origin + origin, self.line_height, window, cx)
8257 .log_err();
8258 }
8259 }
8260
8261 pub fn shape(&self) -> CursorShape {
8262 self.shape
8263 }
8264}
8265
8266#[derive(Debug)]
8267pub struct HighlightedRange {
8268 pub start_y: Pixels,
8269 pub line_height: Pixels,
8270 pub lines: Vec<HighlightedRangeLine>,
8271 pub color: Hsla,
8272 pub corner_radius: Pixels,
8273}
8274
8275#[derive(Debug)]
8276pub struct HighlightedRangeLine {
8277 pub start_x: Pixels,
8278 pub end_x: Pixels,
8279}
8280
8281impl HighlightedRange {
8282 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8283 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8284 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8285 self.paint_lines(
8286 self.start_y + self.line_height,
8287 &self.lines[1..],
8288 bounds,
8289 window,
8290 );
8291 } else {
8292 self.paint_lines(self.start_y, &self.lines, bounds, window);
8293 }
8294 }
8295
8296 fn paint_lines(
8297 &self,
8298 start_y: Pixels,
8299 lines: &[HighlightedRangeLine],
8300 _bounds: Bounds<Pixels>,
8301 window: &mut Window,
8302 ) {
8303 if lines.is_empty() {
8304 return;
8305 }
8306
8307 let first_line = lines.first().unwrap();
8308 let last_line = lines.last().unwrap();
8309
8310 let first_top_left = point(first_line.start_x, start_y);
8311 let first_top_right = point(first_line.end_x, start_y);
8312
8313 let curve_height = point(Pixels::ZERO, self.corner_radius);
8314 let curve_width = |start_x: Pixels, end_x: Pixels| {
8315 let max = (end_x - start_x) / 2.;
8316 let width = if max < self.corner_radius {
8317 max
8318 } else {
8319 self.corner_radius
8320 };
8321
8322 point(width, Pixels::ZERO)
8323 };
8324
8325 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8326 let mut builder = gpui::PathBuilder::fill();
8327 builder.move_to(first_top_right - top_curve_width);
8328 builder.curve_to(first_top_right + curve_height, first_top_right);
8329
8330 let mut iter = lines.iter().enumerate().peekable();
8331 while let Some((ix, line)) = iter.next() {
8332 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8333
8334 if let Some((_, next_line)) = iter.peek() {
8335 let next_top_right = point(next_line.end_x, bottom_right.y);
8336
8337 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8338 Ordering::Equal => {
8339 builder.line_to(bottom_right);
8340 }
8341 Ordering::Less => {
8342 let curve_width = curve_width(next_top_right.x, bottom_right.x);
8343 builder.line_to(bottom_right - curve_height);
8344 if self.corner_radius > Pixels::ZERO {
8345 builder.curve_to(bottom_right - curve_width, bottom_right);
8346 }
8347 builder.line_to(next_top_right + curve_width);
8348 if self.corner_radius > Pixels::ZERO {
8349 builder.curve_to(next_top_right + curve_height, next_top_right);
8350 }
8351 }
8352 Ordering::Greater => {
8353 let curve_width = curve_width(bottom_right.x, next_top_right.x);
8354 builder.line_to(bottom_right - curve_height);
8355 if self.corner_radius > Pixels::ZERO {
8356 builder.curve_to(bottom_right + curve_width, bottom_right);
8357 }
8358 builder.line_to(next_top_right - curve_width);
8359 if self.corner_radius > Pixels::ZERO {
8360 builder.curve_to(next_top_right + curve_height, next_top_right);
8361 }
8362 }
8363 }
8364 } else {
8365 let curve_width = curve_width(line.start_x, line.end_x);
8366 builder.line_to(bottom_right - curve_height);
8367 if self.corner_radius > Pixels::ZERO {
8368 builder.curve_to(bottom_right - curve_width, bottom_right);
8369 }
8370
8371 let bottom_left = point(line.start_x, bottom_right.y);
8372 builder.line_to(bottom_left + curve_width);
8373 if self.corner_radius > Pixels::ZERO {
8374 builder.curve_to(bottom_left - curve_height, bottom_left);
8375 }
8376 }
8377 }
8378
8379 if first_line.start_x > last_line.start_x {
8380 let curve_width = curve_width(last_line.start_x, first_line.start_x);
8381 let second_top_left = point(last_line.start_x, start_y + self.line_height);
8382 builder.line_to(second_top_left + curve_height);
8383 if self.corner_radius > Pixels::ZERO {
8384 builder.curve_to(second_top_left + curve_width, second_top_left);
8385 }
8386 let first_bottom_left = point(first_line.start_x, second_top_left.y);
8387 builder.line_to(first_bottom_left - curve_width);
8388 if self.corner_radius > Pixels::ZERO {
8389 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8390 }
8391 }
8392
8393 builder.line_to(first_top_left + curve_height);
8394 if self.corner_radius > Pixels::ZERO {
8395 builder.curve_to(first_top_left + top_curve_width, first_top_left);
8396 }
8397 builder.line_to(first_top_right - top_curve_width);
8398
8399 if let Ok(path) = builder.build() {
8400 window.paint_path(path, self.color);
8401 }
8402 }
8403}
8404
8405enum CursorPopoverType {
8406 CodeContextMenu,
8407 EditPrediction,
8408}
8409
8410pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8411 (delta.pow(1.5) / 100.0).into()
8412}
8413
8414fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8415 (delta.pow(1.2) / 300.0).into()
8416}
8417
8418pub fn register_action<T: Action>(
8419 editor: &Entity<Editor>,
8420 window: &mut Window,
8421 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8422) {
8423 let editor = editor.clone();
8424 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8425 let action = action.downcast_ref().unwrap();
8426 if phase == DispatchPhase::Bubble {
8427 editor.update(cx, |editor, cx| {
8428 listener(editor, action, window, cx);
8429 })
8430 }
8431 })
8432}
8433
8434fn compute_auto_height_layout(
8435 editor: &mut Editor,
8436 max_lines: usize,
8437 max_line_number_width: Pixels,
8438 known_dimensions: Size<Option<Pixels>>,
8439 available_width: AvailableSpace,
8440 window: &mut Window,
8441 cx: &mut Context<Editor>,
8442) -> Option<Size<Pixels>> {
8443 let width = known_dimensions.width.or({
8444 if let AvailableSpace::Definite(available_width) = available_width {
8445 Some(available_width)
8446 } else {
8447 None
8448 }
8449 })?;
8450 if let Some(height) = known_dimensions.height {
8451 return Some(size(width, height));
8452 }
8453
8454 let style = editor.style.as_ref().unwrap();
8455 let font_id = window.text_system().resolve_font(&style.text.font());
8456 let font_size = style.text.font_size.to_pixels(window.rem_size());
8457 let line_height = style.text.line_height_in_pixels(window.rem_size());
8458 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8459
8460 let mut snapshot = editor.snapshot(window, cx);
8461 let gutter_dimensions = snapshot
8462 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8463 .unwrap_or_default();
8464
8465 editor.gutter_dimensions = gutter_dimensions;
8466 let text_width = width - gutter_dimensions.width;
8467 let overscroll = size(em_width, px(0.));
8468
8469 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8470 if editor.set_wrap_width(Some(editor_width), cx) {
8471 snapshot = editor.snapshot(window, cx);
8472 }
8473
8474 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8475 let height = scroll_height
8476 .max(line_height)
8477 .min(line_height * max_lines as f32);
8478
8479 Some(size(width, height))
8480}
8481
8482#[cfg(test)]
8483mod tests {
8484 use super::*;
8485 use crate::{
8486 display_map::{BlockPlacement, BlockProperties},
8487 editor_tests::{init_test, update_test_language_settings},
8488 Editor, MultiBuffer,
8489 };
8490 use gpui::{TestAppContext, VisualTestContext};
8491 use language::language_settings;
8492 use log::info;
8493 use similar::DiffableStr;
8494 use std::num::NonZeroU32;
8495 use util::test::sample_text;
8496
8497 #[gpui::test]
8498 fn test_shape_line_numbers(cx: &mut TestAppContext) {
8499 init_test(cx, |_| {});
8500 let window = cx.add_window(|window, cx| {
8501 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8502 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8503 });
8504
8505 let editor = window.root(cx).unwrap();
8506 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8507 let line_height = window
8508 .update(cx, |_, window, _| {
8509 style.text.line_height_in_pixels(window.rem_size())
8510 })
8511 .unwrap();
8512 let element = EditorElement::new(&editor, style);
8513 let snapshot = window
8514 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8515 .unwrap();
8516
8517 let layouts = cx
8518 .update_window(*window, |_, window, cx| {
8519 element.layout_line_numbers(
8520 None,
8521 GutterDimensions {
8522 left_padding: Pixels::ZERO,
8523 right_padding: Pixels::ZERO,
8524 width: px(30.0),
8525 margin: Pixels::ZERO,
8526 git_blame_entries_width: None,
8527 },
8528 line_height,
8529 gpui::Point::default(),
8530 DisplayRow(0)..DisplayRow(6),
8531 &(0..6)
8532 .map(|row| RowInfo {
8533 buffer_row: Some(row),
8534 ..Default::default()
8535 })
8536 .collect::<Vec<_>>(),
8537 Some(DisplayPoint::new(DisplayRow(0), 0)),
8538 &snapshot,
8539 window,
8540 cx,
8541 )
8542 })
8543 .unwrap();
8544 assert_eq!(layouts.len(), 6);
8545
8546 let relative_rows = window
8547 .update(cx, |editor, window, cx| {
8548 let snapshot = editor.snapshot(window, cx);
8549 element.calculate_relative_line_numbers(
8550 &snapshot,
8551 &(DisplayRow(0)..DisplayRow(6)),
8552 Some(DisplayRow(3)),
8553 )
8554 })
8555 .unwrap();
8556 assert_eq!(relative_rows[&DisplayRow(0)], 3);
8557 assert_eq!(relative_rows[&DisplayRow(1)], 2);
8558 assert_eq!(relative_rows[&DisplayRow(2)], 1);
8559 // current line has no relative number
8560 assert_eq!(relative_rows[&DisplayRow(4)], 1);
8561 assert_eq!(relative_rows[&DisplayRow(5)], 2);
8562
8563 // works if cursor is before screen
8564 let relative_rows = window
8565 .update(cx, |editor, window, cx| {
8566 let snapshot = editor.snapshot(window, cx);
8567 element.calculate_relative_line_numbers(
8568 &snapshot,
8569 &(DisplayRow(3)..DisplayRow(6)),
8570 Some(DisplayRow(1)),
8571 )
8572 })
8573 .unwrap();
8574 assert_eq!(relative_rows.len(), 3);
8575 assert_eq!(relative_rows[&DisplayRow(3)], 2);
8576 assert_eq!(relative_rows[&DisplayRow(4)], 3);
8577 assert_eq!(relative_rows[&DisplayRow(5)], 4);
8578
8579 // works if cursor is after screen
8580 let relative_rows = window
8581 .update(cx, |editor, window, cx| {
8582 let snapshot = editor.snapshot(window, cx);
8583 element.calculate_relative_line_numbers(
8584 &snapshot,
8585 &(DisplayRow(0)..DisplayRow(3)),
8586 Some(DisplayRow(6)),
8587 )
8588 })
8589 .unwrap();
8590 assert_eq!(relative_rows.len(), 3);
8591 assert_eq!(relative_rows[&DisplayRow(0)], 5);
8592 assert_eq!(relative_rows[&DisplayRow(1)], 4);
8593 assert_eq!(relative_rows[&DisplayRow(2)], 3);
8594 }
8595
8596 #[gpui::test]
8597 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8598 init_test(cx, |_| {});
8599
8600 let window = cx.add_window(|window, cx| {
8601 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8602 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8603 });
8604 let cx = &mut VisualTestContext::from_window(*window, cx);
8605 let editor = window.root(cx).unwrap();
8606 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8607
8608 window
8609 .update(cx, |editor, window, cx| {
8610 editor.cursor_shape = CursorShape::Block;
8611 editor.change_selections(None, window, cx, |s| {
8612 s.select_ranges([
8613 Point::new(0, 0)..Point::new(1, 0),
8614 Point::new(3, 2)..Point::new(3, 3),
8615 Point::new(5, 6)..Point::new(6, 0),
8616 ]);
8617 });
8618 })
8619 .unwrap();
8620
8621 let (_, state) = cx.draw(
8622 point(px(500.), px(500.)),
8623 size(px(500.), px(500.)),
8624 |_, _| EditorElement::new(&editor, style),
8625 );
8626
8627 assert_eq!(state.selections.len(), 1);
8628 let local_selections = &state.selections[0].1;
8629 assert_eq!(local_selections.len(), 3);
8630 // moves cursor back one line
8631 assert_eq!(
8632 local_selections[0].head,
8633 DisplayPoint::new(DisplayRow(0), 6)
8634 );
8635 assert_eq!(
8636 local_selections[0].range,
8637 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8638 );
8639
8640 // moves cursor back one column
8641 assert_eq!(
8642 local_selections[1].range,
8643 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8644 );
8645 assert_eq!(
8646 local_selections[1].head,
8647 DisplayPoint::new(DisplayRow(3), 2)
8648 );
8649
8650 // leaves cursor on the max point
8651 assert_eq!(
8652 local_selections[2].range,
8653 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8654 );
8655 assert_eq!(
8656 local_selections[2].head,
8657 DisplayPoint::new(DisplayRow(6), 0)
8658 );
8659
8660 // active lines does not include 1 (even though the range of the selection does)
8661 assert_eq!(
8662 state.active_rows.keys().cloned().collect::<Vec<_>>(),
8663 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8664 );
8665
8666 // multi-buffer support
8667 // in DisplayPoint coordinates, this is what we're dealing with:
8668 // 0: [[file
8669 // 1: header
8670 // 2: section]]
8671 // 3: aaaaaa
8672 // 4: bbbbbb
8673 // 5: cccccc
8674 // 6:
8675 // 7: [[footer]]
8676 // 8: [[header]]
8677 // 9: ffffff
8678 // 10: gggggg
8679 // 11: hhhhhh
8680 // 12:
8681 // 13: [[footer]]
8682 // 14: [[file
8683 // 15: header
8684 // 16: section]]
8685 // 17: bbbbbb
8686 // 18: cccccc
8687 // 19: dddddd
8688 // 20: [[footer]]
8689 let window = cx.add_window(|window, cx| {
8690 let buffer = MultiBuffer::build_multi(
8691 [
8692 (
8693 &(sample_text(8, 6, 'a') + "\n"),
8694 vec![
8695 Point::new(0, 0)..Point::new(3, 0),
8696 Point::new(4, 0)..Point::new(7, 0),
8697 ],
8698 ),
8699 (
8700 &(sample_text(8, 6, 'a') + "\n"),
8701 vec![Point::new(1, 0)..Point::new(3, 0)],
8702 ),
8703 ],
8704 cx,
8705 );
8706 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8707 });
8708 let editor = window.root(cx).unwrap();
8709 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8710 let _state = window.update(cx, |editor, window, cx| {
8711 editor.cursor_shape = CursorShape::Block;
8712 editor.change_selections(None, window, cx, |s| {
8713 s.select_display_ranges([
8714 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8715 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8716 ]);
8717 });
8718 });
8719
8720 let (_, state) = cx.draw(
8721 point(px(500.), px(500.)),
8722 size(px(500.), px(500.)),
8723 |_, _| EditorElement::new(&editor, style),
8724 );
8725 assert_eq!(state.selections.len(), 1);
8726 let local_selections = &state.selections[0].1;
8727 assert_eq!(local_selections.len(), 2);
8728
8729 // moves cursor on excerpt boundary back a line
8730 // and doesn't allow selection to bleed through
8731 assert_eq!(
8732 local_selections[0].range,
8733 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8734 );
8735 assert_eq!(
8736 local_selections[0].head,
8737 DisplayPoint::new(DisplayRow(6), 0)
8738 );
8739 // moves cursor on buffer boundary back two lines
8740 // and doesn't allow selection to bleed through
8741 assert_eq!(
8742 local_selections[1].range,
8743 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8744 );
8745 assert_eq!(
8746 local_selections[1].head,
8747 DisplayPoint::new(DisplayRow(12), 0)
8748 );
8749 }
8750
8751 #[gpui::test]
8752 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8753 init_test(cx, |_| {});
8754
8755 let window = cx.add_window(|window, cx| {
8756 let buffer = MultiBuffer::build_simple("", cx);
8757 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8758 });
8759 let cx = &mut VisualTestContext::from_window(*window, cx);
8760 let editor = window.root(cx).unwrap();
8761 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8762 window
8763 .update(cx, |editor, window, cx| {
8764 editor.set_placeholder_text("hello", cx);
8765 editor.insert_blocks(
8766 [BlockProperties {
8767 style: BlockStyle::Fixed,
8768 placement: BlockPlacement::Above(Anchor::min()),
8769 height: 3,
8770 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8771 priority: 0,
8772 }],
8773 None,
8774 cx,
8775 );
8776
8777 // Blur the editor so that it displays placeholder text.
8778 window.blur();
8779 })
8780 .unwrap();
8781
8782 let (_, state) = cx.draw(
8783 point(px(500.), px(500.)),
8784 size(px(500.), px(500.)),
8785 |_, _| EditorElement::new(&editor, style),
8786 );
8787 assert_eq!(state.position_map.line_layouts.len(), 4);
8788 assert_eq!(state.line_numbers.len(), 1);
8789 assert_eq!(
8790 state
8791 .line_numbers
8792 .get(&MultiBufferRow(0))
8793 .and_then(|line_number| line_number.shaped_line.text.as_str()),
8794 Some("1")
8795 );
8796 }
8797
8798 #[gpui::test]
8799 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8800 const TAB_SIZE: u32 = 4;
8801
8802 let input_text = "\t \t|\t| a b";
8803 let expected_invisibles = vec![
8804 Invisible::Tab {
8805 line_start_offset: 0,
8806 line_end_offset: TAB_SIZE as usize,
8807 },
8808 Invisible::Whitespace {
8809 line_offset: TAB_SIZE as usize,
8810 },
8811 Invisible::Tab {
8812 line_start_offset: TAB_SIZE as usize + 1,
8813 line_end_offset: TAB_SIZE as usize * 2,
8814 },
8815 Invisible::Tab {
8816 line_start_offset: TAB_SIZE as usize * 2 + 1,
8817 line_end_offset: TAB_SIZE as usize * 3,
8818 },
8819 Invisible::Whitespace {
8820 line_offset: TAB_SIZE as usize * 3 + 1,
8821 },
8822 Invisible::Whitespace {
8823 line_offset: TAB_SIZE as usize * 3 + 3,
8824 },
8825 ];
8826 assert_eq!(
8827 expected_invisibles.len(),
8828 input_text
8829 .chars()
8830 .filter(|initial_char| initial_char.is_whitespace())
8831 .count(),
8832 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8833 );
8834
8835 for show_line_numbers in [true, false] {
8836 init_test(cx, |s| {
8837 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8838 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8839 });
8840
8841 let actual_invisibles = collect_invisibles_from_new_editor(
8842 cx,
8843 EditorMode::Full,
8844 input_text,
8845 px(500.0),
8846 show_line_numbers,
8847 );
8848
8849 assert_eq!(expected_invisibles, actual_invisibles);
8850 }
8851 }
8852
8853 #[gpui::test]
8854 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8855 init_test(cx, |s| {
8856 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8857 s.defaults.tab_size = NonZeroU32::new(4);
8858 });
8859
8860 for editor_mode_without_invisibles in [
8861 EditorMode::SingleLine { auto_width: false },
8862 EditorMode::AutoHeight { max_lines: 100 },
8863 ] {
8864 for show_line_numbers in [true, false] {
8865 let invisibles = collect_invisibles_from_new_editor(
8866 cx,
8867 editor_mode_without_invisibles,
8868 "\t\t\t| | a b",
8869 px(500.0),
8870 show_line_numbers,
8871 );
8872 assert!(invisibles.is_empty(),
8873 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8874 }
8875 }
8876 }
8877
8878 #[gpui::test]
8879 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8880 let tab_size = 4;
8881 let input_text = "a\tbcd ".repeat(9);
8882 let repeated_invisibles = [
8883 Invisible::Tab {
8884 line_start_offset: 1,
8885 line_end_offset: tab_size as usize,
8886 },
8887 Invisible::Whitespace {
8888 line_offset: tab_size as usize + 3,
8889 },
8890 Invisible::Whitespace {
8891 line_offset: tab_size as usize + 4,
8892 },
8893 Invisible::Whitespace {
8894 line_offset: tab_size as usize + 5,
8895 },
8896 Invisible::Whitespace {
8897 line_offset: tab_size as usize + 6,
8898 },
8899 Invisible::Whitespace {
8900 line_offset: tab_size as usize + 7,
8901 },
8902 ];
8903 let expected_invisibles = std::iter::once(repeated_invisibles)
8904 .cycle()
8905 .take(9)
8906 .flatten()
8907 .collect::<Vec<_>>();
8908 assert_eq!(
8909 expected_invisibles.len(),
8910 input_text
8911 .chars()
8912 .filter(|initial_char| initial_char.is_whitespace())
8913 .count(),
8914 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8915 );
8916 info!("Expected invisibles: {expected_invisibles:?}");
8917
8918 init_test(cx, |_| {});
8919
8920 // Put the same string with repeating whitespace pattern into editors of various size,
8921 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8922 let resize_step = 10.0;
8923 let mut editor_width = 200.0;
8924 while editor_width <= 1000.0 {
8925 for show_line_numbers in [true, false] {
8926 update_test_language_settings(cx, |s| {
8927 s.defaults.tab_size = NonZeroU32::new(tab_size);
8928 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8929 s.defaults.preferred_line_length = Some(editor_width as u32);
8930 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8931 });
8932
8933 let actual_invisibles = collect_invisibles_from_new_editor(
8934 cx,
8935 EditorMode::Full,
8936 &input_text,
8937 px(editor_width),
8938 show_line_numbers,
8939 );
8940
8941 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8942 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8943 let mut i = 0;
8944 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8945 i = actual_index;
8946 match expected_invisibles.get(i) {
8947 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8948 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8949 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8950 _ => {
8951 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8952 }
8953 },
8954 None => {
8955 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8956 }
8957 }
8958 }
8959 let missing_expected_invisibles = &expected_invisibles[i + 1..];
8960 assert!(
8961 missing_expected_invisibles.is_empty(),
8962 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8963 );
8964
8965 editor_width += resize_step;
8966 }
8967 }
8968 }
8969
8970 fn collect_invisibles_from_new_editor(
8971 cx: &mut TestAppContext,
8972 editor_mode: EditorMode,
8973 input_text: &str,
8974 editor_width: Pixels,
8975 show_line_numbers: bool,
8976 ) -> Vec<Invisible> {
8977 info!(
8978 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8979 editor_width.0
8980 );
8981 let window = cx.add_window(|window, cx| {
8982 let buffer = MultiBuffer::build_simple(input_text, cx);
8983 Editor::new(editor_mode, buffer, None, true, window, cx)
8984 });
8985 let cx = &mut VisualTestContext::from_window(*window, cx);
8986 let editor = window.root(cx).unwrap();
8987
8988 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8989 window
8990 .update(cx, |editor, _, cx| {
8991 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8992 editor.set_wrap_width(Some(editor_width), cx);
8993 editor.set_show_line_numbers(show_line_numbers, cx);
8994 })
8995 .unwrap();
8996 let (_, state) = cx.draw(
8997 point(px(500.), px(500.)),
8998 size(px(500.), px(500.)),
8999 |_, _| EditorElement::new(&editor, style),
9000 );
9001 state
9002 .position_map
9003 .line_layouts
9004 .iter()
9005 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
9006 .cloned()
9007 .collect()
9008 }
9009}
9010
9011fn diff_hunk_controls(
9012 row: u32,
9013 hunk_range: Range<Anchor>,
9014 line_height: Pixels,
9015 editor: &Entity<Editor>,
9016 _window: &mut Window,
9017 cx: &mut App,
9018) -> AnyElement {
9019 let stage = editor.update(cx, |editor, cx| {
9020 let snapshot = editor.buffer.read(cx).snapshot(cx);
9021 editor.has_stageable_diff_hunks_in_ranges(&[hunk_range.start..hunk_range.start], &snapshot)
9022 });
9023 h_flex()
9024 .h(line_height)
9025 .mr_1()
9026 .gap_1()
9027 .px_1()
9028 .pb_1()
9029 .border_b_1()
9030 .border_color(cx.theme().colors().border_variant)
9031 .rounded_b_lg()
9032 .bg(cx.theme().colors().editor_background)
9033 .gap_1()
9034 .child(
9035 IconButton::new(("discard-hunk", row as u64), IconName::Undo)
9036 .shape(IconButtonShape::Square)
9037 .icon_size(IconSize::Small)
9038 .tooltip({
9039 let focus_handle = editor.focus_handle(cx);
9040 move |window, cx| {
9041 Tooltip::for_action_in(
9042 "Discard Hunk",
9043 &RevertSelectedHunks,
9044 &focus_handle,
9045 window,
9046 cx,
9047 )
9048 }
9049 })
9050 .on_click({
9051 let editor = editor.clone();
9052 move |_event, window, cx| {
9053 editor.update(cx, |editor, cx| {
9054 let snapshot = editor.snapshot(window, cx);
9055 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9056 editor.discard_hunks_in_ranges([point..point].into_iter(), window, cx);
9057 });
9058 }
9059 }),
9060 )
9061 .child(
9062 Button::new(("skip-hunk", row as u64), "Skip")
9063 .label_size(LabelSize::Small)
9064 .tooltip({
9065 let focus_handle = editor.focus_handle(cx);
9066 move |window, cx| {
9067 Tooltip::for_action_in("Skip Hunk", &GoToHunk, &focus_handle, window, cx)
9068 }
9069 })
9070 .on_click({
9071 let editor = editor.clone();
9072 move |_event, window, cx| {
9073 editor.update(cx, |editor, cx| {
9074 let snapshot = editor.snapshot(window, cx);
9075 let position = hunk_range.end.to_point(&snapshot.buffer_snapshot);
9076 editor.go_to_hunk_after_position(&snapshot, position, window, cx);
9077 editor.expand_selected_diff_hunks(cx);
9078 });
9079 }
9080 }),
9081 )
9082 .child(
9083 Button::new(
9084 ("stage-unstage-hunk", row as u64),
9085 if stage { "Stage" } else { "Unstage" },
9086 )
9087 .label_size(LabelSize::Small)
9088 .tooltip({
9089 let focus_handle = editor.focus_handle(cx);
9090 move |window, cx| {
9091 Tooltip::for_action_in(
9092 if stage { "Stage Hunk" } else { "Unstage Hunk" },
9093 &ToggleStagedSelectedDiffHunks,
9094 &focus_handle,
9095 window,
9096 cx,
9097 )
9098 }
9099 })
9100 .on_click({
9101 let editor = editor.clone();
9102 move |_event, _window, cx| {
9103 editor.update(cx, |editor, cx| {
9104 editor
9105 .stage_or_unstage_diff_hunks(&[hunk_range.start..hunk_range.start], cx);
9106 });
9107 }
9108 }),
9109 )
9110 .into_any_element()
9111}