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