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