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