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