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