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