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