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