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