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