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