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