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 mut result = v_flex().id(block_id).w_full();
2407
2408 if let Some(prev_excerpt) = prev_excerpt {
2409 if *show_excerpt_controls {
2410 result = result.child(self.render_expand_excerpt_control(
2411 block_id,
2412 ExpandExcerptDirection::Down,
2413 prev_excerpt.id,
2414 gutter_dimensions,
2415 window,
2416 cx,
2417 ));
2418 }
2419 }
2420
2421 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
2422 result
2423 .child(self.render_buffer_header(
2424 first_excerpt,
2425 true,
2426 selected,
2427 jump_data,
2428 window,
2429 cx,
2430 ))
2431 .into_any_element()
2432 }
2433
2434 Block::ExcerptBoundary {
2435 prev_excerpt,
2436 next_excerpt,
2437 show_excerpt_controls,
2438 height,
2439 starts_new_buffer,
2440 } => {
2441 let color = cx.theme().colors().clone();
2442 let mut result = v_flex().id(block_id).w_full();
2443
2444 if let Some(prev_excerpt) = prev_excerpt {
2445 if *show_excerpt_controls {
2446 result = result.child(self.render_expand_excerpt_control(
2447 block_id,
2448 ExpandExcerptDirection::Down,
2449 prev_excerpt.id,
2450 gutter_dimensions,
2451 window,
2452 cx,
2453 ));
2454 }
2455 }
2456
2457 if let Some(next_excerpt) = next_excerpt {
2458 let jump_data =
2459 header_jump_data(snapshot, block_row_start, *height, next_excerpt);
2460
2461 if *starts_new_buffer {
2462 if sticky_header_excerpt_id != Some(next_excerpt.id) {
2463 let selected = selected_buffer_ids.contains(&next_excerpt.buffer_id);
2464
2465 result = result.child(self.render_buffer_header(
2466 next_excerpt,
2467 false,
2468 selected,
2469 jump_data,
2470 window,
2471 cx,
2472 ));
2473 } else {
2474 result = result
2475 .child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
2476 }
2477
2478 if *show_excerpt_controls {
2479 result = result.child(self.render_expand_excerpt_control(
2480 block_id,
2481 ExpandExcerptDirection::Up,
2482 next_excerpt.id,
2483 gutter_dimensions,
2484 window,
2485 cx,
2486 ));
2487 }
2488 } else {
2489 if *show_excerpt_controls {
2490 result = result.child(
2491 h_flex()
2492 .relative()
2493 .child(
2494 div()
2495 .top(px(0.))
2496 .absolute()
2497 .w_full()
2498 .h_px()
2499 .bg(color.border_variant),
2500 )
2501 .child(self.render_expand_excerpt_control(
2502 block_id,
2503 ExpandExcerptDirection::Up,
2504 next_excerpt.id,
2505 gutter_dimensions,
2506 window,
2507 cx,
2508 )),
2509 );
2510 }
2511 };
2512 }
2513
2514 result.into_any()
2515 }
2516 };
2517
2518 // Discover the element's content height, then round up to the nearest multiple of line height.
2519 let preliminary_size = element.layout_as_root(
2520 size(available_width, AvailableSpace::MinContent),
2521 window,
2522 cx,
2523 );
2524 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2525 let final_size = if preliminary_size.height == quantized_height {
2526 preliminary_size
2527 } else {
2528 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
2529 };
2530
2531 if let BlockId::Custom(custom_block_id) = block_id {
2532 if block.height() > 0 {
2533 let element_height_in_lines =
2534 ((final_size.height / line_height).ceil() as u32).max(1);
2535 if element_height_in_lines != block.height() {
2536 resized_blocks.insert(custom_block_id, element_height_in_lines);
2537 }
2538 }
2539 }
2540
2541 (element, final_size)
2542 }
2543
2544 fn render_buffer_header(
2545 &self,
2546 for_excerpt: &ExcerptInfo,
2547 is_folded: bool,
2548 is_selected: bool,
2549 jump_data: JumpData,
2550 window: &mut Window,
2551 cx: &mut App,
2552 ) -> Div {
2553 let include_root = self
2554 .editor
2555 .read(cx)
2556 .project
2557 .as_ref()
2558 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2559 .unwrap_or_default();
2560 let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
2561 let filename = path
2562 .as_ref()
2563 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
2564 let parent_path = path.as_ref().and_then(|path| {
2565 Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
2566 });
2567 let focus_handle = self.editor.focus_handle(cx);
2568 let colors = cx.theme().colors();
2569
2570 div()
2571 .px_2()
2572 .pt_2()
2573 .w_full()
2574 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
2575 .child(
2576 h_flex()
2577 .size_full()
2578 .gap_2()
2579 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2580 .pl_0p5()
2581 .pr_5()
2582 .rounded_md()
2583 .shadow_md()
2584 .border_1()
2585 .map(|div| {
2586 let border_color = if is_selected && is_folded {
2587 colors.border_focused
2588 } else {
2589 colors.border
2590 };
2591 div.border_color(border_color)
2592 })
2593 .bg(colors.editor_subheader_background)
2594 .hover(|style| style.bg(colors.element_hover))
2595 .map(|header| {
2596 let editor = self.editor.clone();
2597 let buffer_id = for_excerpt.buffer_id;
2598 let toggle_chevron_icon =
2599 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
2600 header.child(
2601 div()
2602 .hover(|style| style.bg(colors.element_selected))
2603 .rounded_sm()
2604 .child(
2605 ButtonLike::new("toggle-buffer-fold")
2606 .style(ui::ButtonStyle::Transparent)
2607 .size(ButtonSize::Large)
2608 .width(px(30.).into())
2609 .children(toggle_chevron_icon)
2610 .tooltip({
2611 let focus_handle = focus_handle.clone();
2612 move |window, cx| {
2613 Tooltip::for_action_in(
2614 "Toggle Excerpt Fold",
2615 &ToggleFold,
2616 &focus_handle,
2617 window,
2618 cx,
2619 )
2620 }
2621 })
2622 .on_click(move |_, _, cx| {
2623 if is_folded {
2624 editor.update(cx, |editor, cx| {
2625 editor.unfold_buffer(buffer_id, cx);
2626 });
2627 } else {
2628 editor.update(cx, |editor, cx| {
2629 editor.fold_buffer(buffer_id, cx);
2630 });
2631 }
2632 }),
2633 ),
2634 )
2635 })
2636 .children(
2637 self.editor
2638 .read(cx)
2639 .addons
2640 .values()
2641 .filter_map(|addon| {
2642 addon.render_buffer_header_controls(for_excerpt, window, cx)
2643 })
2644 .take(1),
2645 )
2646 .child(
2647 h_flex()
2648 .cursor_pointer()
2649 .id("path header block")
2650 .size_full()
2651 .justify_between()
2652 .child(
2653 h_flex()
2654 .gap_2()
2655 .child(
2656 filename
2657 .map(SharedString::from)
2658 .unwrap_or_else(|| "untitled".into()),
2659 )
2660 .when_some(parent_path, |then, path| {
2661 then.child(div().child(path).text_color(colors.text_muted))
2662 }),
2663 )
2664 .when(is_selected, |el| {
2665 el.child(
2666 h_flex()
2667 .id("jump-to-file-button")
2668 .gap_2p5()
2669 .child(Label::new("Jump To File"))
2670 .children(
2671 KeyBinding::for_action_in(
2672 &OpenExcerpts,
2673 &focus_handle,
2674 window,
2675 )
2676 .map(|binding| binding.into_any_element()),
2677 ),
2678 )
2679 })
2680 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
2681 .on_click(window.listener_for(&self.editor, {
2682 move |editor, e: &ClickEvent, window, cx| {
2683 editor.open_excerpts_common(
2684 Some(jump_data.clone()),
2685 e.down.modifiers.secondary(),
2686 window,
2687 cx,
2688 );
2689 }
2690 })),
2691 ),
2692 )
2693 }
2694
2695 fn render_expand_excerpt_control(
2696 &self,
2697 block_id: BlockId,
2698 direction: ExpandExcerptDirection,
2699 excerpt_id: ExcerptId,
2700 gutter_dimensions: &GutterDimensions,
2701 window: &Window,
2702 cx: &mut App,
2703 ) -> impl IntoElement {
2704 let color = cx.theme().colors().clone();
2705 let hover_color = color.border_variant.opacity(0.5);
2706 let focus_handle = self.editor.focus_handle(cx).clone();
2707
2708 let icon_offset =
2709 gutter_dimensions.width - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2710 let header_height = MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * window.line_height();
2711 let group_name = if direction == ExpandExcerptDirection::Down {
2712 "expand-down"
2713 } else {
2714 "expand-up"
2715 };
2716
2717 let expand_area = |id: SharedString| {
2718 h_flex()
2719 .id(id)
2720 .w_full()
2721 .cursor_pointer()
2722 .block_mouse_down()
2723 .on_mouse_move(|_, _, cx| cx.stop_propagation())
2724 .hover(|style| style.bg(hover_color))
2725 .tooltip({
2726 let focus_handle = focus_handle.clone();
2727 move |window, cx| {
2728 Tooltip::for_action_in(
2729 "Expand Excerpt",
2730 &ExpandExcerpts { lines: 0 },
2731 &focus_handle,
2732 window,
2733 cx,
2734 )
2735 }
2736 })
2737 };
2738
2739 expand_area(
2740 format!(
2741 "block-{}-{}",
2742 block_id,
2743 if direction == ExpandExcerptDirection::Down {
2744 "down"
2745 } else {
2746 "up"
2747 }
2748 )
2749 .into(),
2750 )
2751 .group(group_name)
2752 .child(
2753 h_flex()
2754 .w(icon_offset)
2755 .h(header_height)
2756 .flex_none()
2757 .justify_end()
2758 .child(
2759 ButtonLike::new("expand-icon")
2760 .style(ButtonStyle::Transparent)
2761 .child(
2762 svg()
2763 .path(if direction == ExpandExcerptDirection::Down {
2764 IconName::ArrowDownFromLine.path()
2765 } else {
2766 IconName::ArrowUpFromLine.path()
2767 })
2768 .size(IconSize::XSmall.rems())
2769 .text_color(cx.theme().colors().editor_line_number)
2770 .group_hover(group_name, |style| {
2771 style.text_color(cx.theme().colors().editor_active_line_number)
2772 }),
2773 ),
2774 ),
2775 )
2776 .on_click(window.listener_for(&self.editor, {
2777 move |editor, _, _, cx| {
2778 editor.expand_excerpt(excerpt_id, direction, cx);
2779 cx.stop_propagation();
2780 }
2781 }))
2782 }
2783
2784 #[allow(clippy::too_many_arguments)]
2785 fn render_blocks(
2786 &self,
2787 rows: Range<DisplayRow>,
2788 snapshot: &EditorSnapshot,
2789 hitbox: &Hitbox,
2790 text_hitbox: &Hitbox,
2791 editor_width: Pixels,
2792 scroll_width: &mut Pixels,
2793 gutter_dimensions: &GutterDimensions,
2794 em_width: Pixels,
2795 text_x: Pixels,
2796 line_height: Pixels,
2797 line_layouts: &[LineWithInvisibles],
2798 selections: &[Selection<Point>],
2799 selected_buffer_ids: &Vec<BufferId>,
2800 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2801 sticky_header_excerpt_id: Option<ExcerptId>,
2802 window: &mut Window,
2803 cx: &mut App,
2804 ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2805 let (fixed_blocks, non_fixed_blocks) = snapshot
2806 .blocks_in_range(rows.clone())
2807 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2808
2809 let mut focused_block = self
2810 .editor
2811 .update(cx, |editor, _| editor.take_focused_block());
2812 let mut fixed_block_max_width = Pixels::ZERO;
2813 let mut blocks = Vec::new();
2814 let mut resized_blocks = HashMap::default();
2815
2816 for (row, block) in fixed_blocks {
2817 let block_id = block.id();
2818
2819 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2820 focused_block = None;
2821 }
2822
2823 let (element, element_size) = self.render_block(
2824 block,
2825 AvailableSpace::MinContent,
2826 block_id,
2827 row,
2828 snapshot,
2829 text_x,
2830 &rows,
2831 line_layouts,
2832 gutter_dimensions,
2833 line_height,
2834 em_width,
2835 text_hitbox,
2836 editor_width,
2837 scroll_width,
2838 &mut resized_blocks,
2839 selections,
2840 selected_buffer_ids,
2841 is_row_soft_wrapped,
2842 sticky_header_excerpt_id,
2843 window,
2844 cx,
2845 );
2846 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2847 blocks.push(BlockLayout {
2848 id: block_id,
2849 row: Some(row),
2850 element,
2851 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2852 style: BlockStyle::Fixed,
2853 });
2854 }
2855
2856 for (row, block) in non_fixed_blocks {
2857 let style = block.style();
2858 let width = match style {
2859 BlockStyle::Sticky => hitbox.size.width,
2860 BlockStyle::Flex => hitbox
2861 .size
2862 .width
2863 .max(fixed_block_max_width)
2864 .max(gutter_dimensions.width + *scroll_width),
2865 BlockStyle::Fixed => unreachable!(),
2866 };
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 width.into(),
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
2897 blocks.push(BlockLayout {
2898 id: block_id,
2899 row: Some(row),
2900 element,
2901 available_space: size(width.into(), element_size.height.into()),
2902 style,
2903 });
2904 }
2905
2906 if let Some(focused_block) = focused_block {
2907 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2908 if focus_handle.is_focused(window) {
2909 if let Some(block) = snapshot.block_for_id(focused_block.id) {
2910 let style = block.style();
2911 let width = match style {
2912 BlockStyle::Fixed => AvailableSpace::MinContent,
2913 BlockStyle::Flex => AvailableSpace::Definite(
2914 hitbox
2915 .size
2916 .width
2917 .max(fixed_block_max_width)
2918 .max(gutter_dimensions.width + *scroll_width),
2919 ),
2920 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2921 };
2922
2923 let (element, element_size) = self.render_block(
2924 &block,
2925 width,
2926 focused_block.id,
2927 rows.end,
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: None,
2950 element,
2951 available_space: size(width, element_size.height.into()),
2952 style,
2953 });
2954 }
2955 }
2956 }
2957 }
2958
2959 if resized_blocks.is_empty() {
2960 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2961 Ok(blocks)
2962 } else {
2963 Err(resized_blocks)
2964 }
2965 }
2966
2967 /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2968 /// a restart of rendering for the editor based on the new sizes.
2969 #[allow(clippy::too_many_arguments)]
2970 fn layout_blocks(
2971 &self,
2972 blocks: &mut Vec<BlockLayout>,
2973 block_starts: &mut HashSet<DisplayRow>,
2974 hitbox: &Hitbox,
2975 line_height: Pixels,
2976 scroll_pixel_position: gpui::Point<Pixels>,
2977 window: &mut Window,
2978 cx: &mut App,
2979 ) {
2980 for block in blocks {
2981 let mut origin = if let Some(row) = block.row {
2982 block_starts.insert(row);
2983 hitbox.origin
2984 + point(
2985 Pixels::ZERO,
2986 row.as_f32() * line_height - scroll_pixel_position.y,
2987 )
2988 } else {
2989 // Position the block outside the visible area
2990 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2991 };
2992
2993 if !matches!(block.style, BlockStyle::Sticky) {
2994 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2995 }
2996
2997 let focus_handle =
2998 block
2999 .element
3000 .prepaint_as_root(origin, block.available_space, window, cx);
3001
3002 if let Some(focus_handle) = focus_handle {
3003 self.editor.update(cx, |editor, _cx| {
3004 editor.set_focused_block(FocusedBlock {
3005 id: block.id,
3006 focus_handle: focus_handle.downgrade(),
3007 });
3008 });
3009 }
3010 }
3011 }
3012
3013 #[allow(clippy::too_many_arguments)]
3014 fn layout_sticky_buffer_header(
3015 &self,
3016 StickyHeaderExcerpt {
3017 excerpt,
3018 next_excerpt_controls_present,
3019 next_buffer_row,
3020 }: StickyHeaderExcerpt<'_>,
3021 scroll_position: f32,
3022 line_height: Pixels,
3023 snapshot: &EditorSnapshot,
3024 hitbox: &Hitbox,
3025 selected_buffer_ids: &Vec<BufferId>,
3026 window: &mut Window,
3027 cx: &mut App,
3028 ) -> AnyElement {
3029 let jump_data = header_jump_data(
3030 snapshot,
3031 DisplayRow(scroll_position as u32),
3032 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3033 excerpt,
3034 );
3035
3036 let editor_bg_color = cx.theme().colors().editor_background;
3037
3038 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3039
3040 let mut header = v_flex()
3041 .relative()
3042 .child(
3043 div()
3044 .w(hitbox.bounds.size.width)
3045 .h(FILE_HEADER_HEIGHT as f32 * line_height)
3046 .bg(linear_gradient(
3047 0.,
3048 linear_color_stop(editor_bg_color.opacity(0.), 0.),
3049 linear_color_stop(editor_bg_color, 0.6),
3050 ))
3051 .absolute()
3052 .top_0(),
3053 )
3054 .child(
3055 self.render_buffer_header(excerpt, false, selected, jump_data, window, cx)
3056 .into_any_element(),
3057 )
3058 .into_any_element();
3059
3060 let mut origin = hitbox.origin;
3061
3062 if let Some(next_buffer_row) = next_buffer_row {
3063 // Push up the sticky header when the excerpt is getting close to the top of the viewport
3064
3065 let mut max_row = next_buffer_row - FILE_HEADER_HEIGHT * 2;
3066
3067 if next_excerpt_controls_present {
3068 max_row -= MULTI_BUFFER_EXCERPT_HEADER_HEIGHT;
3069 }
3070
3071 let offset = scroll_position - max_row as f32;
3072
3073 if offset > 0.0 {
3074 origin.y -= Pixels(offset) * line_height;
3075 }
3076 }
3077
3078 let size = size(
3079 AvailableSpace::Definite(hitbox.size.width),
3080 AvailableSpace::MinContent,
3081 );
3082
3083 header.prepaint_as_root(origin, size, window, cx);
3084
3085 header
3086 }
3087
3088 #[allow(clippy::too_many_arguments)]
3089 fn layout_cursor_popovers(
3090 &self,
3091 line_height: Pixels,
3092 text_hitbox: &Hitbox,
3093 content_origin: gpui::Point<Pixels>,
3094 start_row: DisplayRow,
3095 scroll_pixel_position: gpui::Point<Pixels>,
3096 line_layouts: &[LineWithInvisibles],
3097 cursor: DisplayPoint,
3098 cursor_point: Point,
3099 style: &EditorStyle,
3100 window: &mut Window,
3101 cx: &mut App,
3102 ) {
3103 let mut min_menu_height = Pixels::ZERO;
3104 let mut max_menu_height = Pixels::ZERO;
3105 let mut height_above_menu = Pixels::ZERO;
3106 let height_below_menu = Pixels::ZERO;
3107 let mut edit_prediction_popover_visible = false;
3108 let mut context_menu_visible = false;
3109
3110 {
3111 let editor = self.editor.read(cx);
3112 if editor.inline_completion_visible_in_cursor_popover(
3113 editor.has_active_inline_completion(),
3114 cx,
3115 ) {
3116 height_above_menu +=
3117 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3118 edit_prediction_popover_visible = true;
3119 }
3120
3121 if editor.context_menu_visible() {
3122 if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3123 min_menu_height += line_height * 3. + POPOVER_Y_PADDING;
3124 max_menu_height += line_height * 12. + POPOVER_Y_PADDING;
3125 context_menu_visible = true;
3126 }
3127 }
3128 }
3129
3130 let visible = edit_prediction_popover_visible || context_menu_visible;
3131 if !visible {
3132 return;
3133 }
3134
3135 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3136 let target_position = content_origin
3137 + gpui::Point {
3138 x: cmp::max(
3139 px(0.),
3140 cursor_row_layout.x_for_index(cursor.column() as usize)
3141 - scroll_pixel_position.x,
3142 ),
3143 y: cmp::max(
3144 px(0.),
3145 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3146 ),
3147 };
3148
3149 let viewport_bounds =
3150 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3151 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3152 ..Default::default()
3153 });
3154
3155 let min_height = height_above_menu + min_menu_height + height_below_menu;
3156 let max_height = height_above_menu + max_menu_height + height_below_menu;
3157 let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3158 target_position,
3159 line_height,
3160 min_height,
3161 max_height,
3162 text_hitbox,
3163 viewport_bounds,
3164 window,
3165 cx,
3166 |height, max_width_for_stable_x, y_flipped, window, cx| {
3167 // First layout the menu to get its size - others can be at least this wide.
3168 let context_menu = if context_menu_visible {
3169 let menu_height = if y_flipped {
3170 height - height_below_menu
3171 } else {
3172 height - height_above_menu
3173 };
3174 let mut element = self
3175 .render_context_menu(line_height, menu_height, y_flipped, window, cx)
3176 .expect("Visible context menu should always render.");
3177 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3178 Some((CursorPopoverType::CodeContextMenu, element, size))
3179 } else {
3180 None
3181 };
3182 let min_width = context_menu
3183 .as_ref()
3184 .map_or(px(0.), |(_, _, size)| size.width);
3185 let max_width = max_width_for_stable_x.max(
3186 context_menu
3187 .as_ref()
3188 .map_or(px(0.), |(_, _, size)| size.width),
3189 );
3190
3191 let edit_prediction = if edit_prediction_popover_visible {
3192 let accept_keystroke: Option<Keystroke>;
3193
3194 // TODO: load modifier from keymap.
3195 // `bindings_for_action_in` returns `None` in Linux, and is intermittent on macOS
3196 #[cfg(target_os = "macos")]
3197 {
3198 // let bindings = window.bindings_for_action_in(
3199 // &crate::AcceptInlineCompletion,
3200 // &self.editor.focus_handle(cx),
3201 // );
3202
3203 // let last_binding = bindings.last();
3204
3205 // accept_keystroke = if let Some(binding) = last_binding {
3206 // match &binding.keystrokes() {
3207 // // TODO: no need to clone once this logic works on linux.
3208 // [keystroke] => Some(keystroke.clone()),
3209 // _ => None,
3210 // }
3211 // } else {
3212 // None
3213 // };
3214 accept_keystroke = Some(Keystroke {
3215 modifiers: gpui::Modifiers {
3216 alt: true,
3217 ..Default::default()
3218 },
3219 key: "tab".to_string(),
3220 key_char: None,
3221 });
3222 }
3223
3224 #[cfg(not(target_os = "macos"))]
3225 {
3226 accept_keystroke = Some(Keystroke {
3227 modifiers: gpui::Modifiers {
3228 alt: true,
3229 ..Default::default()
3230 },
3231 key: "enter".to_string(),
3232 key_char: None,
3233 });
3234 }
3235
3236 self.editor.update(cx, move |editor, cx| {
3237 let mut element = editor.render_edit_prediction_cursor_popover(
3238 min_width,
3239 max_width,
3240 cursor_point,
3241 start_row,
3242 &line_layouts,
3243 style,
3244 accept_keystroke.as_ref()?,
3245 window,
3246 cx,
3247 )?;
3248 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3249 Some((CursorPopoverType::EditPrediction, element, size))
3250 })
3251 } else {
3252 None
3253 };
3254 vec![edit_prediction, context_menu]
3255 .into_iter()
3256 .flatten()
3257 .collect::<Vec<_>>()
3258 },
3259 ) else {
3260 return;
3261 };
3262
3263 let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3264 .iter()
3265 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3266 else {
3267 return;
3268 };
3269 let last_ix = laid_out_popovers.len() - 1;
3270 let menu_is_last = menu_ix == last_ix;
3271 let first_popover_bounds = laid_out_popovers[0].1;
3272 let last_popover_bounds = laid_out_popovers[last_ix].1;
3273
3274 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3275 // right, and otherwise it goes below or to the right.
3276 let mut target_bounds = Bounds::from_corners(
3277 first_popover_bounds.origin,
3278 last_popover_bounds.bottom_right(),
3279 );
3280 target_bounds.size.width = menu_bounds.size.width;
3281
3282 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3283 // based on this is preferred for layout stability.
3284 let mut max_target_bounds = target_bounds;
3285 max_target_bounds.size.height = max_height;
3286 if y_flipped {
3287 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3288 }
3289
3290 // Add spacing around `target_bounds` and `max_target_bounds`.
3291 let mut extend_amount = Edges::all(MENU_GAP);
3292 if y_flipped {
3293 extend_amount.bottom = line_height;
3294 } else {
3295 extend_amount.top = line_height;
3296 }
3297 let target_bounds = target_bounds.extend(extend_amount);
3298 let max_target_bounds = max_target_bounds.extend(extend_amount);
3299
3300 let must_place_above_or_below =
3301 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3302 laid_out_popovers[menu_ix + 1..]
3303 .iter()
3304 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3305 } else {
3306 false
3307 };
3308
3309 self.layout_context_menu_aside(
3310 y_flipped,
3311 *menu_bounds,
3312 target_bounds,
3313 max_target_bounds,
3314 max_menu_height,
3315 must_place_above_or_below,
3316 text_hitbox,
3317 viewport_bounds,
3318 window,
3319 cx,
3320 );
3321 }
3322
3323 #[allow(clippy::too_many_arguments)]
3324 fn layout_gutter_menu(
3325 &self,
3326 line_height: Pixels,
3327 text_hitbox: &Hitbox,
3328 content_origin: gpui::Point<Pixels>,
3329 scroll_pixel_position: gpui::Point<Pixels>,
3330 gutter_overshoot: Pixels,
3331 window: &mut Window,
3332 cx: &mut App,
3333 ) {
3334 let editor = self.editor.read(cx);
3335 if !editor.context_menu_visible() {
3336 return;
3337 }
3338 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3339 editor.context_menu_origin()
3340 else {
3341 return;
3342 };
3343 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3344 // indicator than just a plain first column of the text field.
3345 let target_position = content_origin
3346 + gpui::Point {
3347 x: -gutter_overshoot,
3348 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3349 };
3350 let min_height = line_height * 3. + POPOVER_Y_PADDING;
3351 let max_height = line_height * 12. + POPOVER_Y_PADDING;
3352 let viewport_bounds =
3353 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3354 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3355 ..Default::default()
3356 });
3357 self.layout_popovers_above_or_below_line(
3358 target_position,
3359 line_height,
3360 min_height,
3361 max_height,
3362 text_hitbox,
3363 viewport_bounds,
3364 window,
3365 cx,
3366 move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3367 let mut element = self
3368 .render_context_menu(line_height, height, y_flipped, window, cx)
3369 .expect("Visible context menu should always render.");
3370 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3371 vec![(CursorPopoverType::CodeContextMenu, element, size)]
3372 },
3373 );
3374 }
3375
3376 #[allow(clippy::too_many_arguments)]
3377 fn layout_popovers_above_or_below_line(
3378 &self,
3379 target_position: gpui::Point<Pixels>,
3380 line_height: Pixels,
3381 min_height: Pixels,
3382 max_height: Pixels,
3383 text_hitbox: &Hitbox,
3384 viewport_bounds: Bounds<Pixels>,
3385 window: &mut Window,
3386 cx: &mut App,
3387 make_sized_popovers: impl FnOnce(
3388 Pixels,
3389 Pixels,
3390 bool,
3391 &mut Window,
3392 &mut App,
3393 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3394 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3395 // If the max height won't fit below and there is more space above, put it above the line.
3396 let bottom_y_when_flipped = target_position.y - line_height;
3397 let available_above = bottom_y_when_flipped - text_hitbox.top();
3398 let available_below = text_hitbox.bottom() - target_position.y;
3399 let y_overflows_below = max_height > available_below;
3400 let mut y_flipped = y_overflows_below && available_above > available_below;
3401 let mut height = cmp::min(
3402 max_height,
3403 if y_flipped {
3404 available_above
3405 } else {
3406 available_below
3407 },
3408 );
3409
3410 // If the min height doesn't fit within text bounds, instead fit within the window.
3411 if height < min_height {
3412 let available_above = bottom_y_when_flipped;
3413 let available_below = viewport_bounds.bottom() - target_position.y;
3414 if available_below > min_height {
3415 y_flipped = false;
3416 height = min_height;
3417 } else if available_above > min_height {
3418 y_flipped = true;
3419 height = min_height;
3420 } else if available_above > available_below {
3421 y_flipped = true;
3422 height = available_above;
3423 } else {
3424 y_flipped = false;
3425 height = available_below;
3426 }
3427 }
3428
3429 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3430
3431 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3432 // for very narrow windows.
3433 let popovers = make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3434 if popovers.is_empty() {
3435 return None;
3436 }
3437
3438 let max_width = popovers
3439 .iter()
3440 .map(|(_, _, size)| size.width)
3441 .max()
3442 .unwrap_or_default();
3443
3444 let mut current_position = gpui::Point {
3445 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3446 // overflow. Include space for the scrollbar.
3447 x: target_position
3448 .x
3449 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3450 y: if y_flipped {
3451 bottom_y_when_flipped
3452 } else {
3453 target_position.y
3454 },
3455 };
3456
3457 let mut laid_out_popovers = popovers
3458 .into_iter()
3459 .map(|(popover_type, element, size)| {
3460 if y_flipped {
3461 current_position.y -= size.height;
3462 }
3463 let position = current_position;
3464 window.defer_draw(element, current_position, 1);
3465 if !y_flipped {
3466 current_position.y += size.height + MENU_GAP;
3467 } else {
3468 current_position.y -= MENU_GAP;
3469 }
3470 (popover_type, Bounds::new(position, size))
3471 })
3472 .collect::<Vec<_>>();
3473
3474 if y_flipped {
3475 laid_out_popovers.reverse();
3476 }
3477
3478 Some((laid_out_popovers, y_flipped))
3479 }
3480
3481 #[allow(clippy::too_many_arguments)]
3482 fn layout_context_menu_aside(
3483 &self,
3484 y_flipped: bool,
3485 menu_bounds: Bounds<Pixels>,
3486 target_bounds: Bounds<Pixels>,
3487 max_target_bounds: Bounds<Pixels>,
3488 max_height: Pixels,
3489 must_place_above_or_below: bool,
3490 text_hitbox: &Hitbox,
3491 viewport_bounds: Bounds<Pixels>,
3492 window: &mut Window,
3493 cx: &mut App,
3494 ) {
3495 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3496 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3497 && !must_place_above_or_below
3498 {
3499 let max_width = cmp::min(
3500 available_within_viewport.right - px(1.),
3501 MENU_ASIDE_MAX_WIDTH,
3502 );
3503 let Some(mut aside) =
3504 self.render_context_menu_aside(size(max_width, max_height - POPOVER_Y_PADDING), cx)
3505 else {
3506 return;
3507 };
3508 aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3509 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3510 Some((aside, right_position))
3511 } else {
3512 let max_size = size(
3513 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3514 // won't be needed here.
3515 cmp::min(
3516 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3517 viewport_bounds.right(),
3518 ),
3519 cmp::min(
3520 max_height,
3521 cmp::max(
3522 available_within_viewport.top,
3523 available_within_viewport.bottom,
3524 ),
3525 ) - POPOVER_Y_PADDING,
3526 );
3527 let Some(mut aside) = self.render_context_menu_aside(max_size, cx) else {
3528 return;
3529 };
3530 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3531
3532 let top_position = point(
3533 menu_bounds.origin.x,
3534 target_bounds.top() - actual_size.height,
3535 );
3536 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3537
3538 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3539 // Prefer to fit on the same side of the line as the menu, then on the other side of
3540 // the line.
3541 if !y_flipped && wanted.height < available.bottom {
3542 Some(bottom_position)
3543 } else if !y_flipped && wanted.height < available.top {
3544 Some(top_position)
3545 } else if y_flipped && wanted.height < available.top {
3546 Some(top_position)
3547 } else if y_flipped && wanted.height < available.bottom {
3548 Some(bottom_position)
3549 } else {
3550 None
3551 }
3552 };
3553
3554 // Prefer choosing a direction using max sizes rather than actual size for stability.
3555 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3556 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3557 let aside_position = fit_within(available_within_text, wanted)
3558 // Fallback: fit max size in window.
3559 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3560 // Fallback: fit actual size in window.
3561 .or_else(|| fit_within(available_within_viewport, actual_size));
3562
3563 aside_position.map(|position| (aside, position))
3564 };
3565
3566 // Skip drawing if it doesn't fit anywhere.
3567 if let Some((aside, position)) = positioned_aside {
3568 window.defer_draw(aside, position, 1);
3569 }
3570 }
3571
3572 fn render_context_menu(
3573 &self,
3574 line_height: Pixels,
3575 height: Pixels,
3576 y_flipped: bool,
3577 window: &mut Window,
3578 cx: &mut App,
3579 ) -> Option<AnyElement> {
3580 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3581 self.editor.update(cx, |editor, cx| {
3582 editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3583 })
3584 }
3585
3586 fn render_context_menu_aside(
3587 &self,
3588 max_size: Size<Pixels>,
3589
3590 cx: &mut App,
3591 ) -> Option<AnyElement> {
3592 if max_size.width < px(100.) || max_size.height < px(12.) {
3593 None
3594 } else {
3595 self.editor.update(cx, |editor, cx| {
3596 editor.render_context_menu_aside(&self.style, max_size, cx)
3597 })
3598 }
3599 }
3600
3601 #[allow(clippy::too_many_arguments)]
3602 fn layout_inline_completion_popover(
3603 &self,
3604 text_bounds: &Bounds<Pixels>,
3605 editor_snapshot: &EditorSnapshot,
3606 visible_row_range: Range<DisplayRow>,
3607 scroll_top: f32,
3608 scroll_bottom: f32,
3609 line_layouts: &[LineWithInvisibles],
3610 line_height: Pixels,
3611 scroll_pixel_position: gpui::Point<Pixels>,
3612 newest_selection_head: Option<DisplayPoint>,
3613 editor_width: Pixels,
3614 style: &EditorStyle,
3615 window: &mut Window,
3616 cx: &mut App,
3617 ) -> Option<AnyElement> {
3618 const PADDING_X: Pixels = Pixels(24.);
3619 const PADDING_Y: Pixels = Pixels(2.);
3620
3621 let editor = self.editor.read(cx);
3622 let active_inline_completion = editor.active_inline_completion.as_ref()?;
3623
3624 if editor.inline_completion_visible_in_cursor_popover(true, cx) {
3625 return None;
3626 }
3627
3628 match &active_inline_completion.completion {
3629 InlineCompletion::Move { target, .. } => {
3630 let previewing = false;
3631 let target_display_point = target.to_display_point(editor_snapshot);
3632 if target_display_point.row().as_f32() < scroll_top {
3633 let mut element = inline_completion_accept_indicator(
3634 "Jump to Edit",
3635 Some(IconName::ArrowUp),
3636 previewing,
3637 self.editor.focus_handle(cx),
3638 window,
3639 cx,
3640 );
3641 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3642 let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
3643 element.prepaint_at(text_bounds.origin + offset, window, cx);
3644 Some(element)
3645 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
3646 let mut element = inline_completion_accept_indicator(
3647 "Jump to Edit",
3648 Some(IconName::ArrowDown),
3649 previewing,
3650 self.editor.focus_handle(cx),
3651 window,
3652 cx,
3653 );
3654 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3655 let offset = point(
3656 (text_bounds.size.width - size.width) / 2.,
3657 text_bounds.size.height - size.height - PADDING_Y,
3658 );
3659 element.prepaint_at(text_bounds.origin + offset, window, cx);
3660 Some(element)
3661 } else {
3662 let mut element = inline_completion_accept_indicator(
3663 "Jump to Edit",
3664 None,
3665 previewing,
3666 self.editor.focus_handle(cx),
3667 window,
3668 cx,
3669 );
3670
3671 let target_line_end = DisplayPoint::new(
3672 target_display_point.row(),
3673 editor_snapshot.line_len(target_display_point.row()),
3674 );
3675 let origin = self.editor.update(cx, |editor, _cx| {
3676 editor.display_to_pixel_point(target_line_end, editor_snapshot, window)
3677 })?;
3678 element.prepaint_as_root(
3679 text_bounds.origin + origin + point(PADDING_X, px(0.)),
3680 AvailableSpace::min_size(),
3681 window,
3682 cx,
3683 );
3684 Some(element)
3685 }
3686 }
3687 InlineCompletion::Edit {
3688 edits,
3689 edit_preview,
3690 display_mode,
3691 snapshot,
3692 } => {
3693 if self.editor.read(cx).has_visible_completions_menu() {
3694 return None;
3695 }
3696
3697 let edit_start = edits
3698 .first()
3699 .unwrap()
3700 .0
3701 .start
3702 .to_display_point(editor_snapshot);
3703 let edit_end = edits
3704 .last()
3705 .unwrap()
3706 .0
3707 .end
3708 .to_display_point(editor_snapshot);
3709
3710 let is_visible = visible_row_range.contains(&edit_start.row())
3711 || visible_row_range.contains(&edit_end.row());
3712 if !is_visible {
3713 return None;
3714 }
3715
3716 match display_mode {
3717 EditDisplayMode::TabAccept(previewing) => {
3718 let previewing = *previewing;
3719 let range = &edits.first()?.0;
3720 let target_display_point = range.end.to_display_point(editor_snapshot);
3721
3722 let target_line_end = DisplayPoint::new(
3723 target_display_point.row(),
3724 editor_snapshot.line_len(target_display_point.row()),
3725 );
3726 let origin = self.editor.update(cx, |editor, _cx| {
3727 editor.display_to_pixel_point(target_line_end, editor_snapshot, window)
3728 })?;
3729
3730 let mut element = inline_completion_accept_indicator(
3731 "Accept",
3732 None,
3733 previewing,
3734 self.editor.focus_handle(cx),
3735 window,
3736 cx,
3737 );
3738
3739 element.prepaint_as_root(
3740 text_bounds.origin + origin + point(PADDING_X, px(0.)),
3741 AvailableSpace::min_size(),
3742 window,
3743 cx,
3744 );
3745
3746 return Some(element);
3747 }
3748 EditDisplayMode::Inline => return None,
3749 EditDisplayMode::DiffPopover => {}
3750 }
3751
3752 let highlighted_edits = crate::inline_completion_edit_text(
3753 &snapshot,
3754 edits,
3755 edit_preview.as_ref()?,
3756 false,
3757 cx,
3758 );
3759
3760 let line_count = highlighted_edits.text.lines().count();
3761
3762 let longest_row =
3763 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
3764 let longest_line_width = if visible_row_range.contains(&longest_row) {
3765 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
3766 } else {
3767 layout_line(
3768 longest_row,
3769 editor_snapshot,
3770 style,
3771 editor_width,
3772 |_| false,
3773 window,
3774 cx,
3775 )
3776 .width
3777 };
3778
3779 let styled_text = highlighted_edits.to_styled_text(&style.text);
3780
3781 let mut element = div()
3782 .bg(cx.theme().colors().editor_background)
3783 .border_1()
3784 .border_color(cx.theme().colors().border)
3785 .rounded_md()
3786 .child(styled_text)
3787 .into_any();
3788
3789 let viewport_bounds = Bounds::new(Default::default(), window.viewport_size())
3790 .extend(Edges {
3791 right: -Self::SCROLLBAR_WIDTH,
3792 ..Default::default()
3793 });
3794
3795 let x_after_longest =
3796 text_bounds.origin.x + longest_line_width + PADDING_X - scroll_pixel_position.x;
3797
3798 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3799
3800 // Fully visible if it can be displayed within the window (allow overlapping other
3801 // panes). However, this is only allowed if the popover starts within text_bounds.
3802 let is_fully_visible = x_after_longest < text_bounds.right()
3803 && x_after_longest + element_bounds.width < viewport_bounds.right();
3804
3805 let origin = if is_fully_visible {
3806 point(
3807 x_after_longest,
3808 text_bounds.origin.y + edit_start.row().as_f32() * line_height
3809 - scroll_pixel_position.y,
3810 )
3811 } else {
3812 // Avoid overlapping both the edited rows and the user's cursor.
3813 let target_above = DisplayRow(
3814 edit_start
3815 .row()
3816 .0
3817 .min(
3818 newest_selection_head
3819 .map_or(u32::MAX, |cursor_row| cursor_row.row().0),
3820 )
3821 .saturating_sub(line_count as u32),
3822 );
3823 let mut row_target;
3824 if visible_row_range.contains(&DisplayRow(target_above.0.saturating_sub(1))) {
3825 row_target = target_above;
3826 } else {
3827 row_target = DisplayRow(
3828 edit_end.row().0.max(
3829 newest_selection_head.map_or(0, |cursor_row| cursor_row.row().0),
3830 ) + 1,
3831 );
3832 if !visible_row_range.contains(&row_target) {
3833 // Not visible, so fallback on displaying immediately below the cursor.
3834 if let Some(cursor) = newest_selection_head {
3835 row_target = DisplayRow(cursor.row().0 + 1);
3836 } else {
3837 // Not visible and no cursor visible, so fallback on displaying at the top of the editor.
3838 row_target = DisplayRow(0);
3839 }
3840 }
3841 };
3842
3843 text_bounds.origin
3844 + point(
3845 -scroll_pixel_position.x,
3846 row_target.as_f32() * line_height - scroll_pixel_position.y,
3847 )
3848 };
3849
3850 window.defer_draw(element, origin, 1);
3851
3852 // Do not return an element, since it will already be drawn due to defer_draw.
3853 None
3854 }
3855 }
3856 }
3857
3858 fn layout_mouse_context_menu(
3859 &self,
3860 editor_snapshot: &EditorSnapshot,
3861 visible_range: Range<DisplayRow>,
3862 content_origin: gpui::Point<Pixels>,
3863 window: &mut Window,
3864 cx: &mut App,
3865 ) -> Option<AnyElement> {
3866 let position = self.editor.update(cx, |editor, _cx| {
3867 let visible_start_point = editor.display_to_pixel_point(
3868 DisplayPoint::new(visible_range.start, 0),
3869 editor_snapshot,
3870 window,
3871 )?;
3872 let visible_end_point = editor.display_to_pixel_point(
3873 DisplayPoint::new(visible_range.end, 0),
3874 editor_snapshot,
3875 window,
3876 )?;
3877
3878 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3879 let (source_display_point, position) = match mouse_context_menu.position {
3880 MenuPosition::PinnedToScreen(point) => (None, point),
3881 MenuPosition::PinnedToEditor { source, offset } => {
3882 let source_display_point = source.to_display_point(editor_snapshot);
3883 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3884 let position = content_origin + source_point + offset;
3885 (Some(source_display_point), position)
3886 }
3887 };
3888
3889 let source_included = source_display_point.map_or(true, |source_display_point| {
3890 visible_range
3891 .to_inclusive()
3892 .contains(&source_display_point.row())
3893 });
3894 let position_included =
3895 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3896 if !source_included && !position_included {
3897 None
3898 } else {
3899 Some(position)
3900 }
3901 })?;
3902
3903 let mut element = self.editor.update(cx, |editor, _| {
3904 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3905 let context_menu = mouse_context_menu.context_menu.clone();
3906
3907 Some(
3908 deferred(
3909 anchored()
3910 .position(position)
3911 .child(context_menu)
3912 .anchor(Corner::TopLeft)
3913 .snap_to_window_with_margin(px(8.)),
3914 )
3915 .with_priority(1)
3916 .into_any(),
3917 )
3918 })?;
3919
3920 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3921 Some(element)
3922 }
3923
3924 #[allow(clippy::too_many_arguments)]
3925 fn layout_hover_popovers(
3926 &self,
3927 snapshot: &EditorSnapshot,
3928 hitbox: &Hitbox,
3929 text_hitbox: &Hitbox,
3930 visible_display_row_range: Range<DisplayRow>,
3931 content_origin: gpui::Point<Pixels>,
3932 scroll_pixel_position: gpui::Point<Pixels>,
3933 line_layouts: &[LineWithInvisibles],
3934 line_height: Pixels,
3935 em_width: Pixels,
3936 window: &mut Window,
3937 cx: &mut App,
3938 ) {
3939 struct MeasuredHoverPopover {
3940 element: AnyElement,
3941 size: Size<Pixels>,
3942 horizontal_offset: Pixels,
3943 }
3944
3945 let max_size = size(
3946 (120. * em_width) // Default size
3947 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3948 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3949 (16. * line_height) // Default size
3950 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3951 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3952 );
3953
3954 let hover_popovers = self.editor.update(cx, |editor, cx| {
3955 editor
3956 .hover_state
3957 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3958 });
3959 let Some((position, hover_popovers)) = hover_popovers else {
3960 return;
3961 };
3962
3963 // This is safe because we check on layout whether the required row is available
3964 let hovered_row_layout =
3965 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3966
3967 // Compute Hovered Point
3968 let x =
3969 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3970 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3971 let hovered_point = content_origin + point(x, y);
3972
3973 let mut overall_height = Pixels::ZERO;
3974 let mut measured_hover_popovers = Vec::new();
3975 for mut hover_popover in hover_popovers {
3976 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
3977 let horizontal_offset =
3978 (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3979
3980 overall_height += HOVER_POPOVER_GAP + size.height;
3981
3982 measured_hover_popovers.push(MeasuredHoverPopover {
3983 element: hover_popover,
3984 size,
3985 horizontal_offset,
3986 });
3987 }
3988 overall_height += HOVER_POPOVER_GAP;
3989
3990 fn draw_occluder(
3991 width: Pixels,
3992 origin: gpui::Point<Pixels>,
3993 window: &mut Window,
3994 cx: &mut App,
3995 ) {
3996 let mut occlusion = div()
3997 .size_full()
3998 .occlude()
3999 .on_mouse_move(|_, _, cx| cx.stop_propagation())
4000 .into_any_element();
4001 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4002 window.defer_draw(occlusion, origin, 2);
4003 }
4004
4005 if hovered_point.y > overall_height {
4006 // There is enough space above. Render popovers above the hovered point
4007 let mut current_y = hovered_point.y;
4008 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4009 let size = popover.size;
4010 let popover_origin = point(
4011 hovered_point.x + popover.horizontal_offset,
4012 current_y - size.height,
4013 );
4014
4015 window.defer_draw(popover.element, popover_origin, 2);
4016 if position != itertools::Position::Last {
4017 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4018 draw_occluder(size.width, origin, window, cx);
4019 }
4020
4021 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4022 }
4023 } else {
4024 // There is not enough space above. Render popovers below the hovered point
4025 let mut current_y = hovered_point.y + line_height;
4026 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4027 let size = popover.size;
4028 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4029
4030 window.defer_draw(popover.element, popover_origin, 2);
4031 if position != itertools::Position::Last {
4032 let origin = point(popover_origin.x, popover_origin.y + size.height);
4033 draw_occluder(size.width, origin, window, cx);
4034 }
4035
4036 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4037 }
4038 }
4039 }
4040
4041 #[allow(clippy::too_many_arguments)]
4042 fn layout_diff_hunk_controls(
4043 &self,
4044 row_range: Range<DisplayRow>,
4045 row_infos: &[RowInfo],
4046 text_hitbox: &Hitbox,
4047 position_map: &PositionMap,
4048 newest_cursor_position: Option<DisplayPoint>,
4049 line_height: Pixels,
4050 scroll_pixel_position: gpui::Point<Pixels>,
4051 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4052 editor: Entity<Editor>,
4053 window: &mut Window,
4054 cx: &mut App,
4055 ) -> Vec<AnyElement> {
4056 let point_for_position = position_map.point_for_position(window.mouse_position());
4057
4058 let mut controls = vec![];
4059
4060 let active_positions = [
4061 Some(point_for_position.previous_valid),
4062 newest_cursor_position,
4063 ];
4064
4065 for (hunk, _) in display_hunks {
4066 if let DisplayDiffHunk::Unfolded {
4067 display_row_range,
4068 multi_buffer_range,
4069 status,
4070 ..
4071 } = &hunk
4072 {
4073 if display_row_range.start < row_range.start
4074 || display_row_range.start >= row_range.end
4075 {
4076 continue;
4077 }
4078 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4079 if row_infos[row_ix].diff_status.is_none() {
4080 continue;
4081 }
4082 if row_infos[row_ix].diff_status == Some(DiffHunkStatus::Added)
4083 && *status != DiffHunkStatus::Added
4084 {
4085 continue;
4086 }
4087 if active_positions
4088 .iter()
4089 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4090 {
4091 let y = display_row_range.start.as_f32() * line_height
4092 + text_hitbox.bounds.top()
4093 - scroll_pixel_position.y;
4094 let x = text_hitbox.bounds.right() - px(100.);
4095
4096 let mut element = diff_hunk_controls(
4097 display_row_range.start.0,
4098 multi_buffer_range.clone(),
4099 line_height,
4100 &editor,
4101 cx,
4102 );
4103 element.prepaint_as_root(
4104 gpui::Point::new(x, y),
4105 size(px(100.0), line_height).into(),
4106 window,
4107 cx,
4108 );
4109 controls.push(element);
4110 }
4111 }
4112 }
4113
4114 controls
4115 }
4116
4117 #[allow(clippy::too_many_arguments)]
4118 fn layout_signature_help(
4119 &self,
4120 hitbox: &Hitbox,
4121 content_origin: gpui::Point<Pixels>,
4122 scroll_pixel_position: gpui::Point<Pixels>,
4123 newest_selection_head: Option<DisplayPoint>,
4124 start_row: DisplayRow,
4125 line_layouts: &[LineWithInvisibles],
4126 line_height: Pixels,
4127 em_width: Pixels,
4128 window: &mut Window,
4129 cx: &mut App,
4130 ) {
4131 if !self.editor.focus_handle(cx).is_focused(window) {
4132 return;
4133 }
4134 let Some(newest_selection_head) = newest_selection_head else {
4135 return;
4136 };
4137 let selection_row = newest_selection_head.row();
4138 if selection_row < start_row {
4139 return;
4140 }
4141 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4142 else {
4143 return;
4144 };
4145
4146 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4147 - scroll_pixel_position.x
4148 + content_origin.x;
4149 let start_y =
4150 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4151
4152 let max_size = size(
4153 (120. * em_width) // Default size
4154 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4155 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4156 (16. * line_height) // Default size
4157 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4158 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4159 );
4160
4161 let maybe_element = self.editor.update(cx, |editor, cx| {
4162 if let Some(popover) = editor.signature_help_state.popover_mut() {
4163 let element = popover.render(
4164 &self.style,
4165 max_size,
4166 editor.workspace.as_ref().map(|(w, _)| w.clone()),
4167 cx,
4168 );
4169 Some(element)
4170 } else {
4171 None
4172 }
4173 });
4174 if let Some(mut element) = maybe_element {
4175 let window_size = window.viewport_size();
4176 let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4177 let mut point = point(start_x, start_y - size.height);
4178
4179 // Adjusting to ensure the popover does not overflow in the X-axis direction.
4180 if point.x + size.width >= window_size.width {
4181 point.x = window_size.width - size.width;
4182 }
4183
4184 window.defer_draw(element, point, 1)
4185 }
4186 }
4187
4188 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4189 window.paint_layer(layout.hitbox.bounds, |window| {
4190 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4191 let gutter_bg = cx.theme().colors().editor_gutter_background;
4192 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4193 window.paint_quad(fill(
4194 layout.position_map.text_hitbox.bounds,
4195 self.style.background,
4196 ));
4197
4198 if let EditorMode::Full = layout.mode {
4199 let mut active_rows = layout.active_rows.iter().peekable();
4200 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4201 let mut end_row = start_row.0;
4202 while active_rows
4203 .peek()
4204 .map_or(false, |(active_row, has_selection)| {
4205 active_row.0 == end_row + 1
4206 && *has_selection == contains_non_empty_selection
4207 })
4208 {
4209 active_rows.next().unwrap();
4210 end_row += 1;
4211 }
4212
4213 if !contains_non_empty_selection {
4214 let highlight_h_range =
4215 match layout.position_map.snapshot.current_line_highlight {
4216 CurrentLineHighlight::Gutter => Some(Range {
4217 start: layout.hitbox.left(),
4218 end: layout.gutter_hitbox.right(),
4219 }),
4220 CurrentLineHighlight::Line => Some(Range {
4221 start: layout.position_map.text_hitbox.bounds.left(),
4222 end: layout.position_map.text_hitbox.bounds.right(),
4223 }),
4224 CurrentLineHighlight::All => Some(Range {
4225 start: layout.hitbox.left(),
4226 end: layout.hitbox.right(),
4227 }),
4228 CurrentLineHighlight::None => None,
4229 };
4230 if let Some(range) = highlight_h_range {
4231 let active_line_bg = cx.theme().colors().editor_active_line_background;
4232 let bounds = Bounds {
4233 origin: point(
4234 range.start,
4235 layout.hitbox.origin.y
4236 + (start_row.as_f32() - scroll_top)
4237 * layout.position_map.line_height,
4238 ),
4239 size: size(
4240 range.end - range.start,
4241 layout.position_map.line_height
4242 * (end_row - start_row.0 + 1) as f32,
4243 ),
4244 };
4245 window.paint_quad(fill(bounds, active_line_bg));
4246 }
4247 }
4248 }
4249
4250 let mut paint_highlight =
4251 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4252 let origin = point(
4253 layout.hitbox.origin.x,
4254 layout.hitbox.origin.y
4255 + (highlight_row_start.as_f32() - scroll_top)
4256 * layout.position_map.line_height,
4257 );
4258 let size = size(
4259 layout.hitbox.size.width,
4260 layout.position_map.line_height
4261 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4262 );
4263 window.paint_quad(fill(Bounds { origin, size }, color));
4264 };
4265
4266 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
4267 for (&new_row, &new_color) in &layout.highlighted_rows {
4268 match &mut current_paint {
4269 Some((current_color, current_range)) => {
4270 let current_color = *current_color;
4271 let new_range_started = current_color != new_color
4272 || current_range.end.next_row() != new_row;
4273 if new_range_started {
4274 paint_highlight(
4275 current_range.start,
4276 current_range.end,
4277 current_color,
4278 );
4279 current_paint = Some((new_color, new_row..new_row));
4280 continue;
4281 } else {
4282 current_range.end = current_range.end.next_row();
4283 }
4284 }
4285 None => current_paint = Some((new_color, new_row..new_row)),
4286 };
4287 }
4288 if let Some((color, range)) = current_paint {
4289 paint_highlight(range.start, range.end, color);
4290 }
4291
4292 let scroll_left =
4293 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4294
4295 for (wrap_position, active) in layout.wrap_guides.iter() {
4296 let x = (layout.position_map.text_hitbox.origin.x
4297 + *wrap_position
4298 + layout.position_map.em_width / 2.)
4299 - scroll_left;
4300
4301 let show_scrollbars = {
4302 let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4303
4304 scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4305 || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4306 };
4307
4308 if x < layout.position_map.text_hitbox.origin.x
4309 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4310 {
4311 continue;
4312 }
4313
4314 let color = if *active {
4315 cx.theme().colors().editor_active_wrap_guide
4316 } else {
4317 cx.theme().colors().editor_wrap_guide
4318 };
4319 window.paint_quad(fill(
4320 Bounds {
4321 origin: point(x, layout.position_map.text_hitbox.origin.y),
4322 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4323 },
4324 color,
4325 ));
4326 }
4327 }
4328 })
4329 }
4330
4331 fn paint_indent_guides(
4332 &mut self,
4333 layout: &mut EditorLayout,
4334 window: &mut Window,
4335 cx: &mut App,
4336 ) {
4337 let Some(indent_guides) = &layout.indent_guides else {
4338 return;
4339 };
4340
4341 let faded_color = |color: Hsla, alpha: f32| {
4342 let mut faded = color;
4343 faded.a = alpha;
4344 faded
4345 };
4346
4347 for indent_guide in indent_guides {
4348 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4349 let settings = indent_guide.settings;
4350
4351 // TODO fixed for now, expose them through themes later
4352 const INDENT_AWARE_ALPHA: f32 = 0.2;
4353 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4354 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4355 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4356
4357 let line_color = match (settings.coloring, indent_guide.active) {
4358 (IndentGuideColoring::Disabled, _) => None,
4359 (IndentGuideColoring::Fixed, false) => {
4360 Some(cx.theme().colors().editor_indent_guide)
4361 }
4362 (IndentGuideColoring::Fixed, true) => {
4363 Some(cx.theme().colors().editor_indent_guide_active)
4364 }
4365 (IndentGuideColoring::IndentAware, false) => {
4366 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4367 }
4368 (IndentGuideColoring::IndentAware, true) => {
4369 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4370 }
4371 };
4372
4373 let background_color = match (settings.background_coloring, indent_guide.active) {
4374 (IndentGuideBackgroundColoring::Disabled, _) => None,
4375 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4376 indent_accent_colors,
4377 INDENT_AWARE_BACKGROUND_ALPHA,
4378 )),
4379 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4380 indent_accent_colors,
4381 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4382 )),
4383 };
4384
4385 let requested_line_width = if indent_guide.active {
4386 settings.active_line_width
4387 } else {
4388 settings.line_width
4389 }
4390 .clamp(1, 10);
4391 let mut line_indicator_width = 0.;
4392 if let Some(color) = line_color {
4393 window.paint_quad(fill(
4394 Bounds {
4395 origin: indent_guide.origin,
4396 size: size(px(requested_line_width as f32), indent_guide.length),
4397 },
4398 color,
4399 ));
4400 line_indicator_width = requested_line_width as f32;
4401 }
4402
4403 if let Some(color) = background_color {
4404 let width = indent_guide.single_indent_width - px(line_indicator_width);
4405 window.paint_quad(fill(
4406 Bounds {
4407 origin: point(
4408 indent_guide.origin.x + px(line_indicator_width),
4409 indent_guide.origin.y,
4410 ),
4411 size: size(width, indent_guide.length),
4412 },
4413 color,
4414 ));
4415 }
4416 }
4417 }
4418
4419 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4420 let is_singleton = self.editor.read(cx).is_singleton(cx);
4421
4422 let line_height = layout.position_map.line_height;
4423 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4424
4425 for LineNumberLayout {
4426 shaped_line,
4427 hitbox,
4428 display_row,
4429 } in layout.line_numbers.values()
4430 {
4431 let Some(hitbox) = hitbox else {
4432 continue;
4433 };
4434
4435 let is_active = layout.active_rows.contains_key(&display_row);
4436
4437 let color = if is_active {
4438 cx.theme().colors().editor_active_line_number
4439 } else if !is_singleton && hitbox.is_hovered(window) {
4440 cx.theme().colors().editor_hover_line_number
4441 } else {
4442 cx.theme().colors().editor_line_number
4443 };
4444
4445 let Some(line) = self
4446 .shape_line_number(shaped_line.text.clone(), color, window)
4447 .log_err()
4448 else {
4449 continue;
4450 };
4451 let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4452 continue;
4453 };
4454 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4455 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4456 if is_singleton {
4457 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4458 } else {
4459 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4460 }
4461 }
4462 }
4463
4464 fn paint_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4465 if layout.display_hunks.is_empty() {
4466 return;
4467 }
4468
4469 let line_height = layout.position_map.line_height;
4470 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4471 for (hunk, hitbox) in &layout.display_hunks {
4472 let hunk_to_paint = match hunk {
4473 DisplayDiffHunk::Folded { .. } => {
4474 let hunk_bounds = Self::diff_hunk_bounds(
4475 &layout.position_map.snapshot,
4476 line_height,
4477 layout.gutter_hitbox.bounds,
4478 hunk,
4479 );
4480 Some((
4481 hunk_bounds,
4482 cx.theme().status().modified,
4483 Corners::all(px(0.)),
4484 ))
4485 }
4486 DisplayDiffHunk::Unfolded {
4487 status,
4488 display_row_range,
4489 ..
4490 } => hitbox.as_ref().map(|hunk_hitbox| match status {
4491 DiffHunkStatus::Added => (
4492 hunk_hitbox.bounds,
4493 cx.theme().status().created,
4494 Corners::all(px(0.)),
4495 ),
4496 DiffHunkStatus::Modified => (
4497 hunk_hitbox.bounds,
4498 cx.theme().status().modified,
4499 Corners::all(px(0.)),
4500 ),
4501 DiffHunkStatus::Removed if !display_row_range.is_empty() => (
4502 hunk_hitbox.bounds,
4503 cx.theme().status().deleted,
4504 Corners::all(px(0.)),
4505 ),
4506 DiffHunkStatus::Removed => (
4507 Bounds::new(
4508 point(
4509 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4510 hunk_hitbox.origin.y,
4511 ),
4512 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4513 ),
4514 cx.theme().status().deleted,
4515 Corners::all(1. * line_height),
4516 ),
4517 }),
4518 };
4519
4520 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
4521 window.paint_quad(quad(
4522 hunk_bounds,
4523 corner_radii,
4524 background_color,
4525 Edges::default(),
4526 transparent_black(),
4527 ));
4528 }
4529 }
4530 });
4531 }
4532
4533 fn diff_hunk_bounds(
4534 snapshot: &EditorSnapshot,
4535 line_height: Pixels,
4536 gutter_bounds: Bounds<Pixels>,
4537 hunk: &DisplayDiffHunk,
4538 ) -> Bounds<Pixels> {
4539 let scroll_position = snapshot.scroll_position();
4540 let scroll_top = scroll_position.y * line_height;
4541 let gutter_strip_width = (0.275 * line_height).floor();
4542
4543 match hunk {
4544 DisplayDiffHunk::Folded { display_row, .. } => {
4545 let start_y = display_row.as_f32() * line_height - scroll_top;
4546 let end_y = start_y + line_height;
4547 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4548 let highlight_size = size(gutter_strip_width, end_y - start_y);
4549 Bounds::new(highlight_origin, highlight_size)
4550 }
4551 DisplayDiffHunk::Unfolded {
4552 display_row_range,
4553 status,
4554 ..
4555 } => {
4556 if *status == DiffHunkStatus::Removed && display_row_range.is_empty() {
4557 let row = display_row_range.start;
4558
4559 let offset = line_height / 2.;
4560 let start_y = row.as_f32() * line_height - offset - scroll_top;
4561 let end_y = start_y + line_height;
4562
4563 let width = (0.35 * line_height).floor();
4564 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4565 let highlight_size = size(width, end_y - start_y);
4566 Bounds::new(highlight_origin, highlight_size)
4567 } else {
4568 let start_row = display_row_range.start;
4569 let end_row = display_row_range.end;
4570 // If we're in a multibuffer, row range span might include an
4571 // excerpt header, so if we were to draw the marker straight away,
4572 // the hunk might include the rows of that header.
4573 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4574 // Instead, we simply check whether the range we're dealing with includes
4575 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4576 let end_row_in_current_excerpt = snapshot
4577 .blocks_in_range(start_row..end_row)
4578 .find_map(|(start_row, block)| {
4579 if matches!(block, Block::ExcerptBoundary { .. }) {
4580 Some(start_row)
4581 } else {
4582 None
4583 }
4584 })
4585 .unwrap_or(end_row);
4586
4587 let start_y = start_row.as_f32() * line_height - scroll_top;
4588 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4589
4590 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4591 let highlight_size = size(gutter_strip_width, end_y - start_y);
4592 Bounds::new(highlight_origin, highlight_size)
4593 }
4594 }
4595 }
4596 }
4597
4598 fn paint_gutter_indicators(
4599 &self,
4600 layout: &mut EditorLayout,
4601 window: &mut Window,
4602 cx: &mut App,
4603 ) {
4604 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4605 window.with_element_namespace("crease_toggles", |window| {
4606 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4607 crease_toggle.paint(window, cx);
4608 }
4609 });
4610
4611 for test_indicator in layout.test_indicators.iter_mut() {
4612 test_indicator.paint(window, cx);
4613 }
4614
4615 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4616 indicator.paint(window, cx);
4617 }
4618 });
4619 }
4620
4621 fn paint_gutter_highlights(
4622 &self,
4623 layout: &mut EditorLayout,
4624 window: &mut Window,
4625 cx: &mut App,
4626 ) {
4627 for (_, hunk_hitbox) in &layout.display_hunks {
4628 if let Some(hunk_hitbox) = hunk_hitbox {
4629 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4630 }
4631 }
4632
4633 let show_git_gutter = layout
4634 .position_map
4635 .snapshot
4636 .show_git_diff_gutter
4637 .unwrap_or_else(|| {
4638 matches!(
4639 ProjectSettings::get_global(cx).git.git_gutter,
4640 Some(GitGutterSetting::TrackedFiles)
4641 )
4642 });
4643 if show_git_gutter {
4644 Self::paint_diff_hunks(layout, window, cx)
4645 }
4646
4647 let highlight_width = 0.275 * layout.position_map.line_height;
4648 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4649 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4650 for (range, color) in &layout.highlighted_gutter_ranges {
4651 let start_row = if range.start.row() < layout.visible_display_row_range.start {
4652 layout.visible_display_row_range.start - DisplayRow(1)
4653 } else {
4654 range.start.row()
4655 };
4656 let end_row = if range.end.row() > layout.visible_display_row_range.end {
4657 layout.visible_display_row_range.end + DisplayRow(1)
4658 } else {
4659 range.end.row()
4660 };
4661
4662 let start_y = layout.gutter_hitbox.top()
4663 + start_row.0 as f32 * layout.position_map.line_height
4664 - layout.position_map.scroll_pixel_position.y;
4665 let end_y = layout.gutter_hitbox.top()
4666 + (end_row.0 + 1) as f32 * layout.position_map.line_height
4667 - layout.position_map.scroll_pixel_position.y;
4668 let bounds = Bounds::from_corners(
4669 point(layout.gutter_hitbox.left(), start_y),
4670 point(layout.gutter_hitbox.left() + highlight_width, end_y),
4671 );
4672 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4673 }
4674 });
4675 }
4676
4677 fn paint_blamed_display_rows(
4678 &self,
4679 layout: &mut EditorLayout,
4680 window: &mut Window,
4681 cx: &mut App,
4682 ) {
4683 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4684 return;
4685 };
4686
4687 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4688 for mut blame_element in blamed_display_rows.into_iter() {
4689 blame_element.paint(window, cx);
4690 }
4691 })
4692 }
4693
4694 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4695 window.with_content_mask(
4696 Some(ContentMask {
4697 bounds: layout.position_map.text_hitbox.bounds,
4698 }),
4699 |window| {
4700 let cursor_style = if self
4701 .editor
4702 .read(cx)
4703 .hovered_link_state
4704 .as_ref()
4705 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4706 {
4707 CursorStyle::PointingHand
4708 } else {
4709 CursorStyle::IBeam
4710 };
4711 window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4712
4713 let invisible_display_ranges = self.paint_highlights(layout, window);
4714 self.paint_lines(&invisible_display_ranges, layout, window, cx);
4715 self.paint_redactions(layout, window);
4716 self.paint_cursors(layout, window, cx);
4717 self.paint_inline_blame(layout, window, cx);
4718 self.paint_diff_hunk_controls(layout, window, cx);
4719 window.with_element_namespace("crease_trailers", |window| {
4720 for trailer in layout.crease_trailers.iter_mut().flatten() {
4721 trailer.element.paint(window, cx);
4722 }
4723 });
4724 },
4725 )
4726 }
4727
4728 fn paint_highlights(
4729 &mut self,
4730 layout: &mut EditorLayout,
4731 window: &mut Window,
4732 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4733 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4734 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4735 let line_end_overshoot = 0.15 * layout.position_map.line_height;
4736 for (range, color) in &layout.highlighted_ranges {
4737 self.paint_highlighted_range(
4738 range.clone(),
4739 *color,
4740 Pixels::ZERO,
4741 line_end_overshoot,
4742 layout,
4743 window,
4744 );
4745 }
4746
4747 let corner_radius = 0.15 * layout.position_map.line_height;
4748
4749 for (player_color, selections) in &layout.selections {
4750 for selection in selections.iter() {
4751 self.paint_highlighted_range(
4752 selection.range.clone(),
4753 player_color.selection,
4754 corner_radius,
4755 corner_radius * 2.,
4756 layout,
4757 window,
4758 );
4759
4760 if selection.is_local && !selection.range.is_empty() {
4761 invisible_display_ranges.push(selection.range.clone());
4762 }
4763 }
4764 }
4765 invisible_display_ranges
4766 })
4767 }
4768
4769 fn paint_lines(
4770 &mut self,
4771 invisible_display_ranges: &[Range<DisplayPoint>],
4772 layout: &mut EditorLayout,
4773 window: &mut Window,
4774 cx: &mut App,
4775 ) {
4776 let whitespace_setting = self
4777 .editor
4778 .read(cx)
4779 .buffer
4780 .read(cx)
4781 .settings_at(0, cx)
4782 .show_whitespaces;
4783
4784 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4785 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4786 line_with_invisibles.draw(
4787 layout,
4788 row,
4789 layout.content_origin,
4790 whitespace_setting,
4791 invisible_display_ranges,
4792 window,
4793 cx,
4794 )
4795 }
4796
4797 for line_element in &mut layout.line_elements {
4798 line_element.paint(window, cx);
4799 }
4800 }
4801
4802 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4803 if layout.redacted_ranges.is_empty() {
4804 return;
4805 }
4806
4807 let line_end_overshoot = layout.line_end_overshoot();
4808
4809 // A softer than perfect black
4810 let redaction_color = gpui::rgb(0x0e1111);
4811
4812 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4813 for range in layout.redacted_ranges.iter() {
4814 self.paint_highlighted_range(
4815 range.clone(),
4816 redaction_color.into(),
4817 Pixels::ZERO,
4818 line_end_overshoot,
4819 layout,
4820 window,
4821 );
4822 }
4823 });
4824 }
4825
4826 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4827 for cursor in &mut layout.visible_cursors {
4828 cursor.paint(layout.content_origin, window, cx);
4829 }
4830 }
4831
4832 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4833 let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4834
4835 if let Some(scrollbar_layout) = scrollbar_x {
4836 let hitbox = scrollbar_layout.hitbox.clone();
4837 let text_unit_size = scrollbar_layout.text_unit_size;
4838 let visible_range = scrollbar_layout.visible_range.clone();
4839 let thumb_bounds = scrollbar_layout.thumb_bounds();
4840
4841 if scrollbar_layout.visible {
4842 window.paint_layer(hitbox.bounds, |window| {
4843 window.paint_quad(quad(
4844 hitbox.bounds,
4845 Corners::default(),
4846 cx.theme().colors().scrollbar_track_background,
4847 Edges {
4848 top: Pixels::ZERO,
4849 right: Pixels::ZERO,
4850 bottom: Pixels::ZERO,
4851 left: Pixels::ZERO,
4852 },
4853 cx.theme().colors().scrollbar_track_border,
4854 ));
4855
4856 window.paint_quad(quad(
4857 thumb_bounds,
4858 Corners::default(),
4859 cx.theme().colors().scrollbar_thumb_background,
4860 Edges {
4861 top: Pixels::ZERO,
4862 right: Pixels::ZERO,
4863 bottom: Pixels::ZERO,
4864 left: ScrollbarLayout::BORDER_WIDTH,
4865 },
4866 cx.theme().colors().scrollbar_thumb_border,
4867 ));
4868 })
4869 }
4870
4871 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4872
4873 window.on_mouse_event({
4874 let editor = self.editor.clone();
4875
4876 // there may be a way to avoid this clone
4877 let hitbox = hitbox.clone();
4878
4879 let mut mouse_position = window.mouse_position();
4880 move |event: &MouseMoveEvent, phase, window, cx| {
4881 if phase == DispatchPhase::Capture {
4882 return;
4883 }
4884
4885 editor.update(cx, |editor, cx| {
4886 if event.pressed_button == Some(MouseButton::Left)
4887 && editor
4888 .scroll_manager
4889 .is_dragging_scrollbar(Axis::Horizontal)
4890 {
4891 let x = mouse_position.x;
4892 let new_x = event.position.x;
4893 if (hitbox.left()..hitbox.right()).contains(&x) {
4894 let mut position = editor.scroll_position(cx);
4895
4896 position.x += (new_x - x) / text_unit_size;
4897 if position.x < 0.0 {
4898 position.x = 0.0;
4899 }
4900 editor.set_scroll_position(position, window, cx);
4901 }
4902
4903 cx.stop_propagation();
4904 } else {
4905 editor.scroll_manager.set_is_dragging_scrollbar(
4906 Axis::Horizontal,
4907 false,
4908 cx,
4909 );
4910
4911 if hitbox.is_hovered(window) {
4912 editor.scroll_manager.show_scrollbar(window, cx);
4913 }
4914 }
4915 mouse_position = event.position;
4916 })
4917 }
4918 });
4919
4920 if self
4921 .editor
4922 .read(cx)
4923 .scroll_manager
4924 .is_dragging_scrollbar(Axis::Horizontal)
4925 {
4926 window.on_mouse_event({
4927 let editor = self.editor.clone();
4928 move |_: &MouseUpEvent, phase, _, cx| {
4929 if phase == DispatchPhase::Capture {
4930 return;
4931 }
4932
4933 editor.update(cx, |editor, cx| {
4934 editor.scroll_manager.set_is_dragging_scrollbar(
4935 Axis::Horizontal,
4936 false,
4937 cx,
4938 );
4939 cx.stop_propagation();
4940 });
4941 }
4942 });
4943 } else {
4944 window.on_mouse_event({
4945 let editor = self.editor.clone();
4946
4947 move |event: &MouseDownEvent, phase, window, cx| {
4948 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
4949 return;
4950 }
4951
4952 editor.update(cx, |editor, cx| {
4953 editor.scroll_manager.set_is_dragging_scrollbar(
4954 Axis::Horizontal,
4955 true,
4956 cx,
4957 );
4958
4959 let x = event.position.x;
4960
4961 if x < thumb_bounds.left() || thumb_bounds.right() < x {
4962 let center_row =
4963 ((x - hitbox.left()) / text_unit_size).round() as u32;
4964 let top_row = center_row.saturating_sub(
4965 (visible_range.end - visible_range.start) as u32 / 2,
4966 );
4967
4968 let mut position = editor.scroll_position(cx);
4969 position.x = top_row as f32;
4970
4971 editor.set_scroll_position(position, window, cx);
4972 } else {
4973 editor.scroll_manager.show_scrollbar(window, cx);
4974 }
4975
4976 cx.stop_propagation();
4977 });
4978 }
4979 });
4980 }
4981 }
4982
4983 if let Some(scrollbar_layout) = scrollbar_y {
4984 let hitbox = scrollbar_layout.hitbox.clone();
4985 let text_unit_size = scrollbar_layout.text_unit_size;
4986 let visible_range = scrollbar_layout.visible_range.clone();
4987 let thumb_bounds = scrollbar_layout.thumb_bounds();
4988
4989 if scrollbar_layout.visible {
4990 window.paint_layer(hitbox.bounds, |window| {
4991 window.paint_quad(quad(
4992 hitbox.bounds,
4993 Corners::default(),
4994 cx.theme().colors().scrollbar_track_background,
4995 Edges {
4996 top: Pixels::ZERO,
4997 right: Pixels::ZERO,
4998 bottom: Pixels::ZERO,
4999 left: ScrollbarLayout::BORDER_WIDTH,
5000 },
5001 cx.theme().colors().scrollbar_track_border,
5002 ));
5003
5004 let fast_markers =
5005 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5006 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5007 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5008
5009 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5010 for marker in markers.iter().chain(&fast_markers) {
5011 let mut marker = marker.clone();
5012 marker.bounds.origin += hitbox.origin;
5013 window.paint_quad(marker);
5014 }
5015
5016 window.paint_quad(quad(
5017 thumb_bounds,
5018 Corners::default(),
5019 cx.theme().colors().scrollbar_thumb_background,
5020 Edges {
5021 top: Pixels::ZERO,
5022 right: Pixels::ZERO,
5023 bottom: Pixels::ZERO,
5024 left: ScrollbarLayout::BORDER_WIDTH,
5025 },
5026 cx.theme().colors().scrollbar_thumb_border,
5027 ));
5028 });
5029 }
5030
5031 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5032
5033 window.on_mouse_event({
5034 let editor = self.editor.clone();
5035
5036 let hitbox = hitbox.clone();
5037
5038 let mut mouse_position = window.mouse_position();
5039 move |event: &MouseMoveEvent, phase, window, cx| {
5040 if phase == DispatchPhase::Capture {
5041 return;
5042 }
5043
5044 editor.update(cx, |editor, cx| {
5045 if event.pressed_button == Some(MouseButton::Left)
5046 && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5047 {
5048 let y = mouse_position.y;
5049 let new_y = event.position.y;
5050 if (hitbox.top()..hitbox.bottom()).contains(&y) {
5051 let mut position = editor.scroll_position(cx);
5052 position.y += (new_y - y) / text_unit_size;
5053 if position.y < 0.0 {
5054 position.y = 0.0;
5055 }
5056 editor.set_scroll_position(position, window, cx);
5057 }
5058 } else {
5059 editor.scroll_manager.set_is_dragging_scrollbar(
5060 Axis::Vertical,
5061 false,
5062 cx,
5063 );
5064
5065 if hitbox.is_hovered(window) {
5066 editor.scroll_manager.show_scrollbar(window, cx);
5067 }
5068 }
5069 mouse_position = event.position;
5070 })
5071 }
5072 });
5073
5074 if self
5075 .editor
5076 .read(cx)
5077 .scroll_manager
5078 .is_dragging_scrollbar(Axis::Vertical)
5079 {
5080 window.on_mouse_event({
5081 let editor = self.editor.clone();
5082 move |_: &MouseUpEvent, phase, _, cx| {
5083 if phase == DispatchPhase::Capture {
5084 return;
5085 }
5086
5087 editor.update(cx, |editor, cx| {
5088 editor.scroll_manager.set_is_dragging_scrollbar(
5089 Axis::Vertical,
5090 false,
5091 cx,
5092 );
5093 cx.stop_propagation();
5094 });
5095 }
5096 });
5097 } else {
5098 window.on_mouse_event({
5099 let editor = self.editor.clone();
5100
5101 move |event: &MouseDownEvent, phase, window, cx| {
5102 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5103 return;
5104 }
5105
5106 editor.update(cx, |editor, cx| {
5107 editor.scroll_manager.set_is_dragging_scrollbar(
5108 Axis::Vertical,
5109 true,
5110 cx,
5111 );
5112
5113 let y = event.position.y;
5114 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5115 let center_row =
5116 ((y - hitbox.top()) / text_unit_size).round() as u32;
5117 let top_row = center_row.saturating_sub(
5118 (visible_range.end - visible_range.start) as u32 / 2,
5119 );
5120 let mut position = editor.scroll_position(cx);
5121 position.y = top_row as f32;
5122 editor.set_scroll_position(position, window, cx);
5123 } else {
5124 editor.scroll_manager.show_scrollbar(window, cx);
5125 }
5126
5127 cx.stop_propagation();
5128 });
5129 }
5130 });
5131 }
5132 }
5133 }
5134
5135 fn collect_fast_scrollbar_markers(
5136 &self,
5137 layout: &EditorLayout,
5138 scrollbar_layout: &ScrollbarLayout,
5139 cx: &mut App,
5140 ) -> Vec<PaintQuad> {
5141 const LIMIT: usize = 100;
5142 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5143 return vec![];
5144 }
5145 let cursor_ranges = layout
5146 .cursors
5147 .iter()
5148 .map(|(point, color)| ColoredRange {
5149 start: point.row(),
5150 end: point.row(),
5151 color: *color,
5152 })
5153 .collect_vec();
5154 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5155 }
5156
5157 fn refresh_slow_scrollbar_markers(
5158 &self,
5159 layout: &EditorLayout,
5160 scrollbar_layout: &ScrollbarLayout,
5161 window: &mut Window,
5162 cx: &mut App,
5163 ) {
5164 self.editor.update(cx, |editor, cx| {
5165 if !editor.is_singleton(cx)
5166 || !editor
5167 .scrollbar_marker_state
5168 .should_refresh(scrollbar_layout.hitbox.size)
5169 {
5170 return;
5171 }
5172
5173 let scrollbar_layout = scrollbar_layout.clone();
5174 let background_highlights = editor.background_highlights.clone();
5175 let snapshot = layout.position_map.snapshot.clone();
5176 let theme = cx.theme().clone();
5177 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5178
5179 editor.scrollbar_marker_state.dirty = false;
5180 editor.scrollbar_marker_state.pending_refresh =
5181 Some(cx.spawn_in(window, |editor, mut cx| async move {
5182 let scrollbar_size = scrollbar_layout.hitbox.size;
5183 let scrollbar_markers = cx
5184 .background_executor()
5185 .spawn(async move {
5186 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5187 let mut marker_quads = Vec::new();
5188 if scrollbar_settings.git_diff {
5189 let marker_row_ranges =
5190 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5191 let start_display_row =
5192 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5193 .to_display_point(&snapshot.display_snapshot)
5194 .row();
5195 let mut end_display_row =
5196 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5197 .to_display_point(&snapshot.display_snapshot)
5198 .row();
5199 if end_display_row != start_display_row {
5200 end_display_row.0 -= 1;
5201 }
5202 let color = match &hunk.status() {
5203 DiffHunkStatus::Added => theme.status().created,
5204 DiffHunkStatus::Modified => theme.status().modified,
5205 DiffHunkStatus::Removed => theme.status().deleted,
5206 };
5207 ColoredRange {
5208 start: start_display_row,
5209 end: end_display_row,
5210 color,
5211 }
5212 });
5213
5214 marker_quads.extend(
5215 scrollbar_layout
5216 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5217 );
5218 }
5219
5220 for (background_highlight_id, (_, background_ranges)) in
5221 background_highlights.iter()
5222 {
5223 let is_search_highlights = *background_highlight_id
5224 == TypeId::of::<BufferSearchHighlights>();
5225 let is_symbol_occurrences = *background_highlight_id
5226 == TypeId::of::<DocumentHighlightRead>()
5227 || *background_highlight_id
5228 == TypeId::of::<DocumentHighlightWrite>();
5229 if (is_search_highlights && scrollbar_settings.search_results)
5230 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5231 {
5232 let mut color = theme.status().info;
5233 if is_symbol_occurrences {
5234 color.fade_out(0.5);
5235 }
5236 let marker_row_ranges = background_ranges.iter().map(|range| {
5237 let display_start = range
5238 .start
5239 .to_display_point(&snapshot.display_snapshot);
5240 let display_end =
5241 range.end.to_display_point(&snapshot.display_snapshot);
5242 ColoredRange {
5243 start: display_start.row(),
5244 end: display_end.row(),
5245 color,
5246 }
5247 });
5248 marker_quads.extend(
5249 scrollbar_layout
5250 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5251 );
5252 }
5253 }
5254
5255 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5256 let diagnostics = snapshot
5257 .buffer_snapshot
5258 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5259 // Don't show diagnostics the user doesn't care about
5260 .filter(|diagnostic| {
5261 match (
5262 scrollbar_settings.diagnostics,
5263 diagnostic.diagnostic.severity,
5264 ) {
5265 (ScrollbarDiagnostics::All, _) => true,
5266 (
5267 ScrollbarDiagnostics::Error,
5268 DiagnosticSeverity::ERROR,
5269 ) => true,
5270 (
5271 ScrollbarDiagnostics::Warning,
5272 DiagnosticSeverity::ERROR
5273 | DiagnosticSeverity::WARNING,
5274 ) => true,
5275 (
5276 ScrollbarDiagnostics::Information,
5277 DiagnosticSeverity::ERROR
5278 | DiagnosticSeverity::WARNING
5279 | DiagnosticSeverity::INFORMATION,
5280 ) => true,
5281 (_, _) => false,
5282 }
5283 })
5284 // We want to sort by severity, in order to paint the most severe diagnostics last.
5285 .sorted_by_key(|diagnostic| {
5286 std::cmp::Reverse(diagnostic.diagnostic.severity)
5287 });
5288
5289 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5290 let start_display = diagnostic
5291 .range
5292 .start
5293 .to_display_point(&snapshot.display_snapshot);
5294 let end_display = diagnostic
5295 .range
5296 .end
5297 .to_display_point(&snapshot.display_snapshot);
5298 let color = match diagnostic.diagnostic.severity {
5299 DiagnosticSeverity::ERROR => theme.status().error,
5300 DiagnosticSeverity::WARNING => theme.status().warning,
5301 DiagnosticSeverity::INFORMATION => theme.status().info,
5302 _ => theme.status().hint,
5303 };
5304 ColoredRange {
5305 start: start_display.row(),
5306 end: end_display.row(),
5307 color,
5308 }
5309 });
5310 marker_quads.extend(
5311 scrollbar_layout
5312 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5313 );
5314 }
5315
5316 Arc::from(marker_quads)
5317 })
5318 .await;
5319
5320 editor.update(&mut cx, |editor, cx| {
5321 editor.scrollbar_marker_state.markers = scrollbar_markers;
5322 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5323 editor.scrollbar_marker_state.pending_refresh = None;
5324 cx.notify();
5325 })?;
5326
5327 Ok(())
5328 }));
5329 });
5330 }
5331
5332 #[allow(clippy::too_many_arguments)]
5333 fn paint_highlighted_range(
5334 &self,
5335 range: Range<DisplayPoint>,
5336 color: Hsla,
5337 corner_radius: Pixels,
5338 line_end_overshoot: Pixels,
5339 layout: &EditorLayout,
5340 window: &mut Window,
5341 ) {
5342 let start_row = layout.visible_display_row_range.start;
5343 let end_row = layout.visible_display_row_range.end;
5344 if range.start != range.end {
5345 let row_range = if range.end.column() == 0 {
5346 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5347 } else {
5348 cmp::max(range.start.row(), start_row)
5349 ..cmp::min(range.end.row().next_row(), end_row)
5350 };
5351
5352 let highlighted_range = HighlightedRange {
5353 color,
5354 line_height: layout.position_map.line_height,
5355 corner_radius,
5356 start_y: layout.content_origin.y
5357 + row_range.start.as_f32() * layout.position_map.line_height
5358 - layout.position_map.scroll_pixel_position.y,
5359 lines: row_range
5360 .iter_rows()
5361 .map(|row| {
5362 let line_layout =
5363 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5364 HighlightedRangeLine {
5365 start_x: if row == range.start.row() {
5366 layout.content_origin.x
5367 + line_layout.x_for_index(range.start.column() as usize)
5368 - layout.position_map.scroll_pixel_position.x
5369 } else {
5370 layout.content_origin.x
5371 - layout.position_map.scroll_pixel_position.x
5372 },
5373 end_x: if row == range.end.row() {
5374 layout.content_origin.x
5375 + line_layout.x_for_index(range.end.column() as usize)
5376 - layout.position_map.scroll_pixel_position.x
5377 } else {
5378 layout.content_origin.x + line_layout.width + line_end_overshoot
5379 - layout.position_map.scroll_pixel_position.x
5380 },
5381 }
5382 })
5383 .collect(),
5384 };
5385
5386 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5387 }
5388 }
5389
5390 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5391 if let Some(mut inline_blame) = layout.inline_blame.take() {
5392 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5393 inline_blame.paint(window, cx);
5394 })
5395 }
5396 }
5397
5398 fn paint_diff_hunk_controls(
5399 &mut self,
5400 layout: &mut EditorLayout,
5401 window: &mut Window,
5402 cx: &mut App,
5403 ) {
5404 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5405 diff_hunk_control.paint(window, cx);
5406 }
5407 }
5408
5409 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5410 for mut block in layout.blocks.drain(..) {
5411 block.element.paint(window, cx);
5412 }
5413 }
5414
5415 fn paint_inline_completion_popover(
5416 &mut self,
5417 layout: &mut EditorLayout,
5418 window: &mut Window,
5419 cx: &mut App,
5420 ) {
5421 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5422 inline_completion_popover.paint(window, cx);
5423 }
5424 }
5425
5426 fn paint_mouse_context_menu(
5427 &mut self,
5428 layout: &mut EditorLayout,
5429 window: &mut Window,
5430 cx: &mut App,
5431 ) {
5432 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5433 mouse_context_menu.paint(window, cx);
5434 }
5435 }
5436
5437 fn paint_scroll_wheel_listener(
5438 &mut self,
5439 layout: &EditorLayout,
5440 window: &mut Window,
5441 cx: &mut App,
5442 ) {
5443 window.on_mouse_event({
5444 let position_map = layout.position_map.clone();
5445 let editor = self.editor.clone();
5446 let hitbox = layout.hitbox.clone();
5447 let mut delta = ScrollDelta::default();
5448
5449 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5450 // accidentally turn off their scrolling.
5451 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5452
5453 move |event: &ScrollWheelEvent, phase, window, cx| {
5454 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5455 delta = delta.coalesce(event.delta);
5456 editor.update(cx, |editor, cx| {
5457 let position_map: &PositionMap = &position_map;
5458
5459 let line_height = position_map.line_height;
5460 let max_glyph_width = position_map.em_width;
5461 let (delta, axis) = match delta {
5462 gpui::ScrollDelta::Pixels(mut pixels) => {
5463 //Trackpad
5464 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5465 (pixels, axis)
5466 }
5467
5468 gpui::ScrollDelta::Lines(lines) => {
5469 //Not trackpad
5470 let pixels =
5471 point(lines.x * max_glyph_width, lines.y * line_height);
5472 (pixels, None)
5473 }
5474 };
5475
5476 let current_scroll_position = position_map.snapshot.scroll_position();
5477 let x = (current_scroll_position.x * max_glyph_width
5478 - (delta.x * scroll_sensitivity))
5479 / max_glyph_width;
5480 let y = (current_scroll_position.y * line_height
5481 - (delta.y * scroll_sensitivity))
5482 / line_height;
5483 let mut scroll_position =
5484 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5485 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5486 if forbid_vertical_scroll {
5487 scroll_position.y = current_scroll_position.y;
5488 }
5489
5490 if scroll_position != current_scroll_position {
5491 editor.scroll(scroll_position, axis, window, cx);
5492 cx.stop_propagation();
5493 } else if y < 0. {
5494 // Due to clamping, we may fail to detect cases of overscroll to the top;
5495 // We want the scroll manager to get an update in such cases and detect the change of direction
5496 // on the next frame.
5497 cx.notify();
5498 }
5499 });
5500 }
5501 }
5502 });
5503 }
5504
5505 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5506 self.paint_scroll_wheel_listener(layout, window, cx);
5507
5508 window.on_mouse_event({
5509 let position_map = layout.position_map.clone();
5510 let editor = self.editor.clone();
5511 let multi_buffer_range =
5512 layout
5513 .display_hunks
5514 .iter()
5515 .find_map(|(hunk, hunk_hitbox)| match hunk {
5516 DisplayDiffHunk::Folded { .. } => None,
5517 DisplayDiffHunk::Unfolded {
5518 multi_buffer_range, ..
5519 } => {
5520 if hunk_hitbox
5521 .as_ref()
5522 .map(|hitbox| hitbox.is_hovered(window))
5523 .unwrap_or(false)
5524 {
5525 Some(multi_buffer_range.clone())
5526 } else {
5527 None
5528 }
5529 }
5530 });
5531 let line_numbers = layout.line_numbers.clone();
5532
5533 move |event: &MouseDownEvent, phase, window, cx| {
5534 if phase == DispatchPhase::Bubble {
5535 match event.button {
5536 MouseButton::Left => editor.update(cx, |editor, cx| {
5537 let pending_mouse_down = editor
5538 .pending_mouse_down
5539 .get_or_insert_with(Default::default)
5540 .clone();
5541
5542 *pending_mouse_down.borrow_mut() = Some(event.clone());
5543
5544 Self::mouse_left_down(
5545 editor,
5546 event,
5547 multi_buffer_range.clone(),
5548 &position_map,
5549 line_numbers.as_ref(),
5550 window,
5551 cx,
5552 );
5553 }),
5554 MouseButton::Right => editor.update(cx, |editor, cx| {
5555 Self::mouse_right_down(editor, event, &position_map, window, cx);
5556 }),
5557 MouseButton::Middle => editor.update(cx, |editor, cx| {
5558 Self::mouse_middle_down(editor, event, &position_map, window, cx);
5559 }),
5560 _ => {}
5561 };
5562 }
5563 }
5564 });
5565
5566 window.on_mouse_event({
5567 let editor = self.editor.clone();
5568 let position_map = layout.position_map.clone();
5569
5570 move |event: &MouseUpEvent, phase, window, cx| {
5571 if phase == DispatchPhase::Bubble {
5572 editor.update(cx, |editor, cx| {
5573 Self::mouse_up(editor, event, &position_map, window, cx)
5574 });
5575 }
5576 }
5577 });
5578
5579 window.on_mouse_event({
5580 let editor = self.editor.clone();
5581 let position_map = layout.position_map.clone();
5582 let mut captured_mouse_down = None;
5583
5584 move |event: &MouseUpEvent, phase, window, cx| match phase {
5585 // Clear the pending mouse down during the capture phase,
5586 // so that it happens even if another event handler stops
5587 // propagation.
5588 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5589 let pending_mouse_down = editor
5590 .pending_mouse_down
5591 .get_or_insert_with(Default::default)
5592 .clone();
5593
5594 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5595 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5596 captured_mouse_down = pending_mouse_down.take();
5597 window.refresh();
5598 }
5599 }),
5600 // Fire click handlers during the bubble phase.
5601 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5602 if let Some(mouse_down) = captured_mouse_down.take() {
5603 let event = ClickEvent {
5604 down: mouse_down,
5605 up: event.clone(),
5606 };
5607 Self::click(editor, &event, &position_map, window, cx);
5608 }
5609 }),
5610 }
5611 });
5612
5613 window.on_mouse_event({
5614 let position_map = layout.position_map.clone();
5615 let editor = self.editor.clone();
5616
5617 move |event: &MouseMoveEvent, phase, window, cx| {
5618 if phase == DispatchPhase::Bubble {
5619 editor.update(cx, |editor, cx| {
5620 if editor.hover_state.focused(window, cx) {
5621 return;
5622 }
5623 if event.pressed_button == Some(MouseButton::Left)
5624 || event.pressed_button == Some(MouseButton::Middle)
5625 {
5626 Self::mouse_dragged(editor, event, &position_map, window, cx)
5627 }
5628
5629 Self::mouse_moved(editor, event, &position_map, window, cx)
5630 });
5631 }
5632 }
5633 });
5634 }
5635
5636 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5637 bounds.top_right().x - self.style.scrollbar_width
5638 }
5639
5640 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5641 let style = &self.style;
5642 let font_size = style.text.font_size.to_pixels(window.rem_size());
5643 let layout = window
5644 .text_system()
5645 .shape_line(
5646 SharedString::from(" ".repeat(column)),
5647 font_size,
5648 &[TextRun {
5649 len: column,
5650 font: style.text.font(),
5651 color: Hsla::default(),
5652 background_color: None,
5653 underline: None,
5654 strikethrough: None,
5655 }],
5656 )
5657 .unwrap();
5658
5659 layout.width
5660 }
5661
5662 fn max_line_number_width(
5663 &self,
5664 snapshot: &EditorSnapshot,
5665 window: &mut Window,
5666 cx: &mut App,
5667 ) -> Pixels {
5668 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5669 self.column_pixels(digit_count, window, cx)
5670 }
5671
5672 fn shape_line_number(
5673 &self,
5674 text: SharedString,
5675 color: Hsla,
5676 window: &mut Window,
5677 ) -> anyhow::Result<ShapedLine> {
5678 let run = TextRun {
5679 len: text.len(),
5680 font: self.style.text.font(),
5681 color,
5682 background_color: None,
5683 underline: None,
5684 strikethrough: None,
5685 };
5686 window.text_system().shape_line(
5687 text,
5688 self.style.text.font_size.to_pixels(window.rem_size()),
5689 &[run],
5690 )
5691 }
5692}
5693
5694fn header_jump_data(
5695 snapshot: &EditorSnapshot,
5696 block_row_start: DisplayRow,
5697 height: u32,
5698 for_excerpt: &ExcerptInfo,
5699) -> JumpData {
5700 let range = &for_excerpt.range;
5701 let buffer = &for_excerpt.buffer;
5702 let jump_anchor = range
5703 .primary
5704 .as_ref()
5705 .map_or(range.context.start, |primary| primary.start);
5706
5707 let excerpt_start = range.context.start;
5708 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5709 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5710 0
5711 } else {
5712 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5713 jump_position.row.saturating_sub(excerpt_start_point.row)
5714 };
5715
5716 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5717 .saturating_sub(
5718 snapshot
5719 .scroll_anchor
5720 .scroll_position(&snapshot.display_snapshot)
5721 .y as u32,
5722 );
5723
5724 JumpData::MultiBufferPoint {
5725 excerpt_id: for_excerpt.id,
5726 anchor: jump_anchor,
5727 position: jump_position,
5728 line_offset_from_top,
5729 }
5730}
5731
5732fn inline_completion_accept_indicator(
5733 label: impl Into<SharedString>,
5734 icon: Option<IconName>,
5735 previewing: bool,
5736 focus_handle: FocusHandle,
5737 window: &Window,
5738 cx: &App,
5739) -> AnyElement {
5740 let use_hardcoded_linux_preview_binding;
5741
5742 #[cfg(target_os = "macos")]
5743 {
5744 use_hardcoded_linux_preview_binding = false;
5745 }
5746
5747 #[cfg(not(target_os = "macos"))]
5748 {
5749 use_hardcoded_linux_preview_binding = previewing;
5750 }
5751
5752 let accept_keystroke = if use_hardcoded_linux_preview_binding {
5753 Keystroke {
5754 modifiers: Default::default(),
5755 key: "enter".to_string(),
5756 key_char: None,
5757 }
5758 } else {
5759 let bindings = window.bindings_for_action_in(&crate::AcceptInlineCompletion, &focus_handle);
5760 if let Some(keystroke) = bindings
5761 .last()
5762 .and_then(|binding| binding.keystrokes().first())
5763 {
5764 // TODO: clone unnecessary once `use_hardcoded_linux_preview_binding` is removed.
5765 keystroke.clone()
5766 } else {
5767 return div().into_any();
5768 }
5769 };
5770
5771 let accept_key = h_flex()
5772 .px_0p5()
5773 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5774 .text_size(TextSize::XSmall.rems(cx))
5775 .text_color(cx.theme().colors().text)
5776 .gap_1()
5777 .when(!previewing, |parent| {
5778 parent.children(ui::render_modifiers(
5779 &accept_keystroke.modifiers,
5780 PlatformStyle::platform(),
5781 Some(Color::Default),
5782 false,
5783 ))
5784 })
5785 .child(accept_keystroke.key.clone());
5786
5787 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5788
5789 h_flex()
5790 .py_0p5()
5791 .pl_1()
5792 .pr(padding_right)
5793 .gap_1()
5794 .bg(cx.theme().colors().text_accent.opacity(0.15))
5795 .border_1()
5796 .border_color(cx.theme().colors().text_accent.opacity(0.8))
5797 .rounded_md()
5798 .shadow_sm()
5799 .child(accept_key)
5800 .child(Label::new(label).size(LabelSize::Small))
5801 .when_some(icon, |element, icon| {
5802 element.child(
5803 div()
5804 .mt(px(1.5))
5805 .child(Icon::new(icon).size(IconSize::Small)),
5806 )
5807 })
5808 .into_any()
5809}
5810
5811#[allow(clippy::too_many_arguments)]
5812fn prepaint_gutter_button(
5813 button: IconButton,
5814 row: DisplayRow,
5815 line_height: Pixels,
5816 gutter_dimensions: &GutterDimensions,
5817 scroll_pixel_position: gpui::Point<Pixels>,
5818 gutter_hitbox: &Hitbox,
5819 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5820 window: &mut Window,
5821 cx: &mut App,
5822) -> AnyElement {
5823 let mut button = button.into_any_element();
5824 let available_space = size(
5825 AvailableSpace::MinContent,
5826 AvailableSpace::Definite(line_height),
5827 );
5828 let indicator_size = button.layout_as_root(available_space, window, cx);
5829
5830 let blame_width = gutter_dimensions.git_blame_entries_width;
5831 let gutter_width = rows_with_hunk_bounds
5832 .get(&row)
5833 .map(|bounds| bounds.size.width);
5834 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5835
5836 let mut x = left_offset;
5837 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5838 - indicator_size.width
5839 - left_offset;
5840 x += available_width / 2.;
5841
5842 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5843 y += (line_height - indicator_size.height) / 2.;
5844
5845 button.prepaint_as_root(
5846 gutter_hitbox.origin + point(x, y),
5847 available_space,
5848 window,
5849 cx,
5850 );
5851 button
5852}
5853
5854fn render_inline_blame_entry(
5855 blame: &gpui::Entity<GitBlame>,
5856 blame_entry: BlameEntry,
5857 style: &EditorStyle,
5858 workspace: Option<WeakEntity<Workspace>>,
5859 cx: &mut App,
5860) -> AnyElement {
5861 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5862
5863 let author = blame_entry.author.as_deref().unwrap_or_default();
5864 let summary_enabled = ProjectSettings::get_global(cx)
5865 .git
5866 .show_inline_commit_summary();
5867
5868 let text = match blame_entry.summary.as_ref() {
5869 Some(summary) if summary_enabled => {
5870 format!("{}, {} - {}", author, relative_timestamp, summary)
5871 }
5872 _ => format!("{}, {}", author, relative_timestamp),
5873 };
5874
5875 let details = blame.read(cx).details_for_entry(&blame_entry);
5876
5877 let tooltip = cx.new(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
5878
5879 h_flex()
5880 .id("inline-blame")
5881 .w_full()
5882 .font_family(style.text.font().family)
5883 .text_color(cx.theme().status().hint)
5884 .line_height(style.text.line_height)
5885 .child(Icon::new(IconName::FileGit).color(Color::Hint))
5886 .child(text)
5887 .gap_2()
5888 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5889 .into_any()
5890}
5891
5892fn render_blame_entry(
5893 ix: usize,
5894 blame: &gpui::Entity<GitBlame>,
5895 blame_entry: BlameEntry,
5896 style: &EditorStyle,
5897 last_used_color: &mut Option<(PlayerColor, Oid)>,
5898 editor: Entity<Editor>,
5899 cx: &mut App,
5900) -> AnyElement {
5901 let mut sha_color = cx
5902 .theme()
5903 .players()
5904 .color_for_participant(blame_entry.sha.into());
5905 // If the last color we used is the same as the one we get for this line, but
5906 // the commit SHAs are different, then we try again to get a different color.
5907 match *last_used_color {
5908 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5909 let index: u32 = blame_entry.sha.into();
5910 sha_color = cx.theme().players().color_for_participant(index + 1);
5911 }
5912 _ => {}
5913 };
5914 last_used_color.replace((sha_color, blame_entry.sha));
5915
5916 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5917
5918 let short_commit_id = blame_entry.sha.display_short();
5919
5920 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5921 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5922
5923 let details = blame.read(cx).details_for_entry(&blame_entry);
5924
5925 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
5926
5927 let tooltip =
5928 cx.new(|_| BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace));
5929
5930 h_flex()
5931 .w_full()
5932 .justify_between()
5933 .font_family(style.text.font().family)
5934 .line_height(style.text.line_height)
5935 .id(("blame", ix))
5936 .text_color(cx.theme().status().hint)
5937 .pr_2()
5938 .gap_2()
5939 .child(
5940 h_flex()
5941 .items_center()
5942 .gap_2()
5943 .child(div().text_color(sha_color.cursor).child(short_commit_id))
5944 .child(name),
5945 )
5946 .child(relative_timestamp)
5947 .on_mouse_down(MouseButton::Right, {
5948 let blame_entry = blame_entry.clone();
5949 let details = details.clone();
5950 move |event, window, cx| {
5951 deploy_blame_entry_context_menu(
5952 &blame_entry,
5953 details.as_ref(),
5954 editor.clone(),
5955 event.position,
5956 window,
5957 cx,
5958 );
5959 }
5960 })
5961 .hover(|style| style.bg(cx.theme().colors().element_hover))
5962 .when_some(
5963 details.and_then(|details| details.permalink),
5964 |this, url| {
5965 let url = url.clone();
5966 this.cursor_pointer().on_click(move |_, _, cx| {
5967 cx.stop_propagation();
5968 cx.open_url(url.as_str())
5969 })
5970 },
5971 )
5972 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5973 .into_any()
5974}
5975
5976fn deploy_blame_entry_context_menu(
5977 blame_entry: &BlameEntry,
5978 details: Option<&CommitDetails>,
5979 editor: Entity<Editor>,
5980 position: gpui::Point<Pixels>,
5981 window: &mut Window,
5982 cx: &mut App,
5983) {
5984 let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
5985 let sha = format!("{}", blame_entry.sha);
5986 menu.on_blur_subscription(Subscription::new(|| {}))
5987 .entry("Copy commit SHA", None, move |_, cx| {
5988 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
5989 })
5990 .when_some(
5991 details.and_then(|details| details.permalink.clone()),
5992 |this, url| {
5993 this.entry("Open permalink", None, move |_, cx| {
5994 cx.open_url(url.as_str())
5995 })
5996 },
5997 )
5998 });
5999
6000 editor.update(cx, move |editor, cx| {
6001 editor.mouse_context_menu = Some(MouseContextMenu::new(
6002 MenuPosition::PinnedToScreen(position),
6003 context_menu,
6004 window,
6005 cx,
6006 ));
6007 cx.notify();
6008 });
6009}
6010
6011#[derive(Debug)]
6012pub(crate) struct LineWithInvisibles {
6013 fragments: SmallVec<[LineFragment; 1]>,
6014 invisibles: Vec<Invisible>,
6015 len: usize,
6016 width: Pixels,
6017 font_size: Pixels,
6018}
6019
6020#[allow(clippy::large_enum_variant)]
6021enum LineFragment {
6022 Text(ShapedLine),
6023 Element {
6024 element: Option<AnyElement>,
6025 size: Size<Pixels>,
6026 len: usize,
6027 },
6028}
6029
6030impl fmt::Debug for LineFragment {
6031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6032 match self {
6033 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6034 LineFragment::Element { size, len, .. } => f
6035 .debug_struct("Element")
6036 .field("size", size)
6037 .field("len", len)
6038 .finish(),
6039 }
6040 }
6041}
6042
6043impl LineWithInvisibles {
6044 #[allow(clippy::too_many_arguments)]
6045 fn from_chunks<'a>(
6046 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6047 editor_style: &EditorStyle,
6048 max_line_len: usize,
6049 max_line_count: usize,
6050 editor_mode: EditorMode,
6051 text_width: Pixels,
6052 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6053 window: &mut Window,
6054 cx: &mut App,
6055 ) -> Vec<Self> {
6056 let text_style = &editor_style.text;
6057 let mut layouts = Vec::with_capacity(max_line_count);
6058 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6059 let mut line = String::new();
6060 let mut invisibles = Vec::new();
6061 let mut width = Pixels::ZERO;
6062 let mut len = 0;
6063 let mut styles = Vec::new();
6064 let mut non_whitespace_added = false;
6065 let mut row = 0;
6066 let mut line_exceeded_max_len = false;
6067 let font_size = text_style.font_size.to_pixels(window.rem_size());
6068
6069 let ellipsis = SharedString::from("⋯");
6070
6071 for highlighted_chunk in chunks.chain([HighlightedChunk {
6072 text: "\n",
6073 style: None,
6074 is_tab: false,
6075 replacement: None,
6076 }]) {
6077 if let Some(replacement) = highlighted_chunk.replacement {
6078 if !line.is_empty() {
6079 let shaped_line = window
6080 .text_system()
6081 .shape_line(line.clone().into(), font_size, &styles)
6082 .unwrap();
6083 width += shaped_line.width;
6084 len += shaped_line.len;
6085 fragments.push(LineFragment::Text(shaped_line));
6086 line.clear();
6087 styles.clear();
6088 }
6089
6090 match replacement {
6091 ChunkReplacement::Renderer(renderer) => {
6092 let available_width = if renderer.constrain_width {
6093 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6094 ellipsis.clone()
6095 } else {
6096 SharedString::from(Arc::from(highlighted_chunk.text))
6097 };
6098 let shaped_line = window
6099 .text_system()
6100 .shape_line(
6101 chunk,
6102 font_size,
6103 &[text_style.to_run(highlighted_chunk.text.len())],
6104 )
6105 .unwrap();
6106 AvailableSpace::Definite(shaped_line.width)
6107 } else {
6108 AvailableSpace::MinContent
6109 };
6110
6111 let mut element = (renderer.render)(&mut ChunkRendererContext {
6112 context: cx,
6113 window,
6114 max_width: text_width,
6115 });
6116 let line_height = text_style.line_height_in_pixels(window.rem_size());
6117 let size = element.layout_as_root(
6118 size(available_width, AvailableSpace::Definite(line_height)),
6119 window,
6120 cx,
6121 );
6122
6123 width += size.width;
6124 len += highlighted_chunk.text.len();
6125 fragments.push(LineFragment::Element {
6126 element: Some(element),
6127 size,
6128 len: highlighted_chunk.text.len(),
6129 });
6130 }
6131 ChunkReplacement::Str(x) => {
6132 let text_style = if let Some(style) = highlighted_chunk.style {
6133 Cow::Owned(text_style.clone().highlight(style))
6134 } else {
6135 Cow::Borrowed(text_style)
6136 };
6137
6138 let run = TextRun {
6139 len: x.len(),
6140 font: text_style.font(),
6141 color: text_style.color,
6142 background_color: text_style.background_color,
6143 underline: text_style.underline,
6144 strikethrough: text_style.strikethrough,
6145 };
6146 let line_layout = window
6147 .text_system()
6148 .shape_line(x, font_size, &[run])
6149 .unwrap()
6150 .with_len(highlighted_chunk.text.len());
6151
6152 width += line_layout.width;
6153 len += highlighted_chunk.text.len();
6154 fragments.push(LineFragment::Text(line_layout))
6155 }
6156 }
6157 } else {
6158 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6159 if ix > 0 {
6160 let shaped_line = window
6161 .text_system()
6162 .shape_line(line.clone().into(), font_size, &styles)
6163 .unwrap();
6164 width += shaped_line.width;
6165 len += shaped_line.len;
6166 fragments.push(LineFragment::Text(shaped_line));
6167 layouts.push(Self {
6168 width: mem::take(&mut width),
6169 len: mem::take(&mut len),
6170 fragments: mem::take(&mut fragments),
6171 invisibles: std::mem::take(&mut invisibles),
6172 font_size,
6173 });
6174
6175 line.clear();
6176 styles.clear();
6177 row += 1;
6178 line_exceeded_max_len = false;
6179 non_whitespace_added = false;
6180 if row == max_line_count {
6181 return layouts;
6182 }
6183 }
6184
6185 if !line_chunk.is_empty() && !line_exceeded_max_len {
6186 let text_style = if let Some(style) = highlighted_chunk.style {
6187 Cow::Owned(text_style.clone().highlight(style))
6188 } else {
6189 Cow::Borrowed(text_style)
6190 };
6191
6192 if line.len() + line_chunk.len() > max_line_len {
6193 let mut chunk_len = max_line_len - line.len();
6194 while !line_chunk.is_char_boundary(chunk_len) {
6195 chunk_len -= 1;
6196 }
6197 line_chunk = &line_chunk[..chunk_len];
6198 line_exceeded_max_len = true;
6199 }
6200
6201 styles.push(TextRun {
6202 len: line_chunk.len(),
6203 font: text_style.font(),
6204 color: text_style.color,
6205 background_color: text_style.background_color,
6206 underline: text_style.underline,
6207 strikethrough: text_style.strikethrough,
6208 });
6209
6210 if editor_mode == EditorMode::Full {
6211 // Line wrap pads its contents with fake whitespaces,
6212 // avoid printing them
6213 let is_soft_wrapped = is_row_soft_wrapped(row);
6214 if highlighted_chunk.is_tab {
6215 if non_whitespace_added || !is_soft_wrapped {
6216 invisibles.push(Invisible::Tab {
6217 line_start_offset: line.len(),
6218 line_end_offset: line.len() + line_chunk.len(),
6219 });
6220 }
6221 } else {
6222 invisibles.extend(line_chunk.char_indices().filter_map(
6223 |(index, c)| {
6224 let is_whitespace = c.is_whitespace();
6225 non_whitespace_added |= !is_whitespace;
6226 if is_whitespace
6227 && (non_whitespace_added || !is_soft_wrapped)
6228 {
6229 Some(Invisible::Whitespace {
6230 line_offset: line.len() + index,
6231 })
6232 } else {
6233 None
6234 }
6235 },
6236 ))
6237 }
6238 }
6239
6240 line.push_str(line_chunk);
6241 }
6242 }
6243 }
6244 }
6245
6246 layouts
6247 }
6248
6249 #[allow(clippy::too_many_arguments)]
6250 fn prepaint(
6251 &mut self,
6252 line_height: Pixels,
6253 scroll_pixel_position: gpui::Point<Pixels>,
6254 row: DisplayRow,
6255 content_origin: gpui::Point<Pixels>,
6256 line_elements: &mut SmallVec<[AnyElement; 1]>,
6257 window: &mut Window,
6258 cx: &mut App,
6259 ) {
6260 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6261 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6262 for fragment in &mut self.fragments {
6263 match fragment {
6264 LineFragment::Text(line) => {
6265 fragment_origin.x += line.width;
6266 }
6267 LineFragment::Element { element, size, .. } => {
6268 let mut element = element
6269 .take()
6270 .expect("you can't prepaint LineWithInvisibles twice");
6271
6272 // Center the element vertically within the line.
6273 let mut element_origin = fragment_origin;
6274 element_origin.y += (line_height - size.height) / 2.;
6275 element.prepaint_at(element_origin, window, cx);
6276 line_elements.push(element);
6277
6278 fragment_origin.x += size.width;
6279 }
6280 }
6281 }
6282 }
6283
6284 #[allow(clippy::too_many_arguments)]
6285 fn draw(
6286 &self,
6287 layout: &EditorLayout,
6288 row: DisplayRow,
6289 content_origin: gpui::Point<Pixels>,
6290 whitespace_setting: ShowWhitespaceSetting,
6291 selection_ranges: &[Range<DisplayPoint>],
6292 window: &mut Window,
6293 cx: &mut App,
6294 ) {
6295 let line_height = layout.position_map.line_height;
6296 let line_y = line_height
6297 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6298
6299 let mut fragment_origin =
6300 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6301
6302 for fragment in &self.fragments {
6303 match fragment {
6304 LineFragment::Text(line) => {
6305 line.paint(fragment_origin, line_height, window, cx)
6306 .log_err();
6307 fragment_origin.x += line.width;
6308 }
6309 LineFragment::Element { size, .. } => {
6310 fragment_origin.x += size.width;
6311 }
6312 }
6313 }
6314
6315 self.draw_invisibles(
6316 selection_ranges,
6317 layout,
6318 content_origin,
6319 line_y,
6320 row,
6321 line_height,
6322 whitespace_setting,
6323 window,
6324 cx,
6325 );
6326 }
6327
6328 #[allow(clippy::too_many_arguments)]
6329 fn draw_invisibles(
6330 &self,
6331 selection_ranges: &[Range<DisplayPoint>],
6332 layout: &EditorLayout,
6333 content_origin: gpui::Point<Pixels>,
6334 line_y: Pixels,
6335 row: DisplayRow,
6336 line_height: Pixels,
6337 whitespace_setting: ShowWhitespaceSetting,
6338 window: &mut Window,
6339 cx: &mut App,
6340 ) {
6341 let extract_whitespace_info = |invisible: &Invisible| {
6342 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6343 Invisible::Tab {
6344 line_start_offset,
6345 line_end_offset,
6346 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6347 Invisible::Whitespace { line_offset } => {
6348 (*line_offset, line_offset + 1, &layout.space_invisible)
6349 }
6350 };
6351
6352 let x_offset = self.x_for_index(token_offset);
6353 let invisible_offset =
6354 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6355 let origin = content_origin
6356 + gpui::point(
6357 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6358 line_y,
6359 );
6360
6361 (
6362 [token_offset, token_end_offset],
6363 Box::new(move |window: &mut Window, cx: &mut App| {
6364 invisible_symbol
6365 .paint(origin, line_height, window, cx)
6366 .log_err();
6367 }),
6368 )
6369 };
6370
6371 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6372 match whitespace_setting {
6373 ShowWhitespaceSetting::None => (),
6374 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6375 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6376 let invisible_point = DisplayPoint::new(row, start as u32);
6377 if !selection_ranges
6378 .iter()
6379 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6380 {
6381 return;
6382 }
6383
6384 paint(window, cx);
6385 }),
6386
6387 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6388 // - It is a tab
6389 // - It is adjacent to an edge (start or end)
6390 // - It is adjacent to a whitespace (left or right)
6391 ShowWhitespaceSetting::Boundary => {
6392 // 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
6393 // the above cases.
6394 // Note: We zip in the original `invisibles` to check for tab equality
6395 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6396 for (([start, end], paint), invisible) in
6397 invisible_iter.zip_eq(self.invisibles.iter())
6398 {
6399 let should_render = match (&last_seen, invisible) {
6400 (_, Invisible::Tab { .. }) => true,
6401 (Some((_, last_end, _)), _) => *last_end == start,
6402 _ => false,
6403 };
6404
6405 if should_render || start == 0 || end == self.len {
6406 paint(window, cx);
6407
6408 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6409 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6410 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6411 // Note that we need to make sure that the last one is actually adjacent
6412 if !should_render_last && last_end == start {
6413 paint_last(window, cx);
6414 }
6415 }
6416 }
6417
6418 // Manually render anything within a selection
6419 let invisible_point = DisplayPoint::new(row, start as u32);
6420 if selection_ranges.iter().any(|region| {
6421 region.start <= invisible_point && invisible_point < region.end
6422 }) {
6423 paint(window, cx);
6424 }
6425
6426 last_seen = Some((should_render, end, paint));
6427 }
6428 }
6429 }
6430 }
6431
6432 pub fn x_for_index(&self, index: usize) -> Pixels {
6433 let mut fragment_start_x = Pixels::ZERO;
6434 let mut fragment_start_index = 0;
6435
6436 for fragment in &self.fragments {
6437 match fragment {
6438 LineFragment::Text(shaped_line) => {
6439 let fragment_end_index = fragment_start_index + shaped_line.len;
6440 if index < fragment_end_index {
6441 return fragment_start_x
6442 + shaped_line.x_for_index(index - fragment_start_index);
6443 }
6444 fragment_start_x += shaped_line.width;
6445 fragment_start_index = fragment_end_index;
6446 }
6447 LineFragment::Element { len, size, .. } => {
6448 let fragment_end_index = fragment_start_index + len;
6449 if index < fragment_end_index {
6450 return fragment_start_x;
6451 }
6452 fragment_start_x += size.width;
6453 fragment_start_index = fragment_end_index;
6454 }
6455 }
6456 }
6457
6458 fragment_start_x
6459 }
6460
6461 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6462 let mut fragment_start_x = Pixels::ZERO;
6463 let mut fragment_start_index = 0;
6464
6465 for fragment in &self.fragments {
6466 match fragment {
6467 LineFragment::Text(shaped_line) => {
6468 let fragment_end_x = fragment_start_x + shaped_line.width;
6469 if x < fragment_end_x {
6470 return Some(
6471 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6472 );
6473 }
6474 fragment_start_x = fragment_end_x;
6475 fragment_start_index += shaped_line.len;
6476 }
6477 LineFragment::Element { len, size, .. } => {
6478 let fragment_end_x = fragment_start_x + size.width;
6479 if x < fragment_end_x {
6480 return Some(fragment_start_index);
6481 }
6482 fragment_start_index += len;
6483 fragment_start_x = fragment_end_x;
6484 }
6485 }
6486 }
6487
6488 None
6489 }
6490
6491 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6492 let mut fragment_start_index = 0;
6493
6494 for fragment in &self.fragments {
6495 match fragment {
6496 LineFragment::Text(shaped_line) => {
6497 let fragment_end_index = fragment_start_index + shaped_line.len;
6498 if index < fragment_end_index {
6499 return shaped_line.font_id_for_index(index - fragment_start_index);
6500 }
6501 fragment_start_index = fragment_end_index;
6502 }
6503 LineFragment::Element { len, .. } => {
6504 let fragment_end_index = fragment_start_index + len;
6505 if index < fragment_end_index {
6506 return None;
6507 }
6508 fragment_start_index = fragment_end_index;
6509 }
6510 }
6511 }
6512
6513 None
6514 }
6515}
6516
6517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6518enum Invisible {
6519 /// A tab character
6520 ///
6521 /// A tab character is internally represented by spaces (configured by the user's tab width)
6522 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6523 /// adjacency checks.
6524 Tab {
6525 line_start_offset: usize,
6526 line_end_offset: usize,
6527 },
6528 Whitespace {
6529 line_offset: usize,
6530 },
6531}
6532
6533impl EditorElement {
6534 /// Returns the rem size to use when rendering the [`EditorElement`].
6535 ///
6536 /// This allows UI elements to scale based on the `buffer_font_size`.
6537 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6538 match self.editor.read(cx).mode {
6539 EditorMode::Full => {
6540 let buffer_font_size = self.style.text.font_size;
6541 match buffer_font_size {
6542 AbsoluteLength::Pixels(pixels) => {
6543 let rem_size_scale = {
6544 // Our default UI font size is 14px on a 16px base scale.
6545 // This means the default UI font size is 0.875rems.
6546 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6547
6548 // We then determine the delta between a single rem and the default font
6549 // size scale.
6550 let default_font_size_delta = 1. - default_font_size_scale;
6551
6552 // Finally, we add this delta to 1rem to get the scale factor that
6553 // should be used to scale up the UI.
6554 1. + default_font_size_delta
6555 };
6556
6557 Some(pixels * rem_size_scale)
6558 }
6559 AbsoluteLength::Rems(rems) => {
6560 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6561 }
6562 }
6563 }
6564 // We currently use single-line and auto-height editors in UI contexts,
6565 // so we don't want to scale everything with the buffer font size, as it
6566 // ends up looking off.
6567 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6568 }
6569 }
6570}
6571
6572impl Element for EditorElement {
6573 type RequestLayoutState = ();
6574 type PrepaintState = EditorLayout;
6575
6576 fn id(&self) -> Option<ElementId> {
6577 None
6578 }
6579
6580 fn request_layout(
6581 &mut self,
6582 _: Option<&GlobalElementId>,
6583 window: &mut Window,
6584 cx: &mut App,
6585 ) -> (gpui::LayoutId, ()) {
6586 let rem_size = self.rem_size(cx);
6587 window.with_rem_size(rem_size, |window| {
6588 self.editor.update(cx, |editor, cx| {
6589 editor.set_style(self.style.clone(), window, cx);
6590
6591 let layout_id = match editor.mode {
6592 EditorMode::SingleLine { auto_width } => {
6593 let rem_size = window.rem_size();
6594
6595 let height = self.style.text.line_height_in_pixels(rem_size);
6596 if auto_width {
6597 let editor_handle = cx.entity().clone();
6598 let style = self.style.clone();
6599 window.request_measured_layout(
6600 Style::default(),
6601 move |_, _, window, cx| {
6602 let editor_snapshot = editor_handle
6603 .update(cx, |editor, cx| editor.snapshot(window, cx));
6604 let line = Self::layout_lines(
6605 DisplayRow(0)..DisplayRow(1),
6606 &editor_snapshot,
6607 &style,
6608 px(f32::MAX),
6609 |_| false, // Single lines never soft wrap
6610 window,
6611 cx,
6612 )
6613 .pop()
6614 .unwrap();
6615
6616 let font_id =
6617 window.text_system().resolve_font(&style.text.font());
6618 let font_size =
6619 style.text.font_size.to_pixels(window.rem_size());
6620 let em_width =
6621 window.text_system().em_width(font_id, font_size).unwrap();
6622
6623 size(line.width + em_width, height)
6624 },
6625 )
6626 } else {
6627 let mut style = Style::default();
6628 style.size.height = height.into();
6629 style.size.width = relative(1.).into();
6630 window.request_layout(style, None, cx)
6631 }
6632 }
6633 EditorMode::AutoHeight { max_lines } => {
6634 let editor_handle = cx.entity().clone();
6635 let max_line_number_width =
6636 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6637 window.request_measured_layout(
6638 Style::default(),
6639 move |known_dimensions, available_space, window, cx| {
6640 editor_handle
6641 .update(cx, |editor, cx| {
6642 compute_auto_height_layout(
6643 editor,
6644 max_lines,
6645 max_line_number_width,
6646 known_dimensions,
6647 available_space.width,
6648 window,
6649 cx,
6650 )
6651 })
6652 .unwrap_or_default()
6653 },
6654 )
6655 }
6656 EditorMode::Full => {
6657 let mut style = Style::default();
6658 style.size.width = relative(1.).into();
6659 style.size.height = relative(1.).into();
6660 window.request_layout(style, None, cx)
6661 }
6662 };
6663
6664 (layout_id, ())
6665 })
6666 })
6667 }
6668
6669 fn prepaint(
6670 &mut self,
6671 _: Option<&GlobalElementId>,
6672 bounds: Bounds<Pixels>,
6673 _: &mut Self::RequestLayoutState,
6674 window: &mut Window,
6675 cx: &mut App,
6676 ) -> Self::PrepaintState {
6677 let text_style = TextStyleRefinement {
6678 font_size: Some(self.style.text.font_size),
6679 line_height: Some(self.style.text.line_height),
6680 ..Default::default()
6681 };
6682 let focus_handle = self.editor.focus_handle(cx);
6683 window.set_view_id(self.editor.entity_id());
6684 window.set_focus_handle(&focus_handle, cx);
6685
6686 let rem_size = self.rem_size(cx);
6687 window.with_rem_size(rem_size, |window| {
6688 window.with_text_style(Some(text_style), |window| {
6689 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6690 let mut snapshot = self
6691 .editor
6692 .update(cx, |editor, cx| editor.snapshot(window, cx));
6693 let style = self.style.clone();
6694
6695 let font_id = window.text_system().resolve_font(&style.text.font());
6696 let font_size = style.text.font_size.to_pixels(window.rem_size());
6697 let line_height = style.text.line_height_in_pixels(window.rem_size());
6698 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6699 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6700
6701 let letter_size = size(em_width, line_height);
6702
6703 let gutter_dimensions = snapshot
6704 .gutter_dimensions(
6705 font_id,
6706 font_size,
6707 self.max_line_number_width(&snapshot, window, cx),
6708 cx,
6709 )
6710 .unwrap_or_default();
6711 let text_width = bounds.size.width - gutter_dimensions.width;
6712
6713 let editor_width = text_width - gutter_dimensions.margin - em_width;
6714
6715 snapshot = self.editor.update(cx, |editor, cx| {
6716 editor.last_bounds = Some(bounds);
6717 editor.gutter_dimensions = gutter_dimensions;
6718 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6719
6720 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6721 snapshot
6722 } else {
6723 let wrap_width = match editor.soft_wrap_mode(cx) {
6724 SoftWrap::GitDiff => None,
6725 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6726 SoftWrap::EditorWidth => Some(editor_width),
6727 SoftWrap::Column(column) => Some(column as f32 * em_advance),
6728 SoftWrap::Bounded(column) => {
6729 Some(editor_width.min(column as f32 * em_advance))
6730 }
6731 };
6732
6733 if editor.set_wrap_width(wrap_width, cx) {
6734 editor.snapshot(window, cx)
6735 } else {
6736 snapshot
6737 }
6738 }
6739 });
6740
6741 let wrap_guides = self
6742 .editor
6743 .read(cx)
6744 .wrap_guides(cx)
6745 .iter()
6746 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6747 .collect::<SmallVec<[_; 2]>>();
6748
6749 let hitbox = window.insert_hitbox(bounds, false);
6750 let gutter_hitbox =
6751 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6752 let text_hitbox = window.insert_hitbox(
6753 Bounds {
6754 origin: gutter_hitbox.top_right(),
6755 size: size(text_width, bounds.size.height),
6756 },
6757 false,
6758 );
6759 // Offset the content_bounds from the text_bounds by the gutter margin (which
6760 // is roughly half a character wide) to make hit testing work more like how we want.
6761 let content_origin =
6762 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6763
6764 let scrollbar_bounds =
6765 Bounds::from_corners(content_origin, bounds.bottom_right());
6766
6767 let height_in_lines = scrollbar_bounds.size.height / line_height;
6768
6769 // NOTE: The max row number in the current file, minus one
6770 let max_row = snapshot.max_point().row().as_f32();
6771
6772 // NOTE: The max scroll position for the top of the window
6773 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6774 (max_row - height_in_lines + 1.).max(0.)
6775 } else {
6776 let settings = EditorSettings::get_global(cx);
6777 match settings.scroll_beyond_last_line {
6778 ScrollBeyondLastLine::OnePage => max_row,
6779 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6780 ScrollBeyondLastLine::VerticalScrollMargin => {
6781 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6782 .max(0.)
6783 }
6784 }
6785 };
6786
6787 // TODO: Autoscrolling for both axes
6788 let mut autoscroll_request = None;
6789 let mut autoscroll_containing_element = false;
6790 let mut autoscroll_horizontally = false;
6791 self.editor.update(cx, |editor, cx| {
6792 autoscroll_request = editor.autoscroll_request();
6793 autoscroll_containing_element =
6794 autoscroll_request.is_some() || editor.has_pending_selection();
6795 // TODO: Is this horizontal or vertical?!
6796 autoscroll_horizontally = editor.autoscroll_vertically(
6797 bounds,
6798 line_height,
6799 max_scroll_top,
6800 window,
6801 cx,
6802 );
6803 snapshot = editor.snapshot(window, cx);
6804 });
6805
6806 let mut scroll_position = snapshot.scroll_position();
6807 // The scroll position is a fractional point, the whole number of which represents
6808 // the top of the window in terms of display rows.
6809 let start_row = DisplayRow(scroll_position.y as u32);
6810 let max_row = snapshot.max_point().row();
6811 let end_row = cmp::min(
6812 (scroll_position.y + height_in_lines).ceil() as u32,
6813 max_row.next_row().0,
6814 );
6815 let end_row = DisplayRow(end_row);
6816
6817 let row_infos = snapshot
6818 .row_infos(start_row)
6819 .take((start_row..end_row).len())
6820 .collect::<Vec<RowInfo>>();
6821 let is_row_soft_wrapped = |row: usize| {
6822 row_infos
6823 .get(row)
6824 .map_or(true, |info| info.buffer_row.is_none())
6825 };
6826
6827 let start_anchor = if start_row == Default::default() {
6828 Anchor::min()
6829 } else {
6830 snapshot.buffer_snapshot.anchor_before(
6831 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6832 )
6833 };
6834 let end_anchor = if end_row > max_row {
6835 Anchor::max()
6836 } else {
6837 snapshot.buffer_snapshot.anchor_before(
6838 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6839 )
6840 };
6841
6842 let mut highlighted_rows = self
6843 .editor
6844 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6845
6846 for (ix, row_info) in row_infos.iter().enumerate() {
6847 let color = match row_info.diff_status {
6848 Some(DiffHunkStatus::Added) => style.status.created_background,
6849 Some(DiffHunkStatus::Removed) => style.status.deleted_background,
6850 _ => continue,
6851 };
6852 highlighted_rows
6853 .entry(start_row + DisplayRow(ix as u32))
6854 .or_insert(color);
6855 }
6856
6857 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6858 start_anchor..end_anchor,
6859 &snapshot.display_snapshot,
6860 cx.theme().colors(),
6861 );
6862 let highlighted_gutter_ranges =
6863 self.editor.read(cx).gutter_highlights_in_range(
6864 start_anchor..end_anchor,
6865 &snapshot.display_snapshot,
6866 cx,
6867 );
6868
6869 let redacted_ranges = self.editor.read(cx).redacted_ranges(
6870 start_anchor..end_anchor,
6871 &snapshot.display_snapshot,
6872 cx,
6873 );
6874
6875 let (local_selections, selected_buffer_ids): (
6876 Vec<Selection<Point>>,
6877 Vec<BufferId>,
6878 ) = self.editor.update(cx, |editor, cx| {
6879 let all_selections = editor.selections.all::<Point>(cx);
6880 let selected_buffer_ids = if editor.is_singleton(cx) {
6881 Vec::new()
6882 } else {
6883 let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6884
6885 for selection in all_selections {
6886 for buffer_id in snapshot
6887 .buffer_snapshot
6888 .buffer_ids_for_range(selection.range())
6889 {
6890 if selected_buffer_ids.last() != Some(&buffer_id) {
6891 selected_buffer_ids.push(buffer_id);
6892 }
6893 }
6894 }
6895
6896 selected_buffer_ids
6897 };
6898
6899 let mut selections = editor
6900 .selections
6901 .disjoint_in_range(start_anchor..end_anchor, cx);
6902 selections.extend(editor.selections.pending(cx));
6903
6904 (selections, selected_buffer_ids)
6905 });
6906
6907 let (selections, active_rows, newest_selection_head) = self.layout_selections(
6908 start_anchor,
6909 end_anchor,
6910 &local_selections,
6911 &snapshot,
6912 start_row,
6913 end_row,
6914 window,
6915 cx,
6916 );
6917
6918 let line_numbers = self.layout_line_numbers(
6919 Some(&gutter_hitbox),
6920 gutter_dimensions,
6921 line_height,
6922 scroll_position,
6923 start_row..end_row,
6924 &row_infos,
6925 newest_selection_head,
6926 &snapshot,
6927 window,
6928 cx,
6929 );
6930
6931 let mut crease_toggles =
6932 window.with_element_namespace("crease_toggles", |window| {
6933 self.layout_crease_toggles(
6934 start_row..end_row,
6935 &row_infos,
6936 &active_rows,
6937 &snapshot,
6938 window,
6939 cx,
6940 )
6941 });
6942 let crease_trailers =
6943 window.with_element_namespace("crease_trailers", |window| {
6944 self.layout_crease_trailers(
6945 row_infos.iter().copied(),
6946 &snapshot,
6947 window,
6948 cx,
6949 )
6950 });
6951
6952 let display_hunks = self.layout_gutter_diff_hunks(
6953 line_height,
6954 &gutter_hitbox,
6955 start_row..end_row,
6956 &snapshot,
6957 window,
6958 cx,
6959 );
6960
6961 let mut line_layouts = Self::layout_lines(
6962 start_row..end_row,
6963 &snapshot,
6964 &self.style,
6965 editor_width,
6966 is_row_soft_wrapped,
6967 window,
6968 cx,
6969 );
6970
6971 let longest_line_blame_width = self
6972 .editor
6973 .update(cx, |editor, cx| {
6974 if !editor.show_git_blame_inline {
6975 return None;
6976 }
6977 let blame = editor.blame.as_ref()?;
6978 let blame_entry = blame
6979 .update(cx, |blame, cx| {
6980 let row_infos =
6981 snapshot.row_infos(snapshot.longest_row()).next()?;
6982 blame.blame_for_rows(&[row_infos], cx).next()
6983 })
6984 .flatten()?;
6985 let workspace = editor.workspace.as_ref().map(|(w, _)| w.to_owned());
6986 let mut element = render_inline_blame_entry(
6987 blame,
6988 blame_entry,
6989 &style,
6990 workspace,
6991 cx,
6992 );
6993 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
6994 Some(
6995 element
6996 .layout_as_root(AvailableSpace::min_size(), window, cx)
6997 .width
6998 + inline_blame_padding,
6999 )
7000 })
7001 .unwrap_or(Pixels::ZERO);
7002
7003 let longest_line_width = layout_line(
7004 snapshot.longest_row(),
7005 &snapshot,
7006 &style,
7007 editor_width,
7008 is_row_soft_wrapped,
7009 window,
7010 cx,
7011 )
7012 .width;
7013
7014 let scrollbar_range_data = ScrollbarRangeData::new(
7015 scrollbar_bounds,
7016 letter_size,
7017 &snapshot,
7018 longest_line_width,
7019 longest_line_blame_width,
7020 &style,
7021 cx,
7022 );
7023
7024 let scroll_range_bounds = scrollbar_range_data.scroll_range;
7025 let mut scroll_width = scroll_range_bounds.size.width;
7026
7027 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7028 snapshot.sticky_header_excerpt(start_row)
7029 } else {
7030 None
7031 };
7032 let sticky_header_excerpt_id =
7033 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7034
7035 let blocks = window.with_element_namespace("blocks", |window| {
7036 self.render_blocks(
7037 start_row..end_row,
7038 &snapshot,
7039 &hitbox,
7040 &text_hitbox,
7041 editor_width,
7042 &mut scroll_width,
7043 &gutter_dimensions,
7044 em_width,
7045 gutter_dimensions.full_width(),
7046 line_height,
7047 &line_layouts,
7048 &local_selections,
7049 &selected_buffer_ids,
7050 is_row_soft_wrapped,
7051 sticky_header_excerpt_id,
7052 window,
7053 cx,
7054 )
7055 });
7056 let mut blocks = match blocks {
7057 Ok(blocks) => blocks,
7058 Err(resized_blocks) => {
7059 self.editor.update(cx, |editor, cx| {
7060 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7061 });
7062 return self.prepaint(None, bounds, &mut (), window, cx);
7063 }
7064 };
7065
7066 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7067 window.with_element_namespace("blocks", |window| {
7068 self.layout_sticky_buffer_header(
7069 sticky_header_excerpt,
7070 scroll_position.y,
7071 line_height,
7072 &snapshot,
7073 &hitbox,
7074 &selected_buffer_ids,
7075 window,
7076 cx,
7077 )
7078 })
7079 });
7080
7081 let start_buffer_row =
7082 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7083 let end_buffer_row =
7084 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7085
7086 let scroll_max = point(
7087 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7088 max_row.as_f32(),
7089 );
7090
7091 self.editor.update(cx, |editor, cx| {
7092 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7093
7094 let autoscrolled = if autoscroll_horizontally {
7095 editor.autoscroll_horizontally(
7096 start_row,
7097 editor_width - (letter_size.width / 2.0),
7098 scroll_width,
7099 em_width,
7100 &line_layouts,
7101 cx,
7102 )
7103 } else {
7104 false
7105 };
7106
7107 if clamped || autoscrolled {
7108 snapshot = editor.snapshot(window, cx);
7109 scroll_position = snapshot.scroll_position();
7110 }
7111 });
7112
7113 let scroll_pixel_position = point(
7114 scroll_position.x * em_width,
7115 scroll_position.y * line_height,
7116 );
7117
7118 let indent_guides = self.layout_indent_guides(
7119 content_origin,
7120 text_hitbox.origin,
7121 start_buffer_row..end_buffer_row,
7122 scroll_pixel_position,
7123 line_height,
7124 &snapshot,
7125 window,
7126 cx,
7127 );
7128
7129 let crease_trailers =
7130 window.with_element_namespace("crease_trailers", |window| {
7131 self.prepaint_crease_trailers(
7132 crease_trailers,
7133 &line_layouts,
7134 line_height,
7135 content_origin,
7136 scroll_pixel_position,
7137 em_width,
7138 window,
7139 cx,
7140 )
7141 });
7142
7143 let mut inline_blame = None;
7144 if let Some(newest_selection_head) = newest_selection_head {
7145 let display_row = newest_selection_head.row();
7146 if (start_row..end_row).contains(&display_row) {
7147 let line_ix = display_row.minus(start_row) as usize;
7148 let row_info = &row_infos[line_ix];
7149 let line_layout = &line_layouts[line_ix];
7150 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7151 inline_blame = self.layout_inline_blame(
7152 display_row,
7153 row_info,
7154 line_layout,
7155 crease_trailer_layout,
7156 em_width,
7157 content_origin,
7158 scroll_pixel_position,
7159 line_height,
7160 window,
7161 cx,
7162 );
7163 }
7164 }
7165
7166 let blamed_display_rows = self.layout_blame_entries(
7167 &row_infos,
7168 em_width,
7169 scroll_position,
7170 line_height,
7171 &gutter_hitbox,
7172 gutter_dimensions.git_blame_entries_width,
7173 window,
7174 cx,
7175 );
7176
7177 let scroll_max = point(
7178 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7179 max_scroll_top,
7180 );
7181
7182 self.editor.update(cx, |editor, cx| {
7183 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7184
7185 let autoscrolled = if autoscroll_horizontally {
7186 editor.autoscroll_horizontally(
7187 start_row,
7188 editor_width - (letter_size.width / 2.0),
7189 scroll_width,
7190 em_width,
7191 &line_layouts,
7192 cx,
7193 )
7194 } else {
7195 false
7196 };
7197
7198 if clamped || autoscrolled {
7199 snapshot = editor.snapshot(window, cx);
7200 scroll_position = snapshot.scroll_position();
7201 }
7202 });
7203
7204 let line_elements = self.prepaint_lines(
7205 start_row,
7206 &mut line_layouts,
7207 line_height,
7208 scroll_pixel_position,
7209 content_origin,
7210 window,
7211 cx,
7212 );
7213
7214 let mut block_start_rows = HashSet::default();
7215
7216 window.with_element_namespace("blocks", |window| {
7217 self.layout_blocks(
7218 &mut blocks,
7219 &mut block_start_rows,
7220 &hitbox,
7221 line_height,
7222 scroll_pixel_position,
7223 window,
7224 cx,
7225 );
7226 });
7227
7228 let cursors = self.collect_cursors(&snapshot, cx);
7229 let visible_row_range = start_row..end_row;
7230 let non_visible_cursors = cursors
7231 .iter()
7232 .any(move |c| !visible_row_range.contains(&c.0.row()));
7233
7234 let visible_cursors = self.layout_visible_cursors(
7235 &snapshot,
7236 &selections,
7237 &block_start_rows,
7238 start_row..end_row,
7239 &line_layouts,
7240 &text_hitbox,
7241 content_origin,
7242 scroll_position,
7243 scroll_pixel_position,
7244 line_height,
7245 em_width,
7246 em_advance,
7247 autoscroll_containing_element,
7248 window,
7249 cx,
7250 );
7251
7252 let scrollbars_layout = self.layout_scrollbars(
7253 &snapshot,
7254 scrollbar_range_data,
7255 scroll_position,
7256 non_visible_cursors,
7257 window,
7258 cx,
7259 );
7260
7261 let gutter_settings = EditorSettings::get_global(cx).gutter;
7262
7263 let rows_with_hunk_bounds = display_hunks
7264 .iter()
7265 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7266 .fold(
7267 HashMap::default(),
7268 |mut rows_with_hunk_bounds, (hunk, bounds)| {
7269 match hunk {
7270 DisplayDiffHunk::Folded { display_row } => {
7271 rows_with_hunk_bounds.insert(*display_row, bounds);
7272 }
7273 DisplayDiffHunk::Unfolded {
7274 display_row_range, ..
7275 } => {
7276 for display_row in display_row_range.iter_rows() {
7277 rows_with_hunk_bounds.insert(display_row, bounds);
7278 }
7279 }
7280 }
7281 rows_with_hunk_bounds
7282 },
7283 );
7284 let mut code_actions_indicator = None;
7285 if let Some(newest_selection_head) = newest_selection_head {
7286 let newest_selection_point =
7287 newest_selection_head.to_point(&snapshot.display_snapshot);
7288
7289 if (start_row..end_row).contains(&newest_selection_head.row()) {
7290 self.layout_cursor_popovers(
7291 line_height,
7292 &text_hitbox,
7293 content_origin,
7294 start_row,
7295 scroll_pixel_position,
7296 &line_layouts,
7297 newest_selection_head,
7298 newest_selection_point,
7299 &style,
7300 window,
7301 cx,
7302 );
7303
7304 let show_code_actions = snapshot
7305 .show_code_actions
7306 .unwrap_or(gutter_settings.code_actions);
7307 if show_code_actions {
7308 let newest_selection_point =
7309 newest_selection_head.to_point(&snapshot.display_snapshot);
7310 if !snapshot
7311 .is_line_folded(MultiBufferRow(newest_selection_point.row))
7312 {
7313 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7314 MultiBufferRow(newest_selection_point.row),
7315 );
7316 if let Some((buffer, range)) = buffer {
7317 let buffer_id = buffer.remote_id();
7318 let row = range.start.row;
7319 let has_test_indicator = self
7320 .editor
7321 .read(cx)
7322 .tasks
7323 .contains_key(&(buffer_id, row));
7324
7325 if !has_test_indicator {
7326 code_actions_indicator = self
7327 .layout_code_actions_indicator(
7328 line_height,
7329 newest_selection_head,
7330 scroll_pixel_position,
7331 &gutter_dimensions,
7332 &gutter_hitbox,
7333 &rows_with_hunk_bounds,
7334 window,
7335 cx,
7336 );
7337 }
7338 }
7339 }
7340 }
7341 }
7342 }
7343
7344 self.layout_gutter_menu(
7345 line_height,
7346 &text_hitbox,
7347 content_origin,
7348 scroll_pixel_position,
7349 gutter_dimensions.width - gutter_dimensions.left_padding,
7350 window,
7351 cx,
7352 );
7353
7354 let test_indicators = if gutter_settings.runnables {
7355 self.layout_run_indicators(
7356 line_height,
7357 start_row..end_row,
7358 scroll_pixel_position,
7359 &gutter_dimensions,
7360 &gutter_hitbox,
7361 &rows_with_hunk_bounds,
7362 &snapshot,
7363 window,
7364 cx,
7365 )
7366 } else {
7367 Vec::new()
7368 };
7369
7370 self.layout_signature_help(
7371 &hitbox,
7372 content_origin,
7373 scroll_pixel_position,
7374 newest_selection_head,
7375 start_row,
7376 &line_layouts,
7377 line_height,
7378 em_width,
7379 window,
7380 cx,
7381 );
7382
7383 if !cx.has_active_drag() {
7384 self.layout_hover_popovers(
7385 &snapshot,
7386 &hitbox,
7387 &text_hitbox,
7388 start_row..end_row,
7389 content_origin,
7390 scroll_pixel_position,
7391 &line_layouts,
7392 line_height,
7393 em_width,
7394 window,
7395 cx,
7396 );
7397 }
7398
7399 let inline_completion_popover = self.layout_inline_completion_popover(
7400 &text_hitbox.bounds,
7401 &snapshot,
7402 start_row..end_row,
7403 scroll_position.y,
7404 scroll_position.y + height_in_lines,
7405 &line_layouts,
7406 line_height,
7407 scroll_pixel_position,
7408 newest_selection_head,
7409 editor_width,
7410 &style,
7411 window,
7412 cx,
7413 );
7414
7415 let mouse_context_menu = self.layout_mouse_context_menu(
7416 &snapshot,
7417 start_row..end_row,
7418 content_origin,
7419 window,
7420 cx,
7421 );
7422
7423 window.with_element_namespace("crease_toggles", |window| {
7424 self.prepaint_crease_toggles(
7425 &mut crease_toggles,
7426 line_height,
7427 &gutter_dimensions,
7428 gutter_settings,
7429 scroll_pixel_position,
7430 &gutter_hitbox,
7431 window,
7432 cx,
7433 )
7434 });
7435
7436 let invisible_symbol_font_size = font_size / 2.;
7437 let tab_invisible = window
7438 .text_system()
7439 .shape_line(
7440 "→".into(),
7441 invisible_symbol_font_size,
7442 &[TextRun {
7443 len: "→".len(),
7444 font: self.style.text.font(),
7445 color: cx.theme().colors().editor_invisible,
7446 background_color: None,
7447 underline: None,
7448 strikethrough: None,
7449 }],
7450 )
7451 .unwrap();
7452 let space_invisible = window
7453 .text_system()
7454 .shape_line(
7455 "•".into(),
7456 invisible_symbol_font_size,
7457 &[TextRun {
7458 len: "•".len(),
7459 font: self.style.text.font(),
7460 color: cx.theme().colors().editor_invisible,
7461 background_color: None,
7462 underline: None,
7463 strikethrough: None,
7464 }],
7465 )
7466 .unwrap();
7467
7468 let mode = snapshot.mode;
7469
7470 let position_map = Rc::new(PositionMap {
7471 size: bounds.size,
7472 scroll_pixel_position,
7473 scroll_max,
7474 line_layouts,
7475 line_height,
7476 em_width,
7477 em_advance,
7478 snapshot,
7479 gutter_hitbox: gutter_hitbox.clone(),
7480 text_hitbox: text_hitbox.clone(),
7481 });
7482
7483 self.editor.update(cx, |editor, _| {
7484 editor.last_position_map = Some(position_map.clone())
7485 });
7486
7487 let hunk_controls = self.layout_diff_hunk_controls(
7488 start_row..end_row,
7489 &row_infos,
7490 &text_hitbox,
7491 &position_map,
7492 newest_selection_head,
7493 line_height,
7494 scroll_pixel_position,
7495 &display_hunks,
7496 self.editor.clone(),
7497 window,
7498 cx,
7499 );
7500
7501 EditorLayout {
7502 mode,
7503 position_map,
7504 visible_display_row_range: start_row..end_row,
7505 wrap_guides,
7506 indent_guides,
7507 hitbox,
7508 gutter_hitbox,
7509 display_hunks,
7510 content_origin,
7511 scrollbars_layout,
7512 active_rows,
7513 highlighted_rows,
7514 highlighted_ranges,
7515 highlighted_gutter_ranges,
7516 redacted_ranges,
7517 line_elements,
7518 line_numbers,
7519 blamed_display_rows,
7520 inline_blame,
7521 blocks,
7522 cursors,
7523 visible_cursors,
7524 selections,
7525 inline_completion_popover,
7526 diff_hunk_controls: hunk_controls,
7527 mouse_context_menu,
7528 test_indicators,
7529 code_actions_indicator,
7530 crease_toggles,
7531 crease_trailers,
7532 tab_invisible,
7533 space_invisible,
7534 sticky_buffer_header,
7535 }
7536 })
7537 })
7538 })
7539 }
7540
7541 fn paint(
7542 &mut self,
7543 _: Option<&GlobalElementId>,
7544 bounds: Bounds<gpui::Pixels>,
7545 _: &mut Self::RequestLayoutState,
7546 layout: &mut Self::PrepaintState,
7547 window: &mut Window,
7548 cx: &mut App,
7549 ) {
7550 let focus_handle = self.editor.focus_handle(cx);
7551 let key_context = self
7552 .editor
7553 .update(cx, |editor, cx| editor.key_context(window, cx));
7554
7555 window.set_key_context(key_context);
7556 window.handle_input(
7557 &focus_handle,
7558 ElementInputHandler::new(bounds, self.editor.clone()),
7559 cx,
7560 );
7561 self.register_actions(window, cx);
7562 self.register_key_listeners(window, cx, layout);
7563
7564 let text_style = TextStyleRefinement {
7565 font_size: Some(self.style.text.font_size),
7566 line_height: Some(self.style.text.line_height),
7567 ..Default::default()
7568 };
7569 let rem_size = self.rem_size(cx);
7570 window.with_rem_size(rem_size, |window| {
7571 window.with_text_style(Some(text_style), |window| {
7572 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7573 self.paint_mouse_listeners(layout, window, cx);
7574 self.paint_background(layout, window, cx);
7575 self.paint_indent_guides(layout, window, cx);
7576
7577 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7578 self.paint_blamed_display_rows(layout, window, cx);
7579 self.paint_line_numbers(layout, window, cx);
7580 }
7581
7582 self.paint_text(layout, window, cx);
7583
7584 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7585 self.paint_gutter_highlights(layout, window, cx);
7586 self.paint_gutter_indicators(layout, window, cx);
7587 }
7588
7589 if !layout.blocks.is_empty() {
7590 window.with_element_namespace("blocks", |window| {
7591 self.paint_blocks(layout, window, cx);
7592 });
7593 }
7594
7595 window.with_element_namespace("blocks", |window| {
7596 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7597 sticky_header.paint(window, cx)
7598 }
7599 });
7600
7601 self.paint_scrollbars(layout, window, cx);
7602 self.paint_inline_completion_popover(layout, window, cx);
7603 self.paint_mouse_context_menu(layout, window, cx);
7604 });
7605 })
7606 })
7607 }
7608}
7609
7610pub(super) fn gutter_bounds(
7611 editor_bounds: Bounds<Pixels>,
7612 gutter_dimensions: GutterDimensions,
7613) -> Bounds<Pixels> {
7614 Bounds {
7615 origin: editor_bounds.origin,
7616 size: size(gutter_dimensions.width, editor_bounds.size.height),
7617 }
7618}
7619
7620struct ScrollbarRangeData {
7621 scrollbar_bounds: Bounds<Pixels>,
7622 scroll_range: Bounds<Pixels>,
7623 letter_size: Size<Pixels>,
7624}
7625
7626impl ScrollbarRangeData {
7627 pub fn new(
7628 scrollbar_bounds: Bounds<Pixels>,
7629 letter_size: Size<Pixels>,
7630 snapshot: &EditorSnapshot,
7631 longest_line_width: Pixels,
7632 longest_line_blame_width: Pixels,
7633 style: &EditorStyle,
7634
7635 cx: &mut App,
7636 ) -> ScrollbarRangeData {
7637 // TODO: Simplify this function down, it requires a lot of parameters
7638 let max_row = snapshot.max_point().row();
7639 let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7640
7641 let scrollbar_width = style.scrollbar_width;
7642
7643 let settings = EditorSettings::get_global(cx);
7644 let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7645 ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7646 ScrollBeyondLastLine::Off => px(1.),
7647 ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7648 };
7649
7650 let overscroll = size(
7651 scrollbar_width + (letter_size.width / 2.0) + longest_line_blame_width,
7652 letter_size.height * scroll_beyond_last_line,
7653 );
7654
7655 let scroll_range = Bounds {
7656 origin: scrollbar_bounds.origin,
7657 size: text_bounds_size + overscroll,
7658 };
7659
7660 ScrollbarRangeData {
7661 scrollbar_bounds,
7662 scroll_range,
7663 letter_size,
7664 }
7665 }
7666}
7667
7668impl IntoElement for EditorElement {
7669 type Element = Self;
7670
7671 fn into_element(self) -> Self::Element {
7672 self
7673 }
7674}
7675
7676pub struct EditorLayout {
7677 position_map: Rc<PositionMap>,
7678 hitbox: Hitbox,
7679 gutter_hitbox: Hitbox,
7680 content_origin: gpui::Point<Pixels>,
7681 scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7682 mode: EditorMode,
7683 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7684 indent_guides: Option<Vec<IndentGuideLayout>>,
7685 visible_display_row_range: Range<DisplayRow>,
7686 active_rows: BTreeMap<DisplayRow, bool>,
7687 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
7688 line_elements: SmallVec<[AnyElement; 1]>,
7689 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7690 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7691 blamed_display_rows: Option<Vec<AnyElement>>,
7692 inline_blame: Option<AnyElement>,
7693 blocks: Vec<BlockLayout>,
7694 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7695 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7696 redacted_ranges: Vec<Range<DisplayPoint>>,
7697 cursors: Vec<(DisplayPoint, Hsla)>,
7698 visible_cursors: Vec<CursorLayout>,
7699 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7700 code_actions_indicator: Option<AnyElement>,
7701 test_indicators: Vec<AnyElement>,
7702 crease_toggles: Vec<Option<AnyElement>>,
7703 diff_hunk_controls: Vec<AnyElement>,
7704 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7705 inline_completion_popover: Option<AnyElement>,
7706 mouse_context_menu: Option<AnyElement>,
7707 tab_invisible: ShapedLine,
7708 space_invisible: ShapedLine,
7709 sticky_buffer_header: Option<AnyElement>,
7710}
7711
7712impl EditorLayout {
7713 fn line_end_overshoot(&self) -> Pixels {
7714 0.15 * self.position_map.line_height
7715 }
7716}
7717
7718struct LineNumberLayout {
7719 shaped_line: ShapedLine,
7720 hitbox: Option<Hitbox>,
7721 display_row: DisplayRow,
7722}
7723
7724struct ColoredRange<T> {
7725 start: T,
7726 end: T,
7727 color: Hsla,
7728}
7729
7730#[derive(Clone)]
7731struct ScrollbarLayout {
7732 hitbox: Hitbox,
7733 visible_range: Range<f32>,
7734 visible: bool,
7735 text_unit_size: Pixels,
7736 thumb_size: Pixels,
7737 axis: Axis,
7738}
7739
7740impl ScrollbarLayout {
7741 const BORDER_WIDTH: Pixels = px(1.0);
7742 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7743 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7744 // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7745
7746 fn thumb_bounds(&self) -> Bounds<Pixels> {
7747 match self.axis {
7748 Axis::Vertical => {
7749 let thumb_top = self.y_for_row(self.visible_range.start);
7750 let thumb_bottom = thumb_top + self.thumb_size;
7751 Bounds::from_corners(
7752 point(self.hitbox.left(), thumb_top),
7753 point(self.hitbox.right(), thumb_bottom),
7754 )
7755 }
7756 Axis::Horizontal => {
7757 let thumb_left =
7758 self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7759 let thumb_right = thumb_left + self.thumb_size;
7760 Bounds::from_corners(
7761 point(thumb_left, self.hitbox.top()),
7762 point(thumb_right, self.hitbox.bottom()),
7763 )
7764 }
7765 }
7766 }
7767
7768 fn y_for_row(&self, row: f32) -> Pixels {
7769 self.hitbox.top() + row * self.text_unit_size
7770 }
7771
7772 fn marker_quads_for_ranges(
7773 &self,
7774 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7775 column: Option<usize>,
7776 ) -> Vec<PaintQuad> {
7777 struct MinMax {
7778 min: Pixels,
7779 max: Pixels,
7780 }
7781 let (x_range, height_limit) = if let Some(column) = column {
7782 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7783 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7784 let end = start + column_width;
7785 (
7786 Range { start, end },
7787 MinMax {
7788 min: Self::MIN_MARKER_HEIGHT,
7789 max: px(f32::MAX),
7790 },
7791 )
7792 } else {
7793 (
7794 Range {
7795 start: Self::BORDER_WIDTH,
7796 end: self.hitbox.size.width,
7797 },
7798 MinMax {
7799 min: Self::LINE_MARKER_HEIGHT,
7800 max: Self::LINE_MARKER_HEIGHT,
7801 },
7802 )
7803 };
7804
7805 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7806 let mut pixel_ranges = row_ranges
7807 .into_iter()
7808 .map(|range| {
7809 let start_y = row_to_y(range.start);
7810 let end_y = row_to_y(range.end)
7811 + self
7812 .text_unit_size
7813 .max(height_limit.min)
7814 .min(height_limit.max);
7815 ColoredRange {
7816 start: start_y,
7817 end: end_y,
7818 color: range.color,
7819 }
7820 })
7821 .peekable();
7822
7823 let mut quads = Vec::new();
7824 while let Some(mut pixel_range) = pixel_ranges.next() {
7825 while let Some(next_pixel_range) = pixel_ranges.peek() {
7826 if pixel_range.end >= next_pixel_range.start - px(1.0)
7827 && pixel_range.color == next_pixel_range.color
7828 {
7829 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7830 pixel_ranges.next();
7831 } else {
7832 break;
7833 }
7834 }
7835
7836 let bounds = Bounds::from_corners(
7837 point(x_range.start, pixel_range.start),
7838 point(x_range.end, pixel_range.end),
7839 );
7840 quads.push(quad(
7841 bounds,
7842 Corners::default(),
7843 pixel_range.color,
7844 Edges::default(),
7845 Hsla::transparent_black(),
7846 ));
7847 }
7848
7849 quads
7850 }
7851}
7852
7853struct CreaseTrailerLayout {
7854 element: AnyElement,
7855 bounds: Bounds<Pixels>,
7856}
7857
7858pub(crate) struct PositionMap {
7859 pub size: Size<Pixels>,
7860 pub line_height: Pixels,
7861 pub scroll_pixel_position: gpui::Point<Pixels>,
7862 pub scroll_max: gpui::Point<f32>,
7863 pub em_width: Pixels,
7864 pub em_advance: Pixels,
7865 pub line_layouts: Vec<LineWithInvisibles>,
7866 pub snapshot: EditorSnapshot,
7867 pub text_hitbox: Hitbox,
7868 pub gutter_hitbox: Hitbox,
7869}
7870
7871#[derive(Debug, Copy, Clone)]
7872pub struct PointForPosition {
7873 pub previous_valid: DisplayPoint,
7874 pub next_valid: DisplayPoint,
7875 pub exact_unclipped: DisplayPoint,
7876 pub column_overshoot_after_line_end: u32,
7877}
7878
7879impl PointForPosition {
7880 pub fn as_valid(&self) -> Option<DisplayPoint> {
7881 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
7882 Some(self.previous_valid)
7883 } else {
7884 None
7885 }
7886 }
7887}
7888
7889impl PositionMap {
7890 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
7891 let text_bounds = self.text_hitbox.bounds;
7892 let scroll_position = self.snapshot.scroll_position();
7893 let position = position - text_bounds.origin;
7894 let y = position.y.max(px(0.)).min(self.size.height);
7895 let x = position.x + (scroll_position.x * self.em_width);
7896 let row = ((y / self.line_height) + scroll_position.y) as u32;
7897
7898 let (column, x_overshoot_after_line_end) = if let Some(line) = self
7899 .line_layouts
7900 .get(row as usize - scroll_position.y as usize)
7901 {
7902 if let Some(ix) = line.index_for_x(x) {
7903 (ix as u32, px(0.))
7904 } else {
7905 (line.len as u32, px(0.).max(x - line.width))
7906 }
7907 } else {
7908 (0, x)
7909 };
7910
7911 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
7912 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
7913 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
7914
7915 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
7916 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
7917 PointForPosition {
7918 previous_valid,
7919 next_valid,
7920 exact_unclipped,
7921 column_overshoot_after_line_end,
7922 }
7923 }
7924}
7925
7926struct BlockLayout {
7927 id: BlockId,
7928 row: Option<DisplayRow>,
7929 element: AnyElement,
7930 available_space: Size<AvailableSpace>,
7931 style: BlockStyle,
7932}
7933
7934fn layout_line(
7935 row: DisplayRow,
7936 snapshot: &EditorSnapshot,
7937 style: &EditorStyle,
7938 text_width: Pixels,
7939 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7940 window: &mut Window,
7941 cx: &mut App,
7942) -> LineWithInvisibles {
7943 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
7944 LineWithInvisibles::from_chunks(
7945 chunks,
7946 &style,
7947 MAX_LINE_LEN,
7948 1,
7949 snapshot.mode,
7950 text_width,
7951 is_row_soft_wrapped,
7952 window,
7953 cx,
7954 )
7955 .pop()
7956 .unwrap()
7957}
7958
7959#[derive(Debug)]
7960pub struct IndentGuideLayout {
7961 origin: gpui::Point<Pixels>,
7962 length: Pixels,
7963 single_indent_width: Pixels,
7964 depth: u32,
7965 active: bool,
7966 settings: IndentGuideSettings,
7967}
7968
7969pub struct CursorLayout {
7970 origin: gpui::Point<Pixels>,
7971 block_width: Pixels,
7972 line_height: Pixels,
7973 color: Hsla,
7974 shape: CursorShape,
7975 block_text: Option<ShapedLine>,
7976 cursor_name: Option<AnyElement>,
7977}
7978
7979#[derive(Debug)]
7980pub struct CursorName {
7981 string: SharedString,
7982 color: Hsla,
7983 is_top_row: bool,
7984}
7985
7986impl CursorLayout {
7987 pub fn new(
7988 origin: gpui::Point<Pixels>,
7989 block_width: Pixels,
7990 line_height: Pixels,
7991 color: Hsla,
7992 shape: CursorShape,
7993 block_text: Option<ShapedLine>,
7994 ) -> CursorLayout {
7995 CursorLayout {
7996 origin,
7997 block_width,
7998 line_height,
7999 color,
8000 shape,
8001 block_text,
8002 cursor_name: None,
8003 }
8004 }
8005
8006 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8007 Bounds {
8008 origin: self.origin + origin,
8009 size: size(self.block_width, self.line_height),
8010 }
8011 }
8012
8013 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8014 match self.shape {
8015 CursorShape::Bar => Bounds {
8016 origin: self.origin + origin,
8017 size: size(px(2.0), self.line_height),
8018 },
8019 CursorShape::Block | CursorShape::Hollow => Bounds {
8020 origin: self.origin + origin,
8021 size: size(self.block_width, self.line_height),
8022 },
8023 CursorShape::Underline => Bounds {
8024 origin: self.origin
8025 + origin
8026 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8027 size: size(self.block_width, px(2.0)),
8028 },
8029 }
8030 }
8031
8032 pub fn layout(
8033 &mut self,
8034 origin: gpui::Point<Pixels>,
8035 cursor_name: Option<CursorName>,
8036 window: &mut Window,
8037 cx: &mut App,
8038 ) {
8039 if let Some(cursor_name) = cursor_name {
8040 let bounds = self.bounds(origin);
8041 let text_size = self.line_height / 1.5;
8042
8043 let name_origin = if cursor_name.is_top_row {
8044 point(bounds.right() - px(1.), bounds.top())
8045 } else {
8046 match self.shape {
8047 CursorShape::Bar => point(
8048 bounds.right() - px(2.),
8049 bounds.top() - text_size / 2. - px(1.),
8050 ),
8051 _ => point(
8052 bounds.right() - px(1.),
8053 bounds.top() - text_size / 2. - px(1.),
8054 ),
8055 }
8056 };
8057 let mut name_element = div()
8058 .bg(self.color)
8059 .text_size(text_size)
8060 .px_0p5()
8061 .line_height(text_size + px(2.))
8062 .text_color(cursor_name.color)
8063 .child(cursor_name.string.clone())
8064 .into_any_element();
8065
8066 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8067
8068 self.cursor_name = Some(name_element);
8069 }
8070 }
8071
8072 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8073 let bounds = self.bounds(origin);
8074
8075 //Draw background or border quad
8076 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8077 outline(bounds, self.color)
8078 } else {
8079 fill(bounds, self.color)
8080 };
8081
8082 if let Some(name) = &mut self.cursor_name {
8083 name.paint(window, cx);
8084 }
8085
8086 window.paint_quad(cursor);
8087
8088 if let Some(block_text) = &self.block_text {
8089 block_text
8090 .paint(self.origin + origin, self.line_height, window, cx)
8091 .log_err();
8092 }
8093 }
8094
8095 pub fn shape(&self) -> CursorShape {
8096 self.shape
8097 }
8098}
8099
8100#[derive(Debug)]
8101pub struct HighlightedRange {
8102 pub start_y: Pixels,
8103 pub line_height: Pixels,
8104 pub lines: Vec<HighlightedRangeLine>,
8105 pub color: Hsla,
8106 pub corner_radius: Pixels,
8107}
8108
8109#[derive(Debug)]
8110pub struct HighlightedRangeLine {
8111 pub start_x: Pixels,
8112 pub end_x: Pixels,
8113}
8114
8115impl HighlightedRange {
8116 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8117 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8118 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8119 self.paint_lines(
8120 self.start_y + self.line_height,
8121 &self.lines[1..],
8122 bounds,
8123 window,
8124 );
8125 } else {
8126 self.paint_lines(self.start_y, &self.lines, bounds, window);
8127 }
8128 }
8129
8130 fn paint_lines(
8131 &self,
8132 start_y: Pixels,
8133 lines: &[HighlightedRangeLine],
8134 _bounds: Bounds<Pixels>,
8135 window: &mut Window,
8136 ) {
8137 if lines.is_empty() {
8138 return;
8139 }
8140
8141 let first_line = lines.first().unwrap();
8142 let last_line = lines.last().unwrap();
8143
8144 let first_top_left = point(first_line.start_x, start_y);
8145 let first_top_right = point(first_line.end_x, start_y);
8146
8147 let curve_height = point(Pixels::ZERO, self.corner_radius);
8148 let curve_width = |start_x: Pixels, end_x: Pixels| {
8149 let max = (end_x - start_x) / 2.;
8150 let width = if max < self.corner_radius {
8151 max
8152 } else {
8153 self.corner_radius
8154 };
8155
8156 point(width, Pixels::ZERO)
8157 };
8158
8159 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8160 let mut builder = gpui::PathBuilder::fill();
8161 builder.move_to(first_top_right - top_curve_width);
8162 builder.curve_to(first_top_right + curve_height, first_top_right);
8163
8164 let mut iter = lines.iter().enumerate().peekable();
8165 while let Some((ix, line)) = iter.next() {
8166 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8167
8168 if let Some((_, next_line)) = iter.peek() {
8169 let next_top_right = point(next_line.end_x, bottom_right.y);
8170
8171 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8172 Ordering::Equal => {
8173 builder.line_to(bottom_right);
8174 }
8175 Ordering::Less => {
8176 let curve_width = curve_width(next_top_right.x, bottom_right.x);
8177 builder.line_to(bottom_right - curve_height);
8178 if self.corner_radius > Pixels::ZERO {
8179 builder.curve_to(bottom_right - curve_width, bottom_right);
8180 }
8181 builder.line_to(next_top_right + curve_width);
8182 if self.corner_radius > Pixels::ZERO {
8183 builder.curve_to(next_top_right + curve_height, next_top_right);
8184 }
8185 }
8186 Ordering::Greater => {
8187 let curve_width = curve_width(bottom_right.x, next_top_right.x);
8188 builder.line_to(bottom_right - curve_height);
8189 if self.corner_radius > Pixels::ZERO {
8190 builder.curve_to(bottom_right + curve_width, bottom_right);
8191 }
8192 builder.line_to(next_top_right - curve_width);
8193 if self.corner_radius > Pixels::ZERO {
8194 builder.curve_to(next_top_right + curve_height, next_top_right);
8195 }
8196 }
8197 }
8198 } else {
8199 let curve_width = curve_width(line.start_x, line.end_x);
8200 builder.line_to(bottom_right - curve_height);
8201 if self.corner_radius > Pixels::ZERO {
8202 builder.curve_to(bottom_right - curve_width, bottom_right);
8203 }
8204
8205 let bottom_left = point(line.start_x, bottom_right.y);
8206 builder.line_to(bottom_left + curve_width);
8207 if self.corner_radius > Pixels::ZERO {
8208 builder.curve_to(bottom_left - curve_height, bottom_left);
8209 }
8210 }
8211 }
8212
8213 if first_line.start_x > last_line.start_x {
8214 let curve_width = curve_width(last_line.start_x, first_line.start_x);
8215 let second_top_left = point(last_line.start_x, start_y + self.line_height);
8216 builder.line_to(second_top_left + curve_height);
8217 if self.corner_radius > Pixels::ZERO {
8218 builder.curve_to(second_top_left + curve_width, second_top_left);
8219 }
8220 let first_bottom_left = point(first_line.start_x, second_top_left.y);
8221 builder.line_to(first_bottom_left - curve_width);
8222 if self.corner_radius > Pixels::ZERO {
8223 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8224 }
8225 }
8226
8227 builder.line_to(first_top_left + curve_height);
8228 if self.corner_radius > Pixels::ZERO {
8229 builder.curve_to(first_top_left + top_curve_width, first_top_left);
8230 }
8231 builder.line_to(first_top_right - top_curve_width);
8232
8233 if let Ok(path) = builder.build() {
8234 window.paint_path(path, self.color);
8235 }
8236 }
8237}
8238
8239enum CursorPopoverType {
8240 CodeContextMenu,
8241 EditPrediction,
8242}
8243
8244pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8245 (delta.pow(1.5) / 100.0).into()
8246}
8247
8248fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8249 (delta.pow(1.2) / 300.0).into()
8250}
8251
8252pub fn register_action<T: Action>(
8253 editor: &Entity<Editor>,
8254 window: &mut Window,
8255 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8256) {
8257 let editor = editor.clone();
8258 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8259 let action = action.downcast_ref().unwrap();
8260 if phase == DispatchPhase::Bubble {
8261 editor.update(cx, |editor, cx| {
8262 listener(editor, action, window, cx);
8263 })
8264 }
8265 })
8266}
8267
8268fn compute_auto_height_layout(
8269 editor: &mut Editor,
8270 max_lines: usize,
8271 max_line_number_width: Pixels,
8272 known_dimensions: Size<Option<Pixels>>,
8273 available_width: AvailableSpace,
8274 window: &mut Window,
8275 cx: &mut Context<Editor>,
8276) -> Option<Size<Pixels>> {
8277 let width = known_dimensions.width.or({
8278 if let AvailableSpace::Definite(available_width) = available_width {
8279 Some(available_width)
8280 } else {
8281 None
8282 }
8283 })?;
8284 if let Some(height) = known_dimensions.height {
8285 return Some(size(width, height));
8286 }
8287
8288 let style = editor.style.as_ref().unwrap();
8289 let font_id = window.text_system().resolve_font(&style.text.font());
8290 let font_size = style.text.font_size.to_pixels(window.rem_size());
8291 let line_height = style.text.line_height_in_pixels(window.rem_size());
8292 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8293
8294 let mut snapshot = editor.snapshot(window, cx);
8295 let gutter_dimensions = snapshot
8296 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8297 .unwrap_or_default();
8298
8299 editor.gutter_dimensions = gutter_dimensions;
8300 let text_width = width - gutter_dimensions.width;
8301 let overscroll = size(em_width, px(0.));
8302
8303 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8304 if editor.set_wrap_width(Some(editor_width), cx) {
8305 snapshot = editor.snapshot(window, cx);
8306 }
8307
8308 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8309 let height = scroll_height
8310 .max(line_height)
8311 .min(line_height * max_lines as f32);
8312
8313 Some(size(width, height))
8314}
8315
8316#[cfg(test)]
8317mod tests {
8318 use super::*;
8319 use crate::{
8320 display_map::{BlockPlacement, BlockProperties},
8321 editor_tests::{init_test, update_test_language_settings},
8322 Editor, MultiBuffer,
8323 };
8324 use gpui::{TestAppContext, VisualTestContext};
8325 use language::language_settings;
8326 use log::info;
8327 use similar::DiffableStr;
8328 use std::num::NonZeroU32;
8329 use util::test::sample_text;
8330
8331 #[gpui::test]
8332 fn test_shape_line_numbers(cx: &mut TestAppContext) {
8333 init_test(cx, |_| {});
8334 let window = cx.add_window(|window, cx| {
8335 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8336 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8337 });
8338
8339 let editor = window.root(cx).unwrap();
8340 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8341 let line_height = window
8342 .update(cx, |_, window, _| {
8343 style.text.line_height_in_pixels(window.rem_size())
8344 })
8345 .unwrap();
8346 let element = EditorElement::new(&editor, style);
8347 let snapshot = window
8348 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8349 .unwrap();
8350
8351 let layouts = cx
8352 .update_window(*window, |_, window, cx| {
8353 element.layout_line_numbers(
8354 None,
8355 GutterDimensions {
8356 left_padding: Pixels::ZERO,
8357 right_padding: Pixels::ZERO,
8358 width: px(30.0),
8359 margin: Pixels::ZERO,
8360 git_blame_entries_width: None,
8361 },
8362 line_height,
8363 gpui::Point::default(),
8364 DisplayRow(0)..DisplayRow(6),
8365 &(0..6)
8366 .map(|row| RowInfo {
8367 buffer_row: Some(row),
8368 ..Default::default()
8369 })
8370 .collect::<Vec<_>>(),
8371 Some(DisplayPoint::new(DisplayRow(0), 0)),
8372 &snapshot,
8373 window,
8374 cx,
8375 )
8376 })
8377 .unwrap();
8378 assert_eq!(layouts.len(), 6);
8379
8380 let relative_rows = window
8381 .update(cx, |editor, window, cx| {
8382 let snapshot = editor.snapshot(window, cx);
8383 element.calculate_relative_line_numbers(
8384 &snapshot,
8385 &(DisplayRow(0)..DisplayRow(6)),
8386 Some(DisplayRow(3)),
8387 )
8388 })
8389 .unwrap();
8390 assert_eq!(relative_rows[&DisplayRow(0)], 3);
8391 assert_eq!(relative_rows[&DisplayRow(1)], 2);
8392 assert_eq!(relative_rows[&DisplayRow(2)], 1);
8393 // current line has no relative number
8394 assert_eq!(relative_rows[&DisplayRow(4)], 1);
8395 assert_eq!(relative_rows[&DisplayRow(5)], 2);
8396
8397 // works if cursor is before screen
8398 let relative_rows = window
8399 .update(cx, |editor, window, cx| {
8400 let snapshot = editor.snapshot(window, cx);
8401 element.calculate_relative_line_numbers(
8402 &snapshot,
8403 &(DisplayRow(3)..DisplayRow(6)),
8404 Some(DisplayRow(1)),
8405 )
8406 })
8407 .unwrap();
8408 assert_eq!(relative_rows.len(), 3);
8409 assert_eq!(relative_rows[&DisplayRow(3)], 2);
8410 assert_eq!(relative_rows[&DisplayRow(4)], 3);
8411 assert_eq!(relative_rows[&DisplayRow(5)], 4);
8412
8413 // works if cursor is after screen
8414 let relative_rows = window
8415 .update(cx, |editor, window, cx| {
8416 let snapshot = editor.snapshot(window, cx);
8417 element.calculate_relative_line_numbers(
8418 &snapshot,
8419 &(DisplayRow(0)..DisplayRow(3)),
8420 Some(DisplayRow(6)),
8421 )
8422 })
8423 .unwrap();
8424 assert_eq!(relative_rows.len(), 3);
8425 assert_eq!(relative_rows[&DisplayRow(0)], 5);
8426 assert_eq!(relative_rows[&DisplayRow(1)], 4);
8427 assert_eq!(relative_rows[&DisplayRow(2)], 3);
8428 }
8429
8430 #[gpui::test]
8431 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8432 init_test(cx, |_| {});
8433
8434 let window = cx.add_window(|window, cx| {
8435 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8436 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8437 });
8438 let cx = &mut VisualTestContext::from_window(*window, cx);
8439 let editor = window.root(cx).unwrap();
8440 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8441
8442 window
8443 .update(cx, |editor, window, cx| {
8444 editor.cursor_shape = CursorShape::Block;
8445 editor.change_selections(None, window, cx, |s| {
8446 s.select_ranges([
8447 Point::new(0, 0)..Point::new(1, 0),
8448 Point::new(3, 2)..Point::new(3, 3),
8449 Point::new(5, 6)..Point::new(6, 0),
8450 ]);
8451 });
8452 })
8453 .unwrap();
8454
8455 let (_, state) = cx.draw(
8456 point(px(500.), px(500.)),
8457 size(px(500.), px(500.)),
8458 |_, _| EditorElement::new(&editor, style),
8459 );
8460
8461 assert_eq!(state.selections.len(), 1);
8462 let local_selections = &state.selections[0].1;
8463 assert_eq!(local_selections.len(), 3);
8464 // moves cursor back one line
8465 assert_eq!(
8466 local_selections[0].head,
8467 DisplayPoint::new(DisplayRow(0), 6)
8468 );
8469 assert_eq!(
8470 local_selections[0].range,
8471 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8472 );
8473
8474 // moves cursor back one column
8475 assert_eq!(
8476 local_selections[1].range,
8477 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8478 );
8479 assert_eq!(
8480 local_selections[1].head,
8481 DisplayPoint::new(DisplayRow(3), 2)
8482 );
8483
8484 // leaves cursor on the max point
8485 assert_eq!(
8486 local_selections[2].range,
8487 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8488 );
8489 assert_eq!(
8490 local_selections[2].head,
8491 DisplayPoint::new(DisplayRow(6), 0)
8492 );
8493
8494 // active lines does not include 1 (even though the range of the selection does)
8495 assert_eq!(
8496 state.active_rows.keys().cloned().collect::<Vec<_>>(),
8497 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8498 );
8499
8500 // multi-buffer support
8501 // in DisplayPoint coordinates, this is what we're dealing with:
8502 // 0: [[file
8503 // 1: header
8504 // 2: section]]
8505 // 3: aaaaaa
8506 // 4: bbbbbb
8507 // 5: cccccc
8508 // 6:
8509 // 7: [[footer]]
8510 // 8: [[header]]
8511 // 9: ffffff
8512 // 10: gggggg
8513 // 11: hhhhhh
8514 // 12:
8515 // 13: [[footer]]
8516 // 14: [[file
8517 // 15: header
8518 // 16: section]]
8519 // 17: bbbbbb
8520 // 18: cccccc
8521 // 19: dddddd
8522 // 20: [[footer]]
8523 let window = cx.add_window(|window, cx| {
8524 let buffer = MultiBuffer::build_multi(
8525 [
8526 (
8527 &(sample_text(8, 6, 'a') + "\n"),
8528 vec![
8529 Point::new(0, 0)..Point::new(3, 0),
8530 Point::new(4, 0)..Point::new(7, 0),
8531 ],
8532 ),
8533 (
8534 &(sample_text(8, 6, 'a') + "\n"),
8535 vec![Point::new(1, 0)..Point::new(3, 0)],
8536 ),
8537 ],
8538 cx,
8539 );
8540 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8541 });
8542 let editor = window.root(cx).unwrap();
8543 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8544 let _state = window.update(cx, |editor, window, cx| {
8545 editor.cursor_shape = CursorShape::Block;
8546 editor.change_selections(None, window, cx, |s| {
8547 s.select_display_ranges([
8548 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8549 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8550 ]);
8551 });
8552 });
8553
8554 let (_, state) = cx.draw(
8555 point(px(500.), px(500.)),
8556 size(px(500.), px(500.)),
8557 |_, _| EditorElement::new(&editor, style),
8558 );
8559 assert_eq!(state.selections.len(), 1);
8560 let local_selections = &state.selections[0].1;
8561 assert_eq!(local_selections.len(), 2);
8562
8563 // moves cursor on excerpt boundary back a line
8564 // and doesn't allow selection to bleed through
8565 assert_eq!(
8566 local_selections[0].range,
8567 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8568 );
8569 assert_eq!(
8570 local_selections[0].head,
8571 DisplayPoint::new(DisplayRow(6), 0)
8572 );
8573 // moves cursor on buffer boundary back two lines
8574 // and doesn't allow selection to bleed through
8575 assert_eq!(
8576 local_selections[1].range,
8577 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8578 );
8579 assert_eq!(
8580 local_selections[1].head,
8581 DisplayPoint::new(DisplayRow(12), 0)
8582 );
8583 }
8584
8585 #[gpui::test]
8586 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8587 init_test(cx, |_| {});
8588
8589 let window = cx.add_window(|window, cx| {
8590 let buffer = MultiBuffer::build_simple("", cx);
8591 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8592 });
8593 let cx = &mut VisualTestContext::from_window(*window, cx);
8594 let editor = window.root(cx).unwrap();
8595 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8596 window
8597 .update(cx, |editor, window, cx| {
8598 editor.set_placeholder_text("hello", cx);
8599 editor.insert_blocks(
8600 [BlockProperties {
8601 style: BlockStyle::Fixed,
8602 placement: BlockPlacement::Above(Anchor::min()),
8603 height: 3,
8604 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8605 priority: 0,
8606 }],
8607 None,
8608 cx,
8609 );
8610
8611 // Blur the editor so that it displays placeholder text.
8612 window.blur();
8613 })
8614 .unwrap();
8615
8616 let (_, state) = cx.draw(
8617 point(px(500.), px(500.)),
8618 size(px(500.), px(500.)),
8619 |_, _| EditorElement::new(&editor, style),
8620 );
8621 assert_eq!(state.position_map.line_layouts.len(), 4);
8622 assert_eq!(state.line_numbers.len(), 1);
8623 assert_eq!(
8624 state
8625 .line_numbers
8626 .get(&MultiBufferRow(0))
8627 .and_then(|line_number| line_number.shaped_line.text.as_str()),
8628 Some("1")
8629 );
8630 }
8631
8632 #[gpui::test]
8633 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8634 const TAB_SIZE: u32 = 4;
8635
8636 let input_text = "\t \t|\t| a b";
8637 let expected_invisibles = vec![
8638 Invisible::Tab {
8639 line_start_offset: 0,
8640 line_end_offset: TAB_SIZE as usize,
8641 },
8642 Invisible::Whitespace {
8643 line_offset: TAB_SIZE as usize,
8644 },
8645 Invisible::Tab {
8646 line_start_offset: TAB_SIZE as usize + 1,
8647 line_end_offset: TAB_SIZE as usize * 2,
8648 },
8649 Invisible::Tab {
8650 line_start_offset: TAB_SIZE as usize * 2 + 1,
8651 line_end_offset: TAB_SIZE as usize * 3,
8652 },
8653 Invisible::Whitespace {
8654 line_offset: TAB_SIZE as usize * 3 + 1,
8655 },
8656 Invisible::Whitespace {
8657 line_offset: TAB_SIZE as usize * 3 + 3,
8658 },
8659 ];
8660 assert_eq!(
8661 expected_invisibles.len(),
8662 input_text
8663 .chars()
8664 .filter(|initial_char| initial_char.is_whitespace())
8665 .count(),
8666 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8667 );
8668
8669 for show_line_numbers in [true, false] {
8670 init_test(cx, |s| {
8671 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8672 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8673 });
8674
8675 let actual_invisibles = collect_invisibles_from_new_editor(
8676 cx,
8677 EditorMode::Full,
8678 input_text,
8679 px(500.0),
8680 show_line_numbers,
8681 );
8682
8683 assert_eq!(expected_invisibles, actual_invisibles);
8684 }
8685 }
8686
8687 #[gpui::test]
8688 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8689 init_test(cx, |s| {
8690 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8691 s.defaults.tab_size = NonZeroU32::new(4);
8692 });
8693
8694 for editor_mode_without_invisibles in [
8695 EditorMode::SingleLine { auto_width: false },
8696 EditorMode::AutoHeight { max_lines: 100 },
8697 ] {
8698 for show_line_numbers in [true, false] {
8699 let invisibles = collect_invisibles_from_new_editor(
8700 cx,
8701 editor_mode_without_invisibles,
8702 "\t\t\t| | a b",
8703 px(500.0),
8704 show_line_numbers,
8705 );
8706 assert!(invisibles.is_empty(),
8707 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8708 }
8709 }
8710 }
8711
8712 #[gpui::test]
8713 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8714 let tab_size = 4;
8715 let input_text = "a\tbcd ".repeat(9);
8716 let repeated_invisibles = [
8717 Invisible::Tab {
8718 line_start_offset: 1,
8719 line_end_offset: tab_size as usize,
8720 },
8721 Invisible::Whitespace {
8722 line_offset: tab_size as usize + 3,
8723 },
8724 Invisible::Whitespace {
8725 line_offset: tab_size as usize + 4,
8726 },
8727 Invisible::Whitespace {
8728 line_offset: tab_size as usize + 5,
8729 },
8730 Invisible::Whitespace {
8731 line_offset: tab_size as usize + 6,
8732 },
8733 Invisible::Whitespace {
8734 line_offset: tab_size as usize + 7,
8735 },
8736 ];
8737 let expected_invisibles = std::iter::once(repeated_invisibles)
8738 .cycle()
8739 .take(9)
8740 .flatten()
8741 .collect::<Vec<_>>();
8742 assert_eq!(
8743 expected_invisibles.len(),
8744 input_text
8745 .chars()
8746 .filter(|initial_char| initial_char.is_whitespace())
8747 .count(),
8748 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8749 );
8750 info!("Expected invisibles: {expected_invisibles:?}");
8751
8752 init_test(cx, |_| {});
8753
8754 // Put the same string with repeating whitespace pattern into editors of various size,
8755 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8756 let resize_step = 10.0;
8757 let mut editor_width = 200.0;
8758 while editor_width <= 1000.0 {
8759 for show_line_numbers in [true, false] {
8760 update_test_language_settings(cx, |s| {
8761 s.defaults.tab_size = NonZeroU32::new(tab_size);
8762 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8763 s.defaults.preferred_line_length = Some(editor_width as u32);
8764 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8765 });
8766
8767 let actual_invisibles = collect_invisibles_from_new_editor(
8768 cx,
8769 EditorMode::Full,
8770 &input_text,
8771 px(editor_width),
8772 show_line_numbers,
8773 );
8774
8775 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8776 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8777 let mut i = 0;
8778 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8779 i = actual_index;
8780 match expected_invisibles.get(i) {
8781 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8782 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8783 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8784 _ => {
8785 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8786 }
8787 },
8788 None => {
8789 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8790 }
8791 }
8792 }
8793 let missing_expected_invisibles = &expected_invisibles[i + 1..];
8794 assert!(
8795 missing_expected_invisibles.is_empty(),
8796 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8797 );
8798
8799 editor_width += resize_step;
8800 }
8801 }
8802 }
8803
8804 fn collect_invisibles_from_new_editor(
8805 cx: &mut TestAppContext,
8806 editor_mode: EditorMode,
8807 input_text: &str,
8808 editor_width: Pixels,
8809 show_line_numbers: bool,
8810 ) -> Vec<Invisible> {
8811 info!(
8812 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8813 editor_width.0
8814 );
8815 let window = cx.add_window(|window, cx| {
8816 let buffer = MultiBuffer::build_simple(input_text, cx);
8817 Editor::new(editor_mode, buffer, None, true, window, cx)
8818 });
8819 let cx = &mut VisualTestContext::from_window(*window, cx);
8820 let editor = window.root(cx).unwrap();
8821
8822 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8823 window
8824 .update(cx, |editor, _, cx| {
8825 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8826 editor.set_wrap_width(Some(editor_width), cx);
8827 editor.set_show_line_numbers(show_line_numbers, cx);
8828 })
8829 .unwrap();
8830 let (_, state) = cx.draw(
8831 point(px(500.), px(500.)),
8832 size(px(500.), px(500.)),
8833 |_, _| EditorElement::new(&editor, style),
8834 );
8835 state
8836 .position_map
8837 .line_layouts
8838 .iter()
8839 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8840 .cloned()
8841 .collect()
8842 }
8843}
8844
8845fn diff_hunk_controls(
8846 row: u32,
8847 hunk_range: Range<Anchor>,
8848 line_height: Pixels,
8849 editor: &Entity<Editor>,
8850 cx: &mut App,
8851) -> AnyElement {
8852 h_flex()
8853 .h(line_height)
8854 .mr_1()
8855 .gap_1()
8856 .px_1()
8857 .pb_1()
8858 .border_b_1()
8859 .border_color(cx.theme().colors().border_variant)
8860 .rounded_b_lg()
8861 .bg(cx.theme().colors().editor_background)
8862 .gap_1()
8863 .child(
8864 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
8865 .shape(IconButtonShape::Square)
8866 .icon_size(IconSize::Small)
8867 // .disabled(!has_multiple_hunks)
8868 .tooltip({
8869 let focus_handle = editor.focus_handle(cx);
8870 move |window, cx| {
8871 Tooltip::for_action_in("Next Hunk", &GoToHunk, &focus_handle, window, cx)
8872 }
8873 })
8874 .on_click({
8875 let editor = editor.clone();
8876 move |_event, window, cx| {
8877 editor.update(cx, |editor, cx| {
8878 let snapshot = editor.snapshot(window, cx);
8879 let position = hunk_range.end.to_point(&snapshot.buffer_snapshot);
8880 editor.go_to_hunk_after_position(&snapshot, position, window, cx);
8881 editor.expand_selected_diff_hunks(cx);
8882 });
8883 }
8884 }),
8885 )
8886 .child(
8887 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
8888 .shape(IconButtonShape::Square)
8889 .icon_size(IconSize::Small)
8890 // .disabled(!has_multiple_hunks)
8891 .tooltip({
8892 let focus_handle = editor.focus_handle(cx);
8893 move |window, cx| {
8894 Tooltip::for_action_in(
8895 "Previous Hunk",
8896 &GoToPrevHunk,
8897 &focus_handle,
8898 window,
8899 cx,
8900 )
8901 }
8902 })
8903 .on_click({
8904 let editor = editor.clone();
8905 move |_event, window, cx| {
8906 editor.update(cx, |editor, cx| {
8907 let snapshot = editor.snapshot(window, cx);
8908 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
8909 editor.go_to_hunk_before_position(&snapshot, point, window, cx);
8910 editor.expand_selected_diff_hunks(cx);
8911 });
8912 }
8913 }),
8914 )
8915 .child(
8916 IconButton::new("discard", IconName::Undo)
8917 .shape(IconButtonShape::Square)
8918 .icon_size(IconSize::Small)
8919 .tooltip({
8920 let focus_handle = editor.focus_handle(cx);
8921 move |window, cx| {
8922 Tooltip::for_action_in(
8923 "Discard Hunk",
8924 &RevertSelectedHunks,
8925 &focus_handle,
8926 window,
8927 cx,
8928 )
8929 }
8930 })
8931 .on_click({
8932 let editor = editor.clone();
8933 move |_event, window, cx| {
8934 editor.update(cx, |editor, cx| {
8935 let snapshot = editor.snapshot(window, cx);
8936 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
8937 editor.revert_hunks_in_ranges([point..point].into_iter(), window, cx);
8938 });
8939 }
8940 }),
8941 )
8942 .into_any_element()
8943}