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