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
3812 const ACCEPT_INDICATOR_HEIGHT: Pixels = px(24.);
3813
3814 let mut element = v_flex()
3815 .items_end()
3816 .child(
3817 h_flex()
3818 .h(ACCEPT_INDICATOR_HEIGHT)
3819 .mb(px(-1.))
3820 .px_1p5()
3821 .gap_1()
3822 .shadow_sm()
3823 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
3824 .border_1()
3825 .border_b_0()
3826 .border_color(cx.theme().colors().border)
3827 .rounded_t_lg()
3828 .children(editor.render_edit_prediction_accept_keybind(window, cx)),
3829 )
3830 .child(
3831 div()
3832 .bg(cx.theme().colors().editor_background)
3833 .border_1()
3834 .shadow_sm()
3835 .border_color(cx.theme().colors().border)
3836 .rounded_lg()
3837 .rounded_tr(Pixels::ZERO)
3838 .child(styled_text),
3839 )
3840 .into_any();
3841
3842 let line_count = highlighted_edits.text.lines().count();
3843
3844 let longest_row =
3845 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
3846 let longest_line_width = if visible_row_range.contains(&longest_row) {
3847 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
3848 } else {
3849 layout_line(
3850 longest_row,
3851 editor_snapshot,
3852 style,
3853 editor_width,
3854 |_| false,
3855 window,
3856 cx,
3857 )
3858 .width
3859 };
3860
3861 let viewport_bounds = Bounds::new(Default::default(), window.viewport_size())
3862 .extend(Edges {
3863 right: -Self::SCROLLBAR_WIDTH,
3864 ..Default::default()
3865 });
3866
3867 let x_after_longest =
3868 text_bounds.origin.x + longest_line_width + PADDING_X - scroll_pixel_position.x;
3869
3870 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3871
3872 // Fully visible if it can be displayed within the window (allow overlapping other
3873 // panes). However, this is only allowed if the popover starts within text_bounds.
3874 let is_fully_visible = x_after_longest < text_bounds.right()
3875 && x_after_longest + element_bounds.width < viewport_bounds.right();
3876
3877 let mut origin = if is_fully_visible {
3878 point(
3879 x_after_longest,
3880 text_bounds.origin.y + edit_start.row().as_f32() * line_height
3881 - scroll_pixel_position.y,
3882 )
3883 } else {
3884 // Avoid overlapping both the edited rows and the user's cursor.
3885 let target_above = DisplayRow(
3886 edit_start
3887 .row()
3888 .0
3889 .min(
3890 newest_selection_head
3891 .map_or(u32::MAX, |cursor_row| cursor_row.row().0),
3892 )
3893 .saturating_sub(line_count as u32),
3894 );
3895 let mut row_target;
3896 if visible_row_range.contains(&DisplayRow(target_above.0.saturating_sub(1))) {
3897 row_target = target_above;
3898 } else {
3899 row_target = DisplayRow(
3900 edit_end.row().0.max(
3901 newest_selection_head.map_or(0, |cursor_row| cursor_row.row().0),
3902 ) + 1,
3903 );
3904 if !visible_row_range.contains(&row_target) {
3905 // Not visible, so fallback on displaying immediately below the cursor.
3906 if let Some(cursor) = newest_selection_head {
3907 row_target = DisplayRow(cursor.row().0 + 1);
3908 } else {
3909 // Not visible and no cursor visible, so fallback on displaying at the top of the editor.
3910 row_target = DisplayRow(0);
3911 }
3912 }
3913 };
3914
3915 text_bounds.origin
3916 + point(
3917 -scroll_pixel_position.x,
3918 row_target.as_f32() * line_height - scroll_pixel_position.y,
3919 )
3920 };
3921
3922 origin.y -= ACCEPT_INDICATOR_HEIGHT;
3923
3924 window.defer_draw(element, origin, 1);
3925
3926 // Do not return an element, since it will already be drawn due to defer_draw.
3927 None
3928 }
3929 }
3930 }
3931
3932 fn layout_mouse_context_menu(
3933 &self,
3934 editor_snapshot: &EditorSnapshot,
3935 visible_range: Range<DisplayRow>,
3936 content_origin: gpui::Point<Pixels>,
3937 window: &mut Window,
3938 cx: &mut App,
3939 ) -> Option<AnyElement> {
3940 let position = self.editor.update(cx, |editor, _cx| {
3941 let visible_start_point = editor.display_to_pixel_point(
3942 DisplayPoint::new(visible_range.start, 0),
3943 editor_snapshot,
3944 window,
3945 )?;
3946 let visible_end_point = editor.display_to_pixel_point(
3947 DisplayPoint::new(visible_range.end, 0),
3948 editor_snapshot,
3949 window,
3950 )?;
3951
3952 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3953 let (source_display_point, position) = match mouse_context_menu.position {
3954 MenuPosition::PinnedToScreen(point) => (None, point),
3955 MenuPosition::PinnedToEditor { source, offset } => {
3956 let source_display_point = source.to_display_point(editor_snapshot);
3957 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3958 let position = content_origin + source_point + offset;
3959 (Some(source_display_point), position)
3960 }
3961 };
3962
3963 let source_included = source_display_point.map_or(true, |source_display_point| {
3964 visible_range
3965 .to_inclusive()
3966 .contains(&source_display_point.row())
3967 });
3968 let position_included =
3969 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3970 if !source_included && !position_included {
3971 None
3972 } else {
3973 Some(position)
3974 }
3975 })?;
3976
3977 let mut element = self.editor.update(cx, |editor, _| {
3978 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3979 let context_menu = mouse_context_menu.context_menu.clone();
3980
3981 Some(
3982 deferred(
3983 anchored()
3984 .position(position)
3985 .child(context_menu)
3986 .anchor(Corner::TopLeft)
3987 .snap_to_window_with_margin(px(8.)),
3988 )
3989 .with_priority(1)
3990 .into_any(),
3991 )
3992 })?;
3993
3994 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3995 Some(element)
3996 }
3997
3998 #[allow(clippy::too_many_arguments)]
3999 fn layout_hover_popovers(
4000 &self,
4001 snapshot: &EditorSnapshot,
4002 hitbox: &Hitbox,
4003 text_hitbox: &Hitbox,
4004 visible_display_row_range: Range<DisplayRow>,
4005 content_origin: gpui::Point<Pixels>,
4006 scroll_pixel_position: gpui::Point<Pixels>,
4007 line_layouts: &[LineWithInvisibles],
4008 line_height: Pixels,
4009 em_width: Pixels,
4010 window: &mut Window,
4011 cx: &mut App,
4012 ) {
4013 struct MeasuredHoverPopover {
4014 element: AnyElement,
4015 size: Size<Pixels>,
4016 horizontal_offset: Pixels,
4017 }
4018
4019 let max_size = size(
4020 (120. * em_width) // Default size
4021 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4022 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4023 (16. * line_height) // Default size
4024 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4025 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4026 );
4027
4028 let hover_popovers = self.editor.update(cx, |editor, cx| {
4029 editor
4030 .hover_state
4031 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
4032 });
4033 let Some((position, hover_popovers)) = hover_popovers else {
4034 return;
4035 };
4036
4037 // This is safe because we check on layout whether the required row is available
4038 let hovered_row_layout =
4039 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
4040
4041 // Compute Hovered Point
4042 let x =
4043 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
4044 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
4045 let hovered_point = content_origin + point(x, y);
4046
4047 let mut overall_height = Pixels::ZERO;
4048 let mut measured_hover_popovers = Vec::new();
4049 for mut hover_popover in hover_popovers {
4050 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
4051 let horizontal_offset =
4052 (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
4053
4054 overall_height += HOVER_POPOVER_GAP + size.height;
4055
4056 measured_hover_popovers.push(MeasuredHoverPopover {
4057 element: hover_popover,
4058 size,
4059 horizontal_offset,
4060 });
4061 }
4062 overall_height += HOVER_POPOVER_GAP;
4063
4064 fn draw_occluder(
4065 width: Pixels,
4066 origin: gpui::Point<Pixels>,
4067 window: &mut Window,
4068 cx: &mut App,
4069 ) {
4070 let mut occlusion = div()
4071 .size_full()
4072 .occlude()
4073 .on_mouse_move(|_, _, cx| cx.stop_propagation())
4074 .into_any_element();
4075 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4076 window.defer_draw(occlusion, origin, 2);
4077 }
4078
4079 if hovered_point.y > overall_height {
4080 // There is enough space above. Render popovers above the hovered point
4081 let mut current_y = hovered_point.y;
4082 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4083 let size = popover.size;
4084 let popover_origin = point(
4085 hovered_point.x + popover.horizontal_offset,
4086 current_y - size.height,
4087 );
4088
4089 window.defer_draw(popover.element, popover_origin, 2);
4090 if position != itertools::Position::Last {
4091 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4092 draw_occluder(size.width, origin, window, cx);
4093 }
4094
4095 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4096 }
4097 } else {
4098 // There is not enough space above. Render popovers below the hovered point
4099 let mut current_y = hovered_point.y + line_height;
4100 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4101 let size = popover.size;
4102 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4103
4104 window.defer_draw(popover.element, popover_origin, 2);
4105 if position != itertools::Position::Last {
4106 let origin = point(popover_origin.x, popover_origin.y + size.height);
4107 draw_occluder(size.width, origin, window, cx);
4108 }
4109
4110 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4111 }
4112 }
4113 }
4114
4115 #[allow(clippy::too_many_arguments)]
4116 fn layout_diff_hunk_controls(
4117 &self,
4118 row_range: Range<DisplayRow>,
4119 row_infos: &[RowInfo],
4120 text_hitbox: &Hitbox,
4121 position_map: &PositionMap,
4122 newest_cursor_position: Option<DisplayPoint>,
4123 line_height: Pixels,
4124 scroll_pixel_position: gpui::Point<Pixels>,
4125 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4126 editor: Entity<Editor>,
4127 window: &mut Window,
4128 cx: &mut App,
4129 ) -> Vec<AnyElement> {
4130 let point_for_position = position_map.point_for_position(window.mouse_position());
4131
4132 let mut controls = vec![];
4133
4134 let active_positions = [
4135 Some(point_for_position.previous_valid),
4136 newest_cursor_position,
4137 ];
4138
4139 for (hunk, _) in display_hunks {
4140 if let DisplayDiffHunk::Unfolded {
4141 display_row_range,
4142 multi_buffer_range,
4143 status,
4144 ..
4145 } = &hunk
4146 {
4147 if display_row_range.start < row_range.start
4148 || display_row_range.start >= row_range.end
4149 {
4150 continue;
4151 }
4152 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4153 if row_infos[row_ix].diff_status.is_none() {
4154 continue;
4155 }
4156 if matches!(
4157 row_infos[row_ix].diff_status,
4158 Some(DiffHunkStatus::Added(_))
4159 ) && !matches!(*status, DiffHunkStatus::Added(_))
4160 {
4161 continue;
4162 }
4163 if active_positions
4164 .iter()
4165 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4166 {
4167 let y = display_row_range.start.as_f32() * line_height
4168 + text_hitbox.bounds.top()
4169 - scroll_pixel_position.y;
4170 let x = text_hitbox.bounds.right() - px(100.);
4171
4172 let mut element = diff_hunk_controls(
4173 display_row_range.start.0,
4174 multi_buffer_range.clone(),
4175 line_height,
4176 &editor,
4177 cx,
4178 );
4179 element.prepaint_as_root(
4180 gpui::Point::new(x, y),
4181 size(px(100.0), line_height).into(),
4182 window,
4183 cx,
4184 );
4185 controls.push(element);
4186 }
4187 }
4188 }
4189
4190 controls
4191 }
4192
4193 #[allow(clippy::too_many_arguments)]
4194 fn layout_signature_help(
4195 &self,
4196 hitbox: &Hitbox,
4197 content_origin: gpui::Point<Pixels>,
4198 scroll_pixel_position: gpui::Point<Pixels>,
4199 newest_selection_head: Option<DisplayPoint>,
4200 start_row: DisplayRow,
4201 line_layouts: &[LineWithInvisibles],
4202 line_height: Pixels,
4203 em_width: Pixels,
4204 window: &mut Window,
4205 cx: &mut App,
4206 ) {
4207 if !self.editor.focus_handle(cx).is_focused(window) {
4208 return;
4209 }
4210 let Some(newest_selection_head) = newest_selection_head else {
4211 return;
4212 };
4213 let selection_row = newest_selection_head.row();
4214 if selection_row < start_row {
4215 return;
4216 }
4217 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4218 else {
4219 return;
4220 };
4221
4222 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4223 - scroll_pixel_position.x
4224 + content_origin.x;
4225 let start_y =
4226 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4227
4228 let max_size = size(
4229 (120. * em_width) // Default size
4230 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4231 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4232 (16. * line_height) // Default size
4233 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4234 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4235 );
4236
4237 let maybe_element = self.editor.update(cx, |editor, cx| {
4238 if let Some(popover) = editor.signature_help_state.popover_mut() {
4239 let element = popover.render(
4240 &self.style,
4241 max_size,
4242 editor.workspace.as_ref().map(|(w, _)| w.clone()),
4243 cx,
4244 );
4245 Some(element)
4246 } else {
4247 None
4248 }
4249 });
4250 if let Some(mut element) = maybe_element {
4251 let window_size = window.viewport_size();
4252 let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4253 let mut point = point(start_x, start_y - size.height);
4254
4255 // Adjusting to ensure the popover does not overflow in the X-axis direction.
4256 if point.x + size.width >= window_size.width {
4257 point.x = window_size.width - size.width;
4258 }
4259
4260 window.defer_draw(element, point, 1)
4261 }
4262 }
4263
4264 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4265 window.paint_layer(layout.hitbox.bounds, |window| {
4266 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4267 let gutter_bg = cx.theme().colors().editor_gutter_background;
4268 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4269 window.paint_quad(fill(
4270 layout.position_map.text_hitbox.bounds,
4271 self.style.background,
4272 ));
4273
4274 if let EditorMode::Full = layout.mode {
4275 let mut active_rows = layout.active_rows.iter().peekable();
4276 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4277 let mut end_row = start_row.0;
4278 while active_rows
4279 .peek()
4280 .map_or(false, |(active_row, has_selection)| {
4281 active_row.0 == end_row + 1
4282 && *has_selection == contains_non_empty_selection
4283 })
4284 {
4285 active_rows.next().unwrap();
4286 end_row += 1;
4287 }
4288
4289 if !contains_non_empty_selection {
4290 let highlight_h_range =
4291 match layout.position_map.snapshot.current_line_highlight {
4292 CurrentLineHighlight::Gutter => Some(Range {
4293 start: layout.hitbox.left(),
4294 end: layout.gutter_hitbox.right(),
4295 }),
4296 CurrentLineHighlight::Line => Some(Range {
4297 start: layout.position_map.text_hitbox.bounds.left(),
4298 end: layout.position_map.text_hitbox.bounds.right(),
4299 }),
4300 CurrentLineHighlight::All => Some(Range {
4301 start: layout.hitbox.left(),
4302 end: layout.hitbox.right(),
4303 }),
4304 CurrentLineHighlight::None => None,
4305 };
4306 if let Some(range) = highlight_h_range {
4307 let active_line_bg = cx.theme().colors().editor_active_line_background;
4308 let bounds = Bounds {
4309 origin: point(
4310 range.start,
4311 layout.hitbox.origin.y
4312 + (start_row.as_f32() - scroll_top)
4313 * layout.position_map.line_height,
4314 ),
4315 size: size(
4316 range.end - range.start,
4317 layout.position_map.line_height
4318 * (end_row - start_row.0 + 1) as f32,
4319 ),
4320 };
4321 window.paint_quad(fill(bounds, active_line_bg));
4322 }
4323 }
4324 }
4325
4326 let mut paint_highlight =
4327 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4328 let origin = point(
4329 layout.hitbox.origin.x,
4330 layout.hitbox.origin.y
4331 + (highlight_row_start.as_f32() - scroll_top)
4332 * layout.position_map.line_height,
4333 );
4334 let size = size(
4335 layout.hitbox.size.width,
4336 layout.position_map.line_height
4337 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4338 );
4339 window.paint_quad(fill(Bounds { origin, size }, color));
4340 };
4341
4342 let mut current_paint: Option<(gpui::Background, Range<DisplayRow>)> = None;
4343 for (&new_row, &new_background) in &layout.highlighted_rows {
4344 match &mut current_paint {
4345 Some((current_background, current_range)) => {
4346 let current_background = *current_background;
4347 let new_range_started = current_background != new_background
4348 || current_range.end.next_row() != new_row;
4349 if new_range_started {
4350 paint_highlight(
4351 current_range.start,
4352 current_range.end,
4353 current_background,
4354 );
4355 current_paint = Some((new_background, new_row..new_row));
4356 continue;
4357 } else {
4358 current_range.end = current_range.end.next_row();
4359 }
4360 }
4361 None => current_paint = Some((new_background, new_row..new_row)),
4362 };
4363 }
4364 if let Some((color, range)) = current_paint {
4365 paint_highlight(range.start, range.end, color);
4366 }
4367
4368 let scroll_left =
4369 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4370
4371 for (wrap_position, active) in layout.wrap_guides.iter() {
4372 let x = (layout.position_map.text_hitbox.origin.x
4373 + *wrap_position
4374 + layout.position_map.em_width / 2.)
4375 - scroll_left;
4376
4377 let show_scrollbars = {
4378 let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4379
4380 scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4381 || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4382 };
4383
4384 if x < layout.position_map.text_hitbox.origin.x
4385 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4386 {
4387 continue;
4388 }
4389
4390 let color = if *active {
4391 cx.theme().colors().editor_active_wrap_guide
4392 } else {
4393 cx.theme().colors().editor_wrap_guide
4394 };
4395 window.paint_quad(fill(
4396 Bounds {
4397 origin: point(x, layout.position_map.text_hitbox.origin.y),
4398 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4399 },
4400 color,
4401 ));
4402 }
4403 }
4404 })
4405 }
4406
4407 fn paint_indent_guides(
4408 &mut self,
4409 layout: &mut EditorLayout,
4410 window: &mut Window,
4411 cx: &mut App,
4412 ) {
4413 let Some(indent_guides) = &layout.indent_guides else {
4414 return;
4415 };
4416
4417 let faded_color = |color: Hsla, alpha: f32| {
4418 let mut faded = color;
4419 faded.a = alpha;
4420 faded
4421 };
4422
4423 for indent_guide in indent_guides {
4424 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4425 let settings = indent_guide.settings;
4426
4427 // TODO fixed for now, expose them through themes later
4428 const INDENT_AWARE_ALPHA: f32 = 0.2;
4429 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4430 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4431 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4432
4433 let line_color = match (settings.coloring, indent_guide.active) {
4434 (IndentGuideColoring::Disabled, _) => None,
4435 (IndentGuideColoring::Fixed, false) => {
4436 Some(cx.theme().colors().editor_indent_guide)
4437 }
4438 (IndentGuideColoring::Fixed, true) => {
4439 Some(cx.theme().colors().editor_indent_guide_active)
4440 }
4441 (IndentGuideColoring::IndentAware, false) => {
4442 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4443 }
4444 (IndentGuideColoring::IndentAware, true) => {
4445 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4446 }
4447 };
4448
4449 let background_color = match (settings.background_coloring, indent_guide.active) {
4450 (IndentGuideBackgroundColoring::Disabled, _) => None,
4451 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4452 indent_accent_colors,
4453 INDENT_AWARE_BACKGROUND_ALPHA,
4454 )),
4455 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4456 indent_accent_colors,
4457 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4458 )),
4459 };
4460
4461 let requested_line_width = if indent_guide.active {
4462 settings.active_line_width
4463 } else {
4464 settings.line_width
4465 }
4466 .clamp(1, 10);
4467 let mut line_indicator_width = 0.;
4468 if let Some(color) = line_color {
4469 window.paint_quad(fill(
4470 Bounds {
4471 origin: indent_guide.origin,
4472 size: size(px(requested_line_width as f32), indent_guide.length),
4473 },
4474 color,
4475 ));
4476 line_indicator_width = requested_line_width as f32;
4477 }
4478
4479 if let Some(color) = background_color {
4480 let width = indent_guide.single_indent_width - px(line_indicator_width);
4481 window.paint_quad(fill(
4482 Bounds {
4483 origin: point(
4484 indent_guide.origin.x + px(line_indicator_width),
4485 indent_guide.origin.y,
4486 ),
4487 size: size(width, indent_guide.length),
4488 },
4489 color,
4490 ));
4491 }
4492 }
4493 }
4494
4495 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4496 let is_singleton = self.editor.read(cx).is_singleton(cx);
4497
4498 let line_height = layout.position_map.line_height;
4499 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4500
4501 for LineNumberLayout {
4502 shaped_line,
4503 hitbox,
4504 display_row,
4505 } in layout.line_numbers.values()
4506 {
4507 let Some(hitbox) = hitbox else {
4508 continue;
4509 };
4510
4511 let is_active = layout.active_rows.contains_key(&display_row);
4512
4513 let color = if is_active {
4514 cx.theme().colors().editor_active_line_number
4515 } else if !is_singleton && hitbox.is_hovered(window) {
4516 cx.theme().colors().editor_hover_line_number
4517 } else {
4518 cx.theme().colors().editor_line_number
4519 };
4520
4521 let Some(line) = self
4522 .shape_line_number(shaped_line.text.clone(), color, window)
4523 .log_err()
4524 else {
4525 continue;
4526 };
4527 let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4528 continue;
4529 };
4530 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4531 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4532 if is_singleton {
4533 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4534 } else {
4535 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4536 }
4537 }
4538 }
4539
4540 fn paint_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4541 if layout.display_hunks.is_empty() {
4542 return;
4543 }
4544
4545 let line_height = layout.position_map.line_height;
4546 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4547 for (hunk, hitbox) in &layout.display_hunks {
4548 let hunk_to_paint = match hunk {
4549 DisplayDiffHunk::Folded { .. } => {
4550 let hunk_bounds = Self::diff_hunk_bounds(
4551 &layout.position_map.snapshot,
4552 line_height,
4553 layout.gutter_hitbox.bounds,
4554 hunk,
4555 );
4556 Some((
4557 hunk_bounds,
4558 cx.theme().status().modified,
4559 Corners::all(px(0.)),
4560 &DiffHunkSecondaryStatus::None,
4561 ))
4562 }
4563 DisplayDiffHunk::Unfolded {
4564 status,
4565 display_row_range,
4566 ..
4567 } => hitbox.as_ref().map(|hunk_hitbox| match status {
4568 DiffHunkStatus::Added(secondary_status) => (
4569 hunk_hitbox.bounds,
4570 cx.theme().status().created,
4571 Corners::all(px(0.)),
4572 secondary_status,
4573 ),
4574 DiffHunkStatus::Modified(secondary_status) => (
4575 hunk_hitbox.bounds,
4576 cx.theme().status().modified,
4577 Corners::all(px(0.)),
4578 secondary_status,
4579 ),
4580 DiffHunkStatus::Removed(secondary_status)
4581 if !display_row_range.is_empty() =>
4582 {
4583 (
4584 hunk_hitbox.bounds,
4585 cx.theme().status().deleted,
4586 Corners::all(px(0.)),
4587 secondary_status,
4588 )
4589 }
4590 DiffHunkStatus::Removed(secondary_status) => (
4591 Bounds::new(
4592 point(
4593 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4594 hunk_hitbox.origin.y,
4595 ),
4596 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4597 ),
4598 cx.theme().status().deleted,
4599 Corners::all(1. * line_height),
4600 secondary_status,
4601 ),
4602 }),
4603 };
4604
4605 if let Some((hunk_bounds, mut background_color, corner_radii, secondary_status)) =
4606 hunk_to_paint
4607 {
4608 if *secondary_status != DiffHunkSecondaryStatus::None {
4609 background_color.a *= 0.6;
4610 }
4611 window.paint_quad(quad(
4612 hunk_bounds,
4613 corner_radii,
4614 background_color,
4615 Edges::default(),
4616 transparent_black(),
4617 ));
4618 }
4619 }
4620 });
4621 }
4622
4623 fn diff_hunk_bounds(
4624 snapshot: &EditorSnapshot,
4625 line_height: Pixels,
4626 gutter_bounds: Bounds<Pixels>,
4627 hunk: &DisplayDiffHunk,
4628 ) -> Bounds<Pixels> {
4629 let scroll_position = snapshot.scroll_position();
4630 let scroll_top = scroll_position.y * line_height;
4631 let gutter_strip_width = (0.275 * line_height).floor();
4632
4633 match hunk {
4634 DisplayDiffHunk::Folded { display_row, .. } => {
4635 let start_y = display_row.as_f32() * line_height - scroll_top;
4636 let end_y = start_y + line_height;
4637 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4638 let highlight_size = size(gutter_strip_width, end_y - start_y);
4639 Bounds::new(highlight_origin, highlight_size)
4640 }
4641 DisplayDiffHunk::Unfolded {
4642 display_row_range,
4643 status,
4644 ..
4645 } => {
4646 if status.is_removed() && display_row_range.is_empty() {
4647 let row = display_row_range.start;
4648
4649 let offset = line_height / 2.;
4650 let start_y = row.as_f32() * line_height - offset - scroll_top;
4651 let end_y = start_y + line_height;
4652
4653 let width = (0.35 * line_height).floor();
4654 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4655 let highlight_size = size(width, end_y - start_y);
4656 Bounds::new(highlight_origin, highlight_size)
4657 } else {
4658 let start_row = display_row_range.start;
4659 let end_row = display_row_range.end;
4660 // If we're in a multibuffer, row range span might include an
4661 // excerpt header, so if we were to draw the marker straight away,
4662 // the hunk might include the rows of that header.
4663 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4664 // Instead, we simply check whether the range we're dealing with includes
4665 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4666 let end_row_in_current_excerpt = snapshot
4667 .blocks_in_range(start_row..end_row)
4668 .find_map(|(start_row, block)| {
4669 if matches!(block, Block::ExcerptBoundary { .. }) {
4670 Some(start_row)
4671 } else {
4672 None
4673 }
4674 })
4675 .unwrap_or(end_row);
4676
4677 let start_y = start_row.as_f32() * line_height - scroll_top;
4678 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4679
4680 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4681 let highlight_size = size(gutter_strip_width, end_y - start_y);
4682 Bounds::new(highlight_origin, highlight_size)
4683 }
4684 }
4685 }
4686 }
4687
4688 fn paint_gutter_indicators(
4689 &self,
4690 layout: &mut EditorLayout,
4691 window: &mut Window,
4692 cx: &mut App,
4693 ) {
4694 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4695 window.with_element_namespace("crease_toggles", |window| {
4696 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4697 crease_toggle.paint(window, cx);
4698 }
4699 });
4700
4701 for test_indicator in layout.test_indicators.iter_mut() {
4702 test_indicator.paint(window, cx);
4703 }
4704
4705 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4706 indicator.paint(window, cx);
4707 }
4708 });
4709 }
4710
4711 fn paint_gutter_highlights(
4712 &self,
4713 layout: &mut EditorLayout,
4714 window: &mut Window,
4715 cx: &mut App,
4716 ) {
4717 for (_, hunk_hitbox) in &layout.display_hunks {
4718 if let Some(hunk_hitbox) = hunk_hitbox {
4719 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4720 }
4721 }
4722
4723 let show_git_gutter = layout
4724 .position_map
4725 .snapshot
4726 .show_git_diff_gutter
4727 .unwrap_or_else(|| {
4728 matches!(
4729 ProjectSettings::get_global(cx).git.git_gutter,
4730 Some(GitGutterSetting::TrackedFiles)
4731 )
4732 });
4733 if show_git_gutter {
4734 Self::paint_diff_hunks(layout, window, cx)
4735 }
4736
4737 let highlight_width = 0.275 * layout.position_map.line_height;
4738 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4739 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4740 for (range, color) in &layout.highlighted_gutter_ranges {
4741 let start_row = if range.start.row() < layout.visible_display_row_range.start {
4742 layout.visible_display_row_range.start - DisplayRow(1)
4743 } else {
4744 range.start.row()
4745 };
4746 let end_row = if range.end.row() > layout.visible_display_row_range.end {
4747 layout.visible_display_row_range.end + DisplayRow(1)
4748 } else {
4749 range.end.row()
4750 };
4751
4752 let start_y = layout.gutter_hitbox.top()
4753 + start_row.0 as f32 * layout.position_map.line_height
4754 - layout.position_map.scroll_pixel_position.y;
4755 let end_y = layout.gutter_hitbox.top()
4756 + (end_row.0 + 1) as f32 * layout.position_map.line_height
4757 - layout.position_map.scroll_pixel_position.y;
4758 let bounds = Bounds::from_corners(
4759 point(layout.gutter_hitbox.left(), start_y),
4760 point(layout.gutter_hitbox.left() + highlight_width, end_y),
4761 );
4762 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4763 }
4764 });
4765 }
4766
4767 fn paint_blamed_display_rows(
4768 &self,
4769 layout: &mut EditorLayout,
4770 window: &mut Window,
4771 cx: &mut App,
4772 ) {
4773 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4774 return;
4775 };
4776
4777 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4778 for mut blame_element in blamed_display_rows.into_iter() {
4779 blame_element.paint(window, cx);
4780 }
4781 })
4782 }
4783
4784 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4785 window.with_content_mask(
4786 Some(ContentMask {
4787 bounds: layout.position_map.text_hitbox.bounds,
4788 }),
4789 |window| {
4790 let cursor_style = if self
4791 .editor
4792 .read(cx)
4793 .hovered_link_state
4794 .as_ref()
4795 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4796 {
4797 CursorStyle::PointingHand
4798 } else {
4799 CursorStyle::IBeam
4800 };
4801 window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4802
4803 let invisible_display_ranges = self.paint_highlights(layout, window);
4804 self.paint_lines(&invisible_display_ranges, layout, window, cx);
4805 self.paint_redactions(layout, window);
4806 self.paint_cursors(layout, window, cx);
4807 self.paint_inline_blame(layout, window, cx);
4808 self.paint_diff_hunk_controls(layout, window, cx);
4809 window.with_element_namespace("crease_trailers", |window| {
4810 for trailer in layout.crease_trailers.iter_mut().flatten() {
4811 trailer.element.paint(window, cx);
4812 }
4813 });
4814 },
4815 )
4816 }
4817
4818 fn paint_highlights(
4819 &mut self,
4820 layout: &mut EditorLayout,
4821 window: &mut Window,
4822 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4823 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4824 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4825 let line_end_overshoot = 0.15 * layout.position_map.line_height;
4826 for (range, color) in &layout.highlighted_ranges {
4827 self.paint_highlighted_range(
4828 range.clone(),
4829 *color,
4830 Pixels::ZERO,
4831 line_end_overshoot,
4832 layout,
4833 window,
4834 );
4835 }
4836
4837 let corner_radius = 0.15 * layout.position_map.line_height;
4838
4839 for (player_color, selections) in &layout.selections {
4840 for selection in selections.iter() {
4841 self.paint_highlighted_range(
4842 selection.range.clone(),
4843 player_color.selection,
4844 corner_radius,
4845 corner_radius * 2.,
4846 layout,
4847 window,
4848 );
4849
4850 if selection.is_local && !selection.range.is_empty() {
4851 invisible_display_ranges.push(selection.range.clone());
4852 }
4853 }
4854 }
4855 invisible_display_ranges
4856 })
4857 }
4858
4859 fn paint_lines(
4860 &mut self,
4861 invisible_display_ranges: &[Range<DisplayPoint>],
4862 layout: &mut EditorLayout,
4863 window: &mut Window,
4864 cx: &mut App,
4865 ) {
4866 let whitespace_setting = self
4867 .editor
4868 .read(cx)
4869 .buffer
4870 .read(cx)
4871 .settings_at(0, cx)
4872 .show_whitespaces;
4873
4874 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4875 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4876 line_with_invisibles.draw(
4877 layout,
4878 row,
4879 layout.content_origin,
4880 whitespace_setting,
4881 invisible_display_ranges,
4882 window,
4883 cx,
4884 )
4885 }
4886
4887 for line_element in &mut layout.line_elements {
4888 line_element.paint(window, cx);
4889 }
4890 }
4891
4892 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4893 if layout.redacted_ranges.is_empty() {
4894 return;
4895 }
4896
4897 let line_end_overshoot = layout.line_end_overshoot();
4898
4899 // A softer than perfect black
4900 let redaction_color = gpui::rgb(0x0e1111);
4901
4902 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4903 for range in layout.redacted_ranges.iter() {
4904 self.paint_highlighted_range(
4905 range.clone(),
4906 redaction_color.into(),
4907 Pixels::ZERO,
4908 line_end_overshoot,
4909 layout,
4910 window,
4911 );
4912 }
4913 });
4914 }
4915
4916 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4917 for cursor in &mut layout.visible_cursors {
4918 cursor.paint(layout.content_origin, window, cx);
4919 }
4920 }
4921
4922 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4923 let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4924
4925 if let Some(scrollbar_layout) = scrollbar_x {
4926 let hitbox = scrollbar_layout.hitbox.clone();
4927 let text_unit_size = scrollbar_layout.text_unit_size;
4928 let visible_range = scrollbar_layout.visible_range.clone();
4929 let thumb_bounds = scrollbar_layout.thumb_bounds();
4930
4931 if scrollbar_layout.visible {
4932 window.paint_layer(hitbox.bounds, |window| {
4933 window.paint_quad(quad(
4934 hitbox.bounds,
4935 Corners::default(),
4936 cx.theme().colors().scrollbar_track_background,
4937 Edges {
4938 top: Pixels::ZERO,
4939 right: Pixels::ZERO,
4940 bottom: Pixels::ZERO,
4941 left: Pixels::ZERO,
4942 },
4943 cx.theme().colors().scrollbar_track_border,
4944 ));
4945
4946 window.paint_quad(quad(
4947 thumb_bounds,
4948 Corners::default(),
4949 cx.theme().colors().scrollbar_thumb_background,
4950 Edges {
4951 top: Pixels::ZERO,
4952 right: Pixels::ZERO,
4953 bottom: Pixels::ZERO,
4954 left: ScrollbarLayout::BORDER_WIDTH,
4955 },
4956 cx.theme().colors().scrollbar_thumb_border,
4957 ));
4958 })
4959 }
4960
4961 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4962
4963 window.on_mouse_event({
4964 let editor = self.editor.clone();
4965
4966 // there may be a way to avoid this clone
4967 let hitbox = hitbox.clone();
4968
4969 let mut mouse_position = window.mouse_position();
4970 move |event: &MouseMoveEvent, phase, window, cx| {
4971 if phase == DispatchPhase::Capture {
4972 return;
4973 }
4974
4975 editor.update(cx, |editor, cx| {
4976 if event.pressed_button == Some(MouseButton::Left)
4977 && editor
4978 .scroll_manager
4979 .is_dragging_scrollbar(Axis::Horizontal)
4980 {
4981 let x = mouse_position.x;
4982 let new_x = event.position.x;
4983 if (hitbox.left()..hitbox.right()).contains(&x) {
4984 let mut position = editor.scroll_position(cx);
4985
4986 position.x += (new_x - x) / text_unit_size;
4987 if position.x < 0.0 {
4988 position.x = 0.0;
4989 }
4990 editor.set_scroll_position(position, window, cx);
4991 }
4992
4993 cx.stop_propagation();
4994 } else {
4995 editor.scroll_manager.set_is_dragging_scrollbar(
4996 Axis::Horizontal,
4997 false,
4998 cx,
4999 );
5000
5001 if hitbox.is_hovered(window) {
5002 editor.scroll_manager.show_scrollbar(window, cx);
5003 }
5004 }
5005 mouse_position = event.position;
5006 })
5007 }
5008 });
5009
5010 if self
5011 .editor
5012 .read(cx)
5013 .scroll_manager
5014 .is_dragging_scrollbar(Axis::Horizontal)
5015 {
5016 window.on_mouse_event({
5017 let editor = self.editor.clone();
5018 move |_: &MouseUpEvent, phase, _, cx| {
5019 if phase == DispatchPhase::Capture {
5020 return;
5021 }
5022
5023 editor.update(cx, |editor, cx| {
5024 editor.scroll_manager.set_is_dragging_scrollbar(
5025 Axis::Horizontal,
5026 false,
5027 cx,
5028 );
5029 cx.stop_propagation();
5030 });
5031 }
5032 });
5033 } else {
5034 window.on_mouse_event({
5035 let editor = self.editor.clone();
5036
5037 move |event: &MouseDownEvent, phase, window, cx| {
5038 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5039 return;
5040 }
5041
5042 editor.update(cx, |editor, cx| {
5043 editor.scroll_manager.set_is_dragging_scrollbar(
5044 Axis::Horizontal,
5045 true,
5046 cx,
5047 );
5048
5049 let x = event.position.x;
5050
5051 if x < thumb_bounds.left() || thumb_bounds.right() < x {
5052 let center_row =
5053 ((x - hitbox.left()) / text_unit_size).round() as u32;
5054 let top_row = center_row.saturating_sub(
5055 (visible_range.end - visible_range.start) as u32 / 2,
5056 );
5057
5058 let mut position = editor.scroll_position(cx);
5059 position.x = top_row as f32;
5060
5061 editor.set_scroll_position(position, window, cx);
5062 } else {
5063 editor.scroll_manager.show_scrollbar(window, cx);
5064 }
5065
5066 cx.stop_propagation();
5067 });
5068 }
5069 });
5070 }
5071 }
5072
5073 if let Some(scrollbar_layout) = scrollbar_y {
5074 let hitbox = scrollbar_layout.hitbox.clone();
5075 let text_unit_size = scrollbar_layout.text_unit_size;
5076 let visible_range = scrollbar_layout.visible_range.clone();
5077 let thumb_bounds = scrollbar_layout.thumb_bounds();
5078
5079 if scrollbar_layout.visible {
5080 window.paint_layer(hitbox.bounds, |window| {
5081 window.paint_quad(quad(
5082 hitbox.bounds,
5083 Corners::default(),
5084 cx.theme().colors().scrollbar_track_background,
5085 Edges {
5086 top: Pixels::ZERO,
5087 right: Pixels::ZERO,
5088 bottom: Pixels::ZERO,
5089 left: ScrollbarLayout::BORDER_WIDTH,
5090 },
5091 cx.theme().colors().scrollbar_track_border,
5092 ));
5093
5094 let fast_markers =
5095 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5096 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5097 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5098
5099 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5100 for marker in markers.iter().chain(&fast_markers) {
5101 let mut marker = marker.clone();
5102 marker.bounds.origin += hitbox.origin;
5103 window.paint_quad(marker);
5104 }
5105
5106 window.paint_quad(quad(
5107 thumb_bounds,
5108 Corners::default(),
5109 cx.theme().colors().scrollbar_thumb_background,
5110 Edges {
5111 top: Pixels::ZERO,
5112 right: Pixels::ZERO,
5113 bottom: Pixels::ZERO,
5114 left: ScrollbarLayout::BORDER_WIDTH,
5115 },
5116 cx.theme().colors().scrollbar_thumb_border,
5117 ));
5118 });
5119 }
5120
5121 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5122
5123 window.on_mouse_event({
5124 let editor = self.editor.clone();
5125
5126 let hitbox = hitbox.clone();
5127
5128 let mut mouse_position = window.mouse_position();
5129 move |event: &MouseMoveEvent, phase, window, cx| {
5130 if phase == DispatchPhase::Capture {
5131 return;
5132 }
5133
5134 editor.update(cx, |editor, cx| {
5135 if event.pressed_button == Some(MouseButton::Left)
5136 && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5137 {
5138 let y = mouse_position.y;
5139 let new_y = event.position.y;
5140 if (hitbox.top()..hitbox.bottom()).contains(&y) {
5141 let mut position = editor.scroll_position(cx);
5142 position.y += (new_y - y) / text_unit_size;
5143 if position.y < 0.0 {
5144 position.y = 0.0;
5145 }
5146 editor.set_scroll_position(position, window, cx);
5147 }
5148 } else {
5149 editor.scroll_manager.set_is_dragging_scrollbar(
5150 Axis::Vertical,
5151 false,
5152 cx,
5153 );
5154
5155 if hitbox.is_hovered(window) {
5156 editor.scroll_manager.show_scrollbar(window, cx);
5157 }
5158 }
5159 mouse_position = event.position;
5160 })
5161 }
5162 });
5163
5164 if self
5165 .editor
5166 .read(cx)
5167 .scroll_manager
5168 .is_dragging_scrollbar(Axis::Vertical)
5169 {
5170 window.on_mouse_event({
5171 let editor = self.editor.clone();
5172 move |_: &MouseUpEvent, phase, _, cx| {
5173 if phase == DispatchPhase::Capture {
5174 return;
5175 }
5176
5177 editor.update(cx, |editor, cx| {
5178 editor.scroll_manager.set_is_dragging_scrollbar(
5179 Axis::Vertical,
5180 false,
5181 cx,
5182 );
5183 cx.stop_propagation();
5184 });
5185 }
5186 });
5187 } else {
5188 window.on_mouse_event({
5189 let editor = self.editor.clone();
5190
5191 move |event: &MouseDownEvent, phase, window, cx| {
5192 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5193 return;
5194 }
5195
5196 editor.update(cx, |editor, cx| {
5197 editor.scroll_manager.set_is_dragging_scrollbar(
5198 Axis::Vertical,
5199 true,
5200 cx,
5201 );
5202
5203 let y = event.position.y;
5204 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5205 let center_row =
5206 ((y - hitbox.top()) / text_unit_size).round() as u32;
5207 let top_row = center_row.saturating_sub(
5208 (visible_range.end - visible_range.start) as u32 / 2,
5209 );
5210 let mut position = editor.scroll_position(cx);
5211 position.y = top_row as f32;
5212 editor.set_scroll_position(position, window, cx);
5213 } else {
5214 editor.scroll_manager.show_scrollbar(window, cx);
5215 }
5216
5217 cx.stop_propagation();
5218 });
5219 }
5220 });
5221 }
5222 }
5223 }
5224
5225 fn collect_fast_scrollbar_markers(
5226 &self,
5227 layout: &EditorLayout,
5228 scrollbar_layout: &ScrollbarLayout,
5229 cx: &mut App,
5230 ) -> Vec<PaintQuad> {
5231 const LIMIT: usize = 100;
5232 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5233 return vec![];
5234 }
5235 let cursor_ranges = layout
5236 .cursors
5237 .iter()
5238 .map(|(point, color)| ColoredRange {
5239 start: point.row(),
5240 end: point.row(),
5241 color: *color,
5242 })
5243 .collect_vec();
5244 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5245 }
5246
5247 fn refresh_slow_scrollbar_markers(
5248 &self,
5249 layout: &EditorLayout,
5250 scrollbar_layout: &ScrollbarLayout,
5251 window: &mut Window,
5252 cx: &mut App,
5253 ) {
5254 self.editor.update(cx, |editor, cx| {
5255 if !editor.is_singleton(cx)
5256 || !editor
5257 .scrollbar_marker_state
5258 .should_refresh(scrollbar_layout.hitbox.size)
5259 {
5260 return;
5261 }
5262
5263 let scrollbar_layout = scrollbar_layout.clone();
5264 let background_highlights = editor.background_highlights.clone();
5265 let snapshot = layout.position_map.snapshot.clone();
5266 let theme = cx.theme().clone();
5267 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5268
5269 editor.scrollbar_marker_state.dirty = false;
5270 editor.scrollbar_marker_state.pending_refresh =
5271 Some(cx.spawn_in(window, |editor, mut cx| async move {
5272 let scrollbar_size = scrollbar_layout.hitbox.size;
5273 let scrollbar_markers = cx
5274 .background_executor()
5275 .spawn(async move {
5276 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5277 let mut marker_quads = Vec::new();
5278 if scrollbar_settings.git_diff {
5279 let marker_row_ranges =
5280 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5281 let start_display_row =
5282 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5283 .to_display_point(&snapshot.display_snapshot)
5284 .row();
5285 let mut end_display_row =
5286 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5287 .to_display_point(&snapshot.display_snapshot)
5288 .row();
5289 if end_display_row != start_display_row {
5290 end_display_row.0 -= 1;
5291 }
5292 let color = match &hunk.status() {
5293 DiffHunkStatus::Added(_) => theme.status().created,
5294 DiffHunkStatus::Modified(_) => theme.status().modified,
5295 DiffHunkStatus::Removed(_) => theme.status().deleted,
5296 };
5297 ColoredRange {
5298 start: start_display_row,
5299 end: end_display_row,
5300 color,
5301 }
5302 });
5303
5304 marker_quads.extend(
5305 scrollbar_layout
5306 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5307 );
5308 }
5309
5310 for (background_highlight_id, (_, background_ranges)) in
5311 background_highlights.iter()
5312 {
5313 let is_search_highlights = *background_highlight_id
5314 == TypeId::of::<BufferSearchHighlights>();
5315 let is_symbol_occurrences = *background_highlight_id
5316 == TypeId::of::<DocumentHighlightRead>()
5317 || *background_highlight_id
5318 == TypeId::of::<DocumentHighlightWrite>();
5319 if (is_search_highlights && scrollbar_settings.search_results)
5320 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5321 {
5322 let mut color = theme.status().info;
5323 if is_symbol_occurrences {
5324 color.fade_out(0.5);
5325 }
5326 let marker_row_ranges = background_ranges.iter().map(|range| {
5327 let display_start = range
5328 .start
5329 .to_display_point(&snapshot.display_snapshot);
5330 let display_end =
5331 range.end.to_display_point(&snapshot.display_snapshot);
5332 ColoredRange {
5333 start: display_start.row(),
5334 end: display_end.row(),
5335 color,
5336 }
5337 });
5338 marker_quads.extend(
5339 scrollbar_layout
5340 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5341 );
5342 }
5343 }
5344
5345 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5346 let diagnostics = snapshot
5347 .buffer_snapshot
5348 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5349 // Don't show diagnostics the user doesn't care about
5350 .filter(|diagnostic| {
5351 match (
5352 scrollbar_settings.diagnostics,
5353 diagnostic.diagnostic.severity,
5354 ) {
5355 (ScrollbarDiagnostics::All, _) => true,
5356 (
5357 ScrollbarDiagnostics::Error,
5358 DiagnosticSeverity::ERROR,
5359 ) => true,
5360 (
5361 ScrollbarDiagnostics::Warning,
5362 DiagnosticSeverity::ERROR
5363 | DiagnosticSeverity::WARNING,
5364 ) => true,
5365 (
5366 ScrollbarDiagnostics::Information,
5367 DiagnosticSeverity::ERROR
5368 | DiagnosticSeverity::WARNING
5369 | DiagnosticSeverity::INFORMATION,
5370 ) => true,
5371 (_, _) => false,
5372 }
5373 })
5374 // We want to sort by severity, in order to paint the most severe diagnostics last.
5375 .sorted_by_key(|diagnostic| {
5376 std::cmp::Reverse(diagnostic.diagnostic.severity)
5377 });
5378
5379 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5380 let start_display = diagnostic
5381 .range
5382 .start
5383 .to_display_point(&snapshot.display_snapshot);
5384 let end_display = diagnostic
5385 .range
5386 .end
5387 .to_display_point(&snapshot.display_snapshot);
5388 let color = match diagnostic.diagnostic.severity {
5389 DiagnosticSeverity::ERROR => theme.status().error,
5390 DiagnosticSeverity::WARNING => theme.status().warning,
5391 DiagnosticSeverity::INFORMATION => theme.status().info,
5392 _ => theme.status().hint,
5393 };
5394 ColoredRange {
5395 start: start_display.row(),
5396 end: end_display.row(),
5397 color,
5398 }
5399 });
5400 marker_quads.extend(
5401 scrollbar_layout
5402 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5403 );
5404 }
5405
5406 Arc::from(marker_quads)
5407 })
5408 .await;
5409
5410 editor.update(&mut cx, |editor, cx| {
5411 editor.scrollbar_marker_state.markers = scrollbar_markers;
5412 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5413 editor.scrollbar_marker_state.pending_refresh = None;
5414 cx.notify();
5415 })?;
5416
5417 Ok(())
5418 }));
5419 });
5420 }
5421
5422 #[allow(clippy::too_many_arguments)]
5423 fn paint_highlighted_range(
5424 &self,
5425 range: Range<DisplayPoint>,
5426 color: Hsla,
5427 corner_radius: Pixels,
5428 line_end_overshoot: Pixels,
5429 layout: &EditorLayout,
5430 window: &mut Window,
5431 ) {
5432 let start_row = layout.visible_display_row_range.start;
5433 let end_row = layout.visible_display_row_range.end;
5434 if range.start != range.end {
5435 let row_range = if range.end.column() == 0 {
5436 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5437 } else {
5438 cmp::max(range.start.row(), start_row)
5439 ..cmp::min(range.end.row().next_row(), end_row)
5440 };
5441
5442 let highlighted_range = HighlightedRange {
5443 color,
5444 line_height: layout.position_map.line_height,
5445 corner_radius,
5446 start_y: layout.content_origin.y
5447 + row_range.start.as_f32() * layout.position_map.line_height
5448 - layout.position_map.scroll_pixel_position.y,
5449 lines: row_range
5450 .iter_rows()
5451 .map(|row| {
5452 let line_layout =
5453 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5454 HighlightedRangeLine {
5455 start_x: if row == range.start.row() {
5456 layout.content_origin.x
5457 + line_layout.x_for_index(range.start.column() as usize)
5458 - layout.position_map.scroll_pixel_position.x
5459 } else {
5460 layout.content_origin.x
5461 - layout.position_map.scroll_pixel_position.x
5462 },
5463 end_x: if row == range.end.row() {
5464 layout.content_origin.x
5465 + line_layout.x_for_index(range.end.column() as usize)
5466 - layout.position_map.scroll_pixel_position.x
5467 } else {
5468 layout.content_origin.x + line_layout.width + line_end_overshoot
5469 - layout.position_map.scroll_pixel_position.x
5470 },
5471 }
5472 })
5473 .collect(),
5474 };
5475
5476 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5477 }
5478 }
5479
5480 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5481 if let Some(mut inline_blame) = layout.inline_blame.take() {
5482 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5483 inline_blame.paint(window, cx);
5484 })
5485 }
5486 }
5487
5488 fn paint_diff_hunk_controls(
5489 &mut self,
5490 layout: &mut EditorLayout,
5491 window: &mut Window,
5492 cx: &mut App,
5493 ) {
5494 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5495 diff_hunk_control.paint(window, cx);
5496 }
5497 }
5498
5499 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5500 for mut block in layout.blocks.drain(..) {
5501 block.element.paint(window, cx);
5502 }
5503 }
5504
5505 fn paint_inline_completion_popover(
5506 &mut self,
5507 layout: &mut EditorLayout,
5508 window: &mut Window,
5509 cx: &mut App,
5510 ) {
5511 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5512 inline_completion_popover.paint(window, cx);
5513 }
5514 }
5515
5516 fn paint_mouse_context_menu(
5517 &mut self,
5518 layout: &mut EditorLayout,
5519 window: &mut Window,
5520 cx: &mut App,
5521 ) {
5522 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5523 mouse_context_menu.paint(window, cx);
5524 }
5525 }
5526
5527 fn paint_scroll_wheel_listener(
5528 &mut self,
5529 layout: &EditorLayout,
5530 window: &mut Window,
5531 cx: &mut App,
5532 ) {
5533 window.on_mouse_event({
5534 let position_map = layout.position_map.clone();
5535 let editor = self.editor.clone();
5536 let hitbox = layout.hitbox.clone();
5537 let mut delta = ScrollDelta::default();
5538
5539 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5540 // accidentally turn off their scrolling.
5541 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5542
5543 move |event: &ScrollWheelEvent, phase, window, cx| {
5544 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5545 delta = delta.coalesce(event.delta);
5546 editor.update(cx, |editor, cx| {
5547 let position_map: &PositionMap = &position_map;
5548
5549 let line_height = position_map.line_height;
5550 let max_glyph_width = position_map.em_width;
5551 let (delta, axis) = match delta {
5552 gpui::ScrollDelta::Pixels(mut pixels) => {
5553 //Trackpad
5554 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5555 (pixels, axis)
5556 }
5557
5558 gpui::ScrollDelta::Lines(lines) => {
5559 //Not trackpad
5560 let pixels =
5561 point(lines.x * max_glyph_width, lines.y * line_height);
5562 (pixels, None)
5563 }
5564 };
5565
5566 let current_scroll_position = position_map.snapshot.scroll_position();
5567 let x = (current_scroll_position.x * max_glyph_width
5568 - (delta.x * scroll_sensitivity))
5569 / max_glyph_width;
5570 let y = (current_scroll_position.y * line_height
5571 - (delta.y * scroll_sensitivity))
5572 / line_height;
5573 let mut scroll_position =
5574 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5575 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5576 if forbid_vertical_scroll {
5577 scroll_position.y = current_scroll_position.y;
5578 }
5579
5580 if scroll_position != current_scroll_position {
5581 editor.scroll(scroll_position, axis, window, cx);
5582 cx.stop_propagation();
5583 } else if y < 0. {
5584 // Due to clamping, we may fail to detect cases of overscroll to the top;
5585 // We want the scroll manager to get an update in such cases and detect the change of direction
5586 // on the next frame.
5587 cx.notify();
5588 }
5589 });
5590 }
5591 }
5592 });
5593 }
5594
5595 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5596 self.paint_scroll_wheel_listener(layout, window, cx);
5597
5598 window.on_mouse_event({
5599 let position_map = layout.position_map.clone();
5600 let editor = self.editor.clone();
5601 let multi_buffer_range =
5602 layout
5603 .display_hunks
5604 .iter()
5605 .find_map(|(hunk, hunk_hitbox)| match hunk {
5606 DisplayDiffHunk::Folded { .. } => None,
5607 DisplayDiffHunk::Unfolded {
5608 multi_buffer_range, ..
5609 } => {
5610 if hunk_hitbox
5611 .as_ref()
5612 .map(|hitbox| hitbox.is_hovered(window))
5613 .unwrap_or(false)
5614 {
5615 Some(multi_buffer_range.clone())
5616 } else {
5617 None
5618 }
5619 }
5620 });
5621 let line_numbers = layout.line_numbers.clone();
5622
5623 move |event: &MouseDownEvent, phase, window, cx| {
5624 if phase == DispatchPhase::Bubble {
5625 match event.button {
5626 MouseButton::Left => editor.update(cx, |editor, cx| {
5627 let pending_mouse_down = editor
5628 .pending_mouse_down
5629 .get_or_insert_with(Default::default)
5630 .clone();
5631
5632 *pending_mouse_down.borrow_mut() = Some(event.clone());
5633
5634 Self::mouse_left_down(
5635 editor,
5636 event,
5637 multi_buffer_range.clone(),
5638 &position_map,
5639 line_numbers.as_ref(),
5640 window,
5641 cx,
5642 );
5643 }),
5644 MouseButton::Right => editor.update(cx, |editor, cx| {
5645 Self::mouse_right_down(editor, event, &position_map, window, cx);
5646 }),
5647 MouseButton::Middle => editor.update(cx, |editor, cx| {
5648 Self::mouse_middle_down(editor, event, &position_map, window, cx);
5649 }),
5650 _ => {}
5651 };
5652 }
5653 }
5654 });
5655
5656 window.on_mouse_event({
5657 let editor = self.editor.clone();
5658 let position_map = layout.position_map.clone();
5659
5660 move |event: &MouseUpEvent, phase, window, cx| {
5661 if phase == DispatchPhase::Bubble {
5662 editor.update(cx, |editor, cx| {
5663 Self::mouse_up(editor, event, &position_map, window, cx)
5664 });
5665 }
5666 }
5667 });
5668
5669 window.on_mouse_event({
5670 let editor = self.editor.clone();
5671 let position_map = layout.position_map.clone();
5672 let mut captured_mouse_down = None;
5673
5674 move |event: &MouseUpEvent, phase, window, cx| match phase {
5675 // Clear the pending mouse down during the capture phase,
5676 // so that it happens even if another event handler stops
5677 // propagation.
5678 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5679 let pending_mouse_down = editor
5680 .pending_mouse_down
5681 .get_or_insert_with(Default::default)
5682 .clone();
5683
5684 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5685 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5686 captured_mouse_down = pending_mouse_down.take();
5687 window.refresh();
5688 }
5689 }),
5690 // Fire click handlers during the bubble phase.
5691 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5692 if let Some(mouse_down) = captured_mouse_down.take() {
5693 let event = ClickEvent {
5694 down: mouse_down,
5695 up: event.clone(),
5696 };
5697 Self::click(editor, &event, &position_map, window, cx);
5698 }
5699 }),
5700 }
5701 });
5702
5703 window.on_mouse_event({
5704 let position_map = layout.position_map.clone();
5705 let editor = self.editor.clone();
5706
5707 move |event: &MouseMoveEvent, phase, window, cx| {
5708 if phase == DispatchPhase::Bubble {
5709 editor.update(cx, |editor, cx| {
5710 if editor.hover_state.focused(window, cx) {
5711 return;
5712 }
5713 if event.pressed_button == Some(MouseButton::Left)
5714 || event.pressed_button == Some(MouseButton::Middle)
5715 {
5716 Self::mouse_dragged(editor, event, &position_map, window, cx)
5717 }
5718
5719 Self::mouse_moved(editor, event, &position_map, window, cx)
5720 });
5721 }
5722 }
5723 });
5724 }
5725
5726 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5727 bounds.top_right().x - self.style.scrollbar_width
5728 }
5729
5730 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5731 let style = &self.style;
5732 let font_size = style.text.font_size.to_pixels(window.rem_size());
5733 let layout = window
5734 .text_system()
5735 .shape_line(
5736 SharedString::from(" ".repeat(column)),
5737 font_size,
5738 &[TextRun {
5739 len: column,
5740 font: style.text.font(),
5741 color: Hsla::default(),
5742 background_color: None,
5743 underline: None,
5744 strikethrough: None,
5745 }],
5746 )
5747 .unwrap();
5748
5749 layout.width
5750 }
5751
5752 fn max_line_number_width(
5753 &self,
5754 snapshot: &EditorSnapshot,
5755 window: &mut Window,
5756 cx: &mut App,
5757 ) -> Pixels {
5758 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5759 self.column_pixels(digit_count, window, cx)
5760 }
5761
5762 fn shape_line_number(
5763 &self,
5764 text: SharedString,
5765 color: Hsla,
5766 window: &mut Window,
5767 ) -> anyhow::Result<ShapedLine> {
5768 let run = TextRun {
5769 len: text.len(),
5770 font: self.style.text.font(),
5771 color,
5772 background_color: None,
5773 underline: None,
5774 strikethrough: None,
5775 };
5776 window.text_system().shape_line(
5777 text,
5778 self.style.text.font_size.to_pixels(window.rem_size()),
5779 &[run],
5780 )
5781 }
5782}
5783
5784fn header_jump_data(
5785 snapshot: &EditorSnapshot,
5786 block_row_start: DisplayRow,
5787 height: u32,
5788 for_excerpt: &ExcerptInfo,
5789) -> JumpData {
5790 let range = &for_excerpt.range;
5791 let buffer = &for_excerpt.buffer;
5792 let jump_anchor = range
5793 .primary
5794 .as_ref()
5795 .map_or(range.context.start, |primary| primary.start);
5796
5797 let excerpt_start = range.context.start;
5798 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5799 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5800 0
5801 } else {
5802 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5803 jump_position.row.saturating_sub(excerpt_start_point.row)
5804 };
5805
5806 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5807 .saturating_sub(
5808 snapshot
5809 .scroll_anchor
5810 .scroll_position(&snapshot.display_snapshot)
5811 .y as u32,
5812 );
5813
5814 JumpData::MultiBufferPoint {
5815 excerpt_id: for_excerpt.id,
5816 anchor: jump_anchor,
5817 position: jump_position,
5818 line_offset_from_top,
5819 }
5820}
5821
5822pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5823
5824impl AcceptEditPredictionBinding {
5825 pub fn keystroke(&self) -> Option<&Keystroke> {
5826 if let Some(binding) = self.0.as_ref() {
5827 match &binding.keystrokes() {
5828 [keystroke] => Some(keystroke),
5829 _ => None,
5830 }
5831 } else {
5832 None
5833 }
5834 }
5835}
5836
5837struct AcceptEditPredictionsBindingValidator;
5838
5839inventory::submit! { KeyBindingValidatorRegistration(|| Box::new(AcceptEditPredictionsBindingValidator)) }
5840
5841impl KeyBindingValidator for AcceptEditPredictionsBindingValidator {
5842 fn action_type_id(&self) -> TypeId {
5843 TypeId::of::<AcceptEditPrediction>()
5844 }
5845
5846 fn validate(&self, binding: &gpui::KeyBinding) -> Result<(), MarkdownString> {
5847 use KeyBindingContextPredicate::*;
5848
5849 if binding.keystrokes().len() == 1 && binding.keystrokes()[0].modifiers.modified() {
5850 return Ok(());
5851 }
5852 let required_predicate =
5853 Not(Identifier(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT.into()).into());
5854 match binding.predicate() {
5855 Some(predicate) if required_predicate.is_superset(&predicate) => {
5856 return Ok(());
5857 }
5858 _ => {}
5859 }
5860 Err(MarkdownString(format!(
5861 "{} can only be bound to a single keystroke with modifiers, so \
5862 that holding down these modifiers can be used to preview \
5863 completions inline when the completions menu is open.\n\n\
5864 This restriction does not apply when the context requires {}, \
5865 since these bindings will not be used when the completions menu \
5866 is open.",
5867 MarkdownString::inline_code(AcceptEditPrediction.name()),
5868 MarkdownString::inline_code(&format!(
5869 "!{}",
5870 EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT
5871 )),
5872 )))
5873 }
5874}
5875
5876#[allow(clippy::too_many_arguments)]
5877fn prepaint_gutter_button(
5878 button: IconButton,
5879 row: DisplayRow,
5880 line_height: Pixels,
5881 gutter_dimensions: &GutterDimensions,
5882 scroll_pixel_position: gpui::Point<Pixels>,
5883 gutter_hitbox: &Hitbox,
5884 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5885 window: &mut Window,
5886 cx: &mut App,
5887) -> AnyElement {
5888 let mut button = button.into_any_element();
5889 let available_space = size(
5890 AvailableSpace::MinContent,
5891 AvailableSpace::Definite(line_height),
5892 );
5893 let indicator_size = button.layout_as_root(available_space, window, cx);
5894
5895 let blame_width = gutter_dimensions.git_blame_entries_width;
5896 let gutter_width = rows_with_hunk_bounds
5897 .get(&row)
5898 .map(|bounds| bounds.size.width);
5899 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5900
5901 let mut x = left_offset;
5902 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5903 - indicator_size.width
5904 - left_offset;
5905 x += available_width / 2.;
5906
5907 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5908 y += (line_height - indicator_size.height) / 2.;
5909
5910 button.prepaint_as_root(
5911 gutter_hitbox.origin + point(x, y),
5912 available_space,
5913 window,
5914 cx,
5915 );
5916 button
5917}
5918
5919fn render_inline_blame_entry(
5920 blame: &gpui::Entity<GitBlame>,
5921 blame_entry: BlameEntry,
5922 style: &EditorStyle,
5923 workspace: Option<WeakEntity<Workspace>>,
5924 cx: &mut App,
5925) -> AnyElement {
5926 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5927
5928 let author = blame_entry.author.as_deref().unwrap_or_default();
5929 let summary_enabled = ProjectSettings::get_global(cx)
5930 .git
5931 .show_inline_commit_summary();
5932
5933 let text = match blame_entry.summary.as_ref() {
5934 Some(summary) if summary_enabled => {
5935 format!("{}, {} - {}", author, relative_timestamp, summary)
5936 }
5937 _ => format!("{}, {}", author, relative_timestamp),
5938 };
5939
5940 let details = blame.read(cx).details_for_entry(&blame_entry);
5941
5942 let tooltip = cx.new(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
5943
5944 h_flex()
5945 .id("inline-blame")
5946 .w_full()
5947 .font_family(style.text.font().family)
5948 .text_color(cx.theme().status().hint)
5949 .line_height(style.text.line_height)
5950 .child(Icon::new(IconName::FileGit).color(Color::Hint))
5951 .child(text)
5952 .gap_2()
5953 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5954 .into_any()
5955}
5956
5957fn render_blame_entry(
5958 ix: usize,
5959 blame: &gpui::Entity<GitBlame>,
5960 blame_entry: BlameEntry,
5961 style: &EditorStyle,
5962 last_used_color: &mut Option<(PlayerColor, Oid)>,
5963 editor: Entity<Editor>,
5964 cx: &mut App,
5965) -> AnyElement {
5966 let mut sha_color = cx
5967 .theme()
5968 .players()
5969 .color_for_participant(blame_entry.sha.into());
5970 // If the last color we used is the same as the one we get for this line, but
5971 // the commit SHAs are different, then we try again to get a different color.
5972 match *last_used_color {
5973 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5974 let index: u32 = blame_entry.sha.into();
5975 sha_color = cx.theme().players().color_for_participant(index + 1);
5976 }
5977 _ => {}
5978 };
5979 last_used_color.replace((sha_color, blame_entry.sha));
5980
5981 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5982
5983 let short_commit_id = blame_entry.sha.display_short();
5984
5985 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5986 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5987
5988 let details = blame.read(cx).details_for_entry(&blame_entry);
5989
5990 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
5991
5992 let tooltip =
5993 cx.new(|_| BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace));
5994
5995 h_flex()
5996 .w_full()
5997 .justify_between()
5998 .font_family(style.text.font().family)
5999 .line_height(style.text.line_height)
6000 .id(("blame", ix))
6001 .text_color(cx.theme().status().hint)
6002 .pr_2()
6003 .gap_2()
6004 .child(
6005 h_flex()
6006 .items_center()
6007 .gap_2()
6008 .child(div().text_color(sha_color.cursor).child(short_commit_id))
6009 .child(name),
6010 )
6011 .child(relative_timestamp)
6012 .on_mouse_down(MouseButton::Right, {
6013 let blame_entry = blame_entry.clone();
6014 let details = details.clone();
6015 move |event, window, cx| {
6016 deploy_blame_entry_context_menu(
6017 &blame_entry,
6018 details.as_ref(),
6019 editor.clone(),
6020 event.position,
6021 window,
6022 cx,
6023 );
6024 }
6025 })
6026 .hover(|style| style.bg(cx.theme().colors().element_hover))
6027 .when_some(
6028 details.and_then(|details| details.permalink),
6029 |this, url| {
6030 let url = url.clone();
6031 this.cursor_pointer().on_click(move |_, _, cx| {
6032 cx.stop_propagation();
6033 cx.open_url(url.as_str())
6034 })
6035 },
6036 )
6037 .hoverable_tooltip(move |_, _| tooltip.clone().into())
6038 .into_any()
6039}
6040
6041fn deploy_blame_entry_context_menu(
6042 blame_entry: &BlameEntry,
6043 details: Option<&CommitDetails>,
6044 editor: Entity<Editor>,
6045 position: gpui::Point<Pixels>,
6046 window: &mut Window,
6047 cx: &mut App,
6048) {
6049 let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
6050 let sha = format!("{}", blame_entry.sha);
6051 menu.on_blur_subscription(Subscription::new(|| {}))
6052 .entry("Copy commit SHA", None, move |_, cx| {
6053 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
6054 })
6055 .when_some(
6056 details.and_then(|details| details.permalink.clone()),
6057 |this, url| {
6058 this.entry("Open permalink", None, move |_, cx| {
6059 cx.open_url(url.as_str())
6060 })
6061 },
6062 )
6063 });
6064
6065 editor.update(cx, move |editor, cx| {
6066 editor.mouse_context_menu = Some(MouseContextMenu::new(
6067 MenuPosition::PinnedToScreen(position),
6068 context_menu,
6069 window,
6070 cx,
6071 ));
6072 cx.notify();
6073 });
6074}
6075
6076#[derive(Debug)]
6077pub(crate) struct LineWithInvisibles {
6078 fragments: SmallVec<[LineFragment; 1]>,
6079 invisibles: Vec<Invisible>,
6080 len: usize,
6081 width: Pixels,
6082 font_size: Pixels,
6083}
6084
6085#[allow(clippy::large_enum_variant)]
6086enum LineFragment {
6087 Text(ShapedLine),
6088 Element {
6089 element: Option<AnyElement>,
6090 size: Size<Pixels>,
6091 len: usize,
6092 },
6093}
6094
6095impl fmt::Debug for LineFragment {
6096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6097 match self {
6098 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6099 LineFragment::Element { size, len, .. } => f
6100 .debug_struct("Element")
6101 .field("size", size)
6102 .field("len", len)
6103 .finish(),
6104 }
6105 }
6106}
6107
6108impl LineWithInvisibles {
6109 #[allow(clippy::too_many_arguments)]
6110 fn from_chunks<'a>(
6111 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6112 editor_style: &EditorStyle,
6113 max_line_len: usize,
6114 max_line_count: usize,
6115 editor_mode: EditorMode,
6116 text_width: Pixels,
6117 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6118 window: &mut Window,
6119 cx: &mut App,
6120 ) -> Vec<Self> {
6121 let text_style = &editor_style.text;
6122 let mut layouts = Vec::with_capacity(max_line_count);
6123 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6124 let mut line = String::new();
6125 let mut invisibles = Vec::new();
6126 let mut width = Pixels::ZERO;
6127 let mut len = 0;
6128 let mut styles = Vec::new();
6129 let mut non_whitespace_added = false;
6130 let mut row = 0;
6131 let mut line_exceeded_max_len = false;
6132 let font_size = text_style.font_size.to_pixels(window.rem_size());
6133
6134 let ellipsis = SharedString::from("⋯");
6135
6136 for highlighted_chunk in chunks.chain([HighlightedChunk {
6137 text: "\n",
6138 style: None,
6139 is_tab: false,
6140 replacement: None,
6141 }]) {
6142 if let Some(replacement) = highlighted_chunk.replacement {
6143 if !line.is_empty() {
6144 let shaped_line = window
6145 .text_system()
6146 .shape_line(line.clone().into(), font_size, &styles)
6147 .unwrap();
6148 width += shaped_line.width;
6149 len += shaped_line.len;
6150 fragments.push(LineFragment::Text(shaped_line));
6151 line.clear();
6152 styles.clear();
6153 }
6154
6155 match replacement {
6156 ChunkReplacement::Renderer(renderer) => {
6157 let available_width = if renderer.constrain_width {
6158 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6159 ellipsis.clone()
6160 } else {
6161 SharedString::from(Arc::from(highlighted_chunk.text))
6162 };
6163 let shaped_line = window
6164 .text_system()
6165 .shape_line(
6166 chunk,
6167 font_size,
6168 &[text_style.to_run(highlighted_chunk.text.len())],
6169 )
6170 .unwrap();
6171 AvailableSpace::Definite(shaped_line.width)
6172 } else {
6173 AvailableSpace::MinContent
6174 };
6175
6176 let mut element = (renderer.render)(&mut ChunkRendererContext {
6177 context: cx,
6178 window,
6179 max_width: text_width,
6180 });
6181 let line_height = text_style.line_height_in_pixels(window.rem_size());
6182 let size = element.layout_as_root(
6183 size(available_width, AvailableSpace::Definite(line_height)),
6184 window,
6185 cx,
6186 );
6187
6188 width += size.width;
6189 len += highlighted_chunk.text.len();
6190 fragments.push(LineFragment::Element {
6191 element: Some(element),
6192 size,
6193 len: highlighted_chunk.text.len(),
6194 });
6195 }
6196 ChunkReplacement::Str(x) => {
6197 let text_style = if let Some(style) = highlighted_chunk.style {
6198 Cow::Owned(text_style.clone().highlight(style))
6199 } else {
6200 Cow::Borrowed(text_style)
6201 };
6202
6203 let run = TextRun {
6204 len: x.len(),
6205 font: text_style.font(),
6206 color: text_style.color,
6207 background_color: text_style.background_color,
6208 underline: text_style.underline,
6209 strikethrough: text_style.strikethrough,
6210 };
6211 let line_layout = window
6212 .text_system()
6213 .shape_line(x, font_size, &[run])
6214 .unwrap()
6215 .with_len(highlighted_chunk.text.len());
6216
6217 width += line_layout.width;
6218 len += highlighted_chunk.text.len();
6219 fragments.push(LineFragment::Text(line_layout))
6220 }
6221 }
6222 } else {
6223 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6224 if ix > 0 {
6225 let shaped_line = window
6226 .text_system()
6227 .shape_line(line.clone().into(), font_size, &styles)
6228 .unwrap();
6229 width += shaped_line.width;
6230 len += shaped_line.len;
6231 fragments.push(LineFragment::Text(shaped_line));
6232 layouts.push(Self {
6233 width: mem::take(&mut width),
6234 len: mem::take(&mut len),
6235 fragments: mem::take(&mut fragments),
6236 invisibles: std::mem::take(&mut invisibles),
6237 font_size,
6238 });
6239
6240 line.clear();
6241 styles.clear();
6242 row += 1;
6243 line_exceeded_max_len = false;
6244 non_whitespace_added = false;
6245 if row == max_line_count {
6246 return layouts;
6247 }
6248 }
6249
6250 if !line_chunk.is_empty() && !line_exceeded_max_len {
6251 let text_style = if let Some(style) = highlighted_chunk.style {
6252 Cow::Owned(text_style.clone().highlight(style))
6253 } else {
6254 Cow::Borrowed(text_style)
6255 };
6256
6257 if line.len() + line_chunk.len() > max_line_len {
6258 let mut chunk_len = max_line_len - line.len();
6259 while !line_chunk.is_char_boundary(chunk_len) {
6260 chunk_len -= 1;
6261 }
6262 line_chunk = &line_chunk[..chunk_len];
6263 line_exceeded_max_len = true;
6264 }
6265
6266 styles.push(TextRun {
6267 len: line_chunk.len(),
6268 font: text_style.font(),
6269 color: text_style.color,
6270 background_color: text_style.background_color,
6271 underline: text_style.underline,
6272 strikethrough: text_style.strikethrough,
6273 });
6274
6275 if editor_mode == EditorMode::Full {
6276 // Line wrap pads its contents with fake whitespaces,
6277 // avoid printing them
6278 let is_soft_wrapped = is_row_soft_wrapped(row);
6279 if highlighted_chunk.is_tab {
6280 if non_whitespace_added || !is_soft_wrapped {
6281 invisibles.push(Invisible::Tab {
6282 line_start_offset: line.len(),
6283 line_end_offset: line.len() + line_chunk.len(),
6284 });
6285 }
6286 } else {
6287 invisibles.extend(line_chunk.char_indices().filter_map(
6288 |(index, c)| {
6289 let is_whitespace = c.is_whitespace();
6290 non_whitespace_added |= !is_whitespace;
6291 if is_whitespace
6292 && (non_whitespace_added || !is_soft_wrapped)
6293 {
6294 Some(Invisible::Whitespace {
6295 line_offset: line.len() + index,
6296 })
6297 } else {
6298 None
6299 }
6300 },
6301 ))
6302 }
6303 }
6304
6305 line.push_str(line_chunk);
6306 }
6307 }
6308 }
6309 }
6310
6311 layouts
6312 }
6313
6314 #[allow(clippy::too_many_arguments)]
6315 fn prepaint(
6316 &mut self,
6317 line_height: Pixels,
6318 scroll_pixel_position: gpui::Point<Pixels>,
6319 row: DisplayRow,
6320 content_origin: gpui::Point<Pixels>,
6321 line_elements: &mut SmallVec<[AnyElement; 1]>,
6322 window: &mut Window,
6323 cx: &mut App,
6324 ) {
6325 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6326 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6327 for fragment in &mut self.fragments {
6328 match fragment {
6329 LineFragment::Text(line) => {
6330 fragment_origin.x += line.width;
6331 }
6332 LineFragment::Element { element, size, .. } => {
6333 let mut element = element
6334 .take()
6335 .expect("you can't prepaint LineWithInvisibles twice");
6336
6337 // Center the element vertically within the line.
6338 let mut element_origin = fragment_origin;
6339 element_origin.y += (line_height - size.height) / 2.;
6340 element.prepaint_at(element_origin, window, cx);
6341 line_elements.push(element);
6342
6343 fragment_origin.x += size.width;
6344 }
6345 }
6346 }
6347 }
6348
6349 #[allow(clippy::too_many_arguments)]
6350 fn draw(
6351 &self,
6352 layout: &EditorLayout,
6353 row: DisplayRow,
6354 content_origin: gpui::Point<Pixels>,
6355 whitespace_setting: ShowWhitespaceSetting,
6356 selection_ranges: &[Range<DisplayPoint>],
6357 window: &mut Window,
6358 cx: &mut App,
6359 ) {
6360 let line_height = layout.position_map.line_height;
6361 let line_y = line_height
6362 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6363
6364 let mut fragment_origin =
6365 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6366
6367 for fragment in &self.fragments {
6368 match fragment {
6369 LineFragment::Text(line) => {
6370 line.paint(fragment_origin, line_height, window, cx)
6371 .log_err();
6372 fragment_origin.x += line.width;
6373 }
6374 LineFragment::Element { size, .. } => {
6375 fragment_origin.x += size.width;
6376 }
6377 }
6378 }
6379
6380 self.draw_invisibles(
6381 selection_ranges,
6382 layout,
6383 content_origin,
6384 line_y,
6385 row,
6386 line_height,
6387 whitespace_setting,
6388 window,
6389 cx,
6390 );
6391 }
6392
6393 #[allow(clippy::too_many_arguments)]
6394 fn draw_invisibles(
6395 &self,
6396 selection_ranges: &[Range<DisplayPoint>],
6397 layout: &EditorLayout,
6398 content_origin: gpui::Point<Pixels>,
6399 line_y: Pixels,
6400 row: DisplayRow,
6401 line_height: Pixels,
6402 whitespace_setting: ShowWhitespaceSetting,
6403 window: &mut Window,
6404 cx: &mut App,
6405 ) {
6406 let extract_whitespace_info = |invisible: &Invisible| {
6407 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6408 Invisible::Tab {
6409 line_start_offset,
6410 line_end_offset,
6411 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6412 Invisible::Whitespace { line_offset } => {
6413 (*line_offset, line_offset + 1, &layout.space_invisible)
6414 }
6415 };
6416
6417 let x_offset = self.x_for_index(token_offset);
6418 let invisible_offset =
6419 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6420 let origin = content_origin
6421 + gpui::point(
6422 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6423 line_y,
6424 );
6425
6426 (
6427 [token_offset, token_end_offset],
6428 Box::new(move |window: &mut Window, cx: &mut App| {
6429 invisible_symbol
6430 .paint(origin, line_height, window, cx)
6431 .log_err();
6432 }),
6433 )
6434 };
6435
6436 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6437 match whitespace_setting {
6438 ShowWhitespaceSetting::None => (),
6439 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6440 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6441 let invisible_point = DisplayPoint::new(row, start as u32);
6442 if !selection_ranges
6443 .iter()
6444 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6445 {
6446 return;
6447 }
6448
6449 paint(window, cx);
6450 }),
6451
6452 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6453 // - It is a tab
6454 // - It is adjacent to an edge (start or end)
6455 // - It is adjacent to a whitespace (left or right)
6456 ShowWhitespaceSetting::Boundary => {
6457 // 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
6458 // the above cases.
6459 // Note: We zip in the original `invisibles` to check for tab equality
6460 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6461 for (([start, end], paint), invisible) in
6462 invisible_iter.zip_eq(self.invisibles.iter())
6463 {
6464 let should_render = match (&last_seen, invisible) {
6465 (_, Invisible::Tab { .. }) => true,
6466 (Some((_, last_end, _)), _) => *last_end == start,
6467 _ => false,
6468 };
6469
6470 if should_render || start == 0 || end == self.len {
6471 paint(window, cx);
6472
6473 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6474 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6475 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6476 // Note that we need to make sure that the last one is actually adjacent
6477 if !should_render_last && last_end == start {
6478 paint_last(window, cx);
6479 }
6480 }
6481 }
6482
6483 // Manually render anything within a selection
6484 let invisible_point = DisplayPoint::new(row, start as u32);
6485 if selection_ranges.iter().any(|region| {
6486 region.start <= invisible_point && invisible_point < region.end
6487 }) {
6488 paint(window, cx);
6489 }
6490
6491 last_seen = Some((should_render, end, paint));
6492 }
6493 }
6494 }
6495 }
6496
6497 pub fn x_for_index(&self, index: usize) -> Pixels {
6498 let mut fragment_start_x = Pixels::ZERO;
6499 let mut fragment_start_index = 0;
6500
6501 for fragment in &self.fragments {
6502 match fragment {
6503 LineFragment::Text(shaped_line) => {
6504 let fragment_end_index = fragment_start_index + shaped_line.len;
6505 if index < fragment_end_index {
6506 return fragment_start_x
6507 + shaped_line.x_for_index(index - fragment_start_index);
6508 }
6509 fragment_start_x += shaped_line.width;
6510 fragment_start_index = fragment_end_index;
6511 }
6512 LineFragment::Element { len, size, .. } => {
6513 let fragment_end_index = fragment_start_index + len;
6514 if index < fragment_end_index {
6515 return fragment_start_x;
6516 }
6517 fragment_start_x += size.width;
6518 fragment_start_index = fragment_end_index;
6519 }
6520 }
6521 }
6522
6523 fragment_start_x
6524 }
6525
6526 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6527 let mut fragment_start_x = Pixels::ZERO;
6528 let mut fragment_start_index = 0;
6529
6530 for fragment in &self.fragments {
6531 match fragment {
6532 LineFragment::Text(shaped_line) => {
6533 let fragment_end_x = fragment_start_x + shaped_line.width;
6534 if x < fragment_end_x {
6535 return Some(
6536 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6537 );
6538 }
6539 fragment_start_x = fragment_end_x;
6540 fragment_start_index += shaped_line.len;
6541 }
6542 LineFragment::Element { len, size, .. } => {
6543 let fragment_end_x = fragment_start_x + size.width;
6544 if x < fragment_end_x {
6545 return Some(fragment_start_index);
6546 }
6547 fragment_start_index += len;
6548 fragment_start_x = fragment_end_x;
6549 }
6550 }
6551 }
6552
6553 None
6554 }
6555
6556 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6557 let mut fragment_start_index = 0;
6558
6559 for fragment in &self.fragments {
6560 match fragment {
6561 LineFragment::Text(shaped_line) => {
6562 let fragment_end_index = fragment_start_index + shaped_line.len;
6563 if index < fragment_end_index {
6564 return shaped_line.font_id_for_index(index - fragment_start_index);
6565 }
6566 fragment_start_index = fragment_end_index;
6567 }
6568 LineFragment::Element { len, .. } => {
6569 let fragment_end_index = fragment_start_index + len;
6570 if index < fragment_end_index {
6571 return None;
6572 }
6573 fragment_start_index = fragment_end_index;
6574 }
6575 }
6576 }
6577
6578 None
6579 }
6580}
6581
6582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6583enum Invisible {
6584 /// A tab character
6585 ///
6586 /// A tab character is internally represented by spaces (configured by the user's tab width)
6587 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6588 /// adjacency checks.
6589 Tab {
6590 line_start_offset: usize,
6591 line_end_offset: usize,
6592 },
6593 Whitespace {
6594 line_offset: usize,
6595 },
6596}
6597
6598impl EditorElement {
6599 /// Returns the rem size to use when rendering the [`EditorElement`].
6600 ///
6601 /// This allows UI elements to scale based on the `buffer_font_size`.
6602 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6603 match self.editor.read(cx).mode {
6604 EditorMode::Full => {
6605 let buffer_font_size = self.style.text.font_size;
6606 match buffer_font_size {
6607 AbsoluteLength::Pixels(pixels) => {
6608 let rem_size_scale = {
6609 // Our default UI font size is 14px on a 16px base scale.
6610 // This means the default UI font size is 0.875rems.
6611 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6612
6613 // We then determine the delta between a single rem and the default font
6614 // size scale.
6615 let default_font_size_delta = 1. - default_font_size_scale;
6616
6617 // Finally, we add this delta to 1rem to get the scale factor that
6618 // should be used to scale up the UI.
6619 1. + default_font_size_delta
6620 };
6621
6622 Some(pixels * rem_size_scale)
6623 }
6624 AbsoluteLength::Rems(rems) => {
6625 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6626 }
6627 }
6628 }
6629 // We currently use single-line and auto-height editors in UI contexts,
6630 // so we don't want to scale everything with the buffer font size, as it
6631 // ends up looking off.
6632 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6633 }
6634 }
6635}
6636
6637impl Element for EditorElement {
6638 type RequestLayoutState = ();
6639 type PrepaintState = EditorLayout;
6640
6641 fn id(&self) -> Option<ElementId> {
6642 None
6643 }
6644
6645 fn request_layout(
6646 &mut self,
6647 _: Option<&GlobalElementId>,
6648 window: &mut Window,
6649 cx: &mut App,
6650 ) -> (gpui::LayoutId, ()) {
6651 let rem_size = self.rem_size(cx);
6652 window.with_rem_size(rem_size, |window| {
6653 self.editor.update(cx, |editor, cx| {
6654 editor.set_style(self.style.clone(), window, cx);
6655
6656 let layout_id = match editor.mode {
6657 EditorMode::SingleLine { auto_width } => {
6658 let rem_size = window.rem_size();
6659
6660 let height = self.style.text.line_height_in_pixels(rem_size);
6661 if auto_width {
6662 let editor_handle = cx.entity().clone();
6663 let style = self.style.clone();
6664 window.request_measured_layout(
6665 Style::default(),
6666 move |_, _, window, cx| {
6667 let editor_snapshot = editor_handle
6668 .update(cx, |editor, cx| editor.snapshot(window, cx));
6669 let line = Self::layout_lines(
6670 DisplayRow(0)..DisplayRow(1),
6671 &editor_snapshot,
6672 &style,
6673 px(f32::MAX),
6674 |_| false, // Single lines never soft wrap
6675 window,
6676 cx,
6677 )
6678 .pop()
6679 .unwrap();
6680
6681 let font_id =
6682 window.text_system().resolve_font(&style.text.font());
6683 let font_size =
6684 style.text.font_size.to_pixels(window.rem_size());
6685 let em_width =
6686 window.text_system().em_width(font_id, font_size).unwrap();
6687
6688 size(line.width + em_width, height)
6689 },
6690 )
6691 } else {
6692 let mut style = Style::default();
6693 style.size.height = height.into();
6694 style.size.width = relative(1.).into();
6695 window.request_layout(style, None, cx)
6696 }
6697 }
6698 EditorMode::AutoHeight { max_lines } => {
6699 let editor_handle = cx.entity().clone();
6700 let max_line_number_width =
6701 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6702 window.request_measured_layout(
6703 Style::default(),
6704 move |known_dimensions, available_space, window, cx| {
6705 editor_handle
6706 .update(cx, |editor, cx| {
6707 compute_auto_height_layout(
6708 editor,
6709 max_lines,
6710 max_line_number_width,
6711 known_dimensions,
6712 available_space.width,
6713 window,
6714 cx,
6715 )
6716 })
6717 .unwrap_or_default()
6718 },
6719 )
6720 }
6721 EditorMode::Full => {
6722 let mut style = Style::default();
6723 style.size.width = relative(1.).into();
6724 style.size.height = relative(1.).into();
6725 window.request_layout(style, None, cx)
6726 }
6727 };
6728
6729 (layout_id, ())
6730 })
6731 })
6732 }
6733
6734 fn prepaint(
6735 &mut self,
6736 _: Option<&GlobalElementId>,
6737 bounds: Bounds<Pixels>,
6738 _: &mut Self::RequestLayoutState,
6739 window: &mut Window,
6740 cx: &mut App,
6741 ) -> Self::PrepaintState {
6742 let text_style = TextStyleRefinement {
6743 font_size: Some(self.style.text.font_size),
6744 line_height: Some(self.style.text.line_height),
6745 ..Default::default()
6746 };
6747 let focus_handle = self.editor.focus_handle(cx);
6748 window.set_view_id(self.editor.entity_id());
6749 window.set_focus_handle(&focus_handle, cx);
6750
6751 let rem_size = self.rem_size(cx);
6752 window.with_rem_size(rem_size, |window| {
6753 window.with_text_style(Some(text_style), |window| {
6754 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6755 let mut snapshot = self
6756 .editor
6757 .update(cx, |editor, cx| editor.snapshot(window, cx));
6758 let style = self.style.clone();
6759
6760 let font_id = window.text_system().resolve_font(&style.text.font());
6761 let font_size = style.text.font_size.to_pixels(window.rem_size());
6762 let line_height = style.text.line_height_in_pixels(window.rem_size());
6763 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6764 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6765
6766 let letter_size = size(em_width, line_height);
6767
6768 let gutter_dimensions = snapshot
6769 .gutter_dimensions(
6770 font_id,
6771 font_size,
6772 self.max_line_number_width(&snapshot, window, cx),
6773 cx,
6774 )
6775 .unwrap_or_default();
6776 let text_width = bounds.size.width - gutter_dimensions.width;
6777
6778 let editor_width =
6779 text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6780
6781 snapshot = self.editor.update(cx, |editor, cx| {
6782 editor.last_bounds = Some(bounds);
6783 editor.gutter_dimensions = gutter_dimensions;
6784 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6785
6786 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6787 snapshot
6788 } else {
6789 let wrap_width = match editor.soft_wrap_mode(cx) {
6790 SoftWrap::GitDiff => None,
6791 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6792 SoftWrap::EditorWidth => Some(editor_width),
6793 SoftWrap::Column(column) => Some(column as f32 * em_advance),
6794 SoftWrap::Bounded(column) => {
6795 Some(editor_width.min(column as f32 * em_advance))
6796 }
6797 };
6798
6799 if editor.set_wrap_width(wrap_width, cx) {
6800 editor.snapshot(window, cx)
6801 } else {
6802 snapshot
6803 }
6804 }
6805 });
6806
6807 let wrap_guides = self
6808 .editor
6809 .read(cx)
6810 .wrap_guides(cx)
6811 .iter()
6812 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6813 .collect::<SmallVec<[_; 2]>>();
6814
6815 let hitbox = window.insert_hitbox(bounds, false);
6816 let gutter_hitbox =
6817 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6818 let text_hitbox = window.insert_hitbox(
6819 Bounds {
6820 origin: gutter_hitbox.top_right(),
6821 size: size(text_width, bounds.size.height),
6822 },
6823 false,
6824 );
6825 // Offset the content_bounds from the text_bounds by the gutter margin (which
6826 // is roughly half a character wide) to make hit testing work more like how we want.
6827 let content_origin =
6828 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6829
6830 let scrollbar_bounds =
6831 Bounds::from_corners(content_origin, bounds.bottom_right());
6832
6833 let height_in_lines = scrollbar_bounds.size.height / line_height;
6834
6835 // NOTE: The max row number in the current file, minus one
6836 let max_row = snapshot.max_point().row().as_f32();
6837
6838 // NOTE: The max scroll position for the top of the window
6839 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6840 (max_row - height_in_lines + 1.).max(0.)
6841 } else {
6842 let settings = EditorSettings::get_global(cx);
6843 match settings.scroll_beyond_last_line {
6844 ScrollBeyondLastLine::OnePage => max_row,
6845 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6846 ScrollBeyondLastLine::VerticalScrollMargin => {
6847 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6848 .max(0.)
6849 }
6850 }
6851 };
6852
6853 // TODO: Autoscrolling for both axes
6854 let mut autoscroll_request = None;
6855 let mut autoscroll_containing_element = false;
6856 let mut autoscroll_horizontally = false;
6857 self.editor.update(cx, |editor, cx| {
6858 autoscroll_request = editor.autoscroll_request();
6859 autoscroll_containing_element =
6860 autoscroll_request.is_some() || editor.has_pending_selection();
6861 // TODO: Is this horizontal or vertical?!
6862 autoscroll_horizontally = editor.autoscroll_vertically(
6863 bounds,
6864 line_height,
6865 max_scroll_top,
6866 window,
6867 cx,
6868 );
6869 snapshot = editor.snapshot(window, cx);
6870 });
6871
6872 let mut scroll_position = snapshot.scroll_position();
6873 // The scroll position is a fractional point, the whole number of which represents
6874 // the top of the window in terms of display rows.
6875 let start_row = DisplayRow(scroll_position.y as u32);
6876 let max_row = snapshot.max_point().row();
6877 let end_row = cmp::min(
6878 (scroll_position.y + height_in_lines).ceil() as u32,
6879 max_row.next_row().0,
6880 );
6881 let end_row = DisplayRow(end_row);
6882
6883 let row_infos = snapshot
6884 .row_infos(start_row)
6885 .take((start_row..end_row).len())
6886 .collect::<Vec<RowInfo>>();
6887 let is_row_soft_wrapped = |row: usize| {
6888 row_infos
6889 .get(row)
6890 .map_or(true, |info| info.buffer_row.is_none())
6891 };
6892
6893 let start_anchor = if start_row == Default::default() {
6894 Anchor::min()
6895 } else {
6896 snapshot.buffer_snapshot.anchor_before(
6897 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6898 )
6899 };
6900 let end_anchor = if end_row > max_row {
6901 Anchor::max()
6902 } else {
6903 snapshot.buffer_snapshot.anchor_before(
6904 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6905 )
6906 };
6907
6908 let (mut highlighted_rows, distinguish_unstaged_hunks) =
6909 self.editor.update(cx, |editor, cx| {
6910 (
6911 editor.highlighted_display_rows(window, cx),
6912 editor.distinguish_unstaged_diff_hunks,
6913 )
6914 });
6915
6916 for (ix, row_info) in row_infos.iter().enumerate() {
6917 let background = match row_info.diff_status {
6918 Some(DiffHunkStatus::Added(secondary_status)) => {
6919 let color = style.status.created_background;
6920 match secondary_status {
6921 DiffHunkSecondaryStatus::HasSecondaryHunk
6922 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6923 if distinguish_unstaged_hunks =>
6924 {
6925 pattern_slash(color, line_height.0 / 4.0)
6926 }
6927 _ => color.into(),
6928 }
6929 }
6930 Some(DiffHunkStatus::Removed(secondary_status)) => {
6931 let color = style.status.deleted_background;
6932 match secondary_status {
6933 DiffHunkSecondaryStatus::HasSecondaryHunk
6934 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6935 if distinguish_unstaged_hunks =>
6936 {
6937 pattern_slash(color, line_height.0 / 4.0)
6938 }
6939 _ => color.into(),
6940 }
6941 }
6942 _ => continue,
6943 };
6944
6945 highlighted_rows
6946 .entry(start_row + DisplayRow(ix as u32))
6947 .or_insert(background);
6948 }
6949
6950 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6951 start_anchor..end_anchor,
6952 &snapshot.display_snapshot,
6953 cx.theme().colors(),
6954 );
6955 let highlighted_gutter_ranges =
6956 self.editor.read(cx).gutter_highlights_in_range(
6957 start_anchor..end_anchor,
6958 &snapshot.display_snapshot,
6959 cx,
6960 );
6961
6962 let redacted_ranges = self.editor.read(cx).redacted_ranges(
6963 start_anchor..end_anchor,
6964 &snapshot.display_snapshot,
6965 cx,
6966 );
6967
6968 let (local_selections, selected_buffer_ids): (
6969 Vec<Selection<Point>>,
6970 Vec<BufferId>,
6971 ) = self.editor.update(cx, |editor, cx| {
6972 let all_selections = editor.selections.all::<Point>(cx);
6973 let selected_buffer_ids = if editor.is_singleton(cx) {
6974 Vec::new()
6975 } else {
6976 let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6977
6978 for selection in all_selections {
6979 for buffer_id in snapshot
6980 .buffer_snapshot
6981 .buffer_ids_for_range(selection.range())
6982 {
6983 if selected_buffer_ids.last() != Some(&buffer_id) {
6984 selected_buffer_ids.push(buffer_id);
6985 }
6986 }
6987 }
6988
6989 selected_buffer_ids
6990 };
6991
6992 let mut selections = editor
6993 .selections
6994 .disjoint_in_range(start_anchor..end_anchor, cx);
6995 selections.extend(editor.selections.pending(cx));
6996
6997 (selections, selected_buffer_ids)
6998 });
6999
7000 let (selections, active_rows, newest_selection_head) = self.layout_selections(
7001 start_anchor,
7002 end_anchor,
7003 &local_selections,
7004 &snapshot,
7005 start_row,
7006 end_row,
7007 window,
7008 cx,
7009 );
7010
7011 let line_numbers = self.layout_line_numbers(
7012 Some(&gutter_hitbox),
7013 gutter_dimensions,
7014 line_height,
7015 scroll_position,
7016 start_row..end_row,
7017 &row_infos,
7018 newest_selection_head,
7019 &snapshot,
7020 window,
7021 cx,
7022 );
7023
7024 let mut crease_toggles =
7025 window.with_element_namespace("crease_toggles", |window| {
7026 self.layout_crease_toggles(
7027 start_row..end_row,
7028 &row_infos,
7029 &active_rows,
7030 &snapshot,
7031 window,
7032 cx,
7033 )
7034 });
7035 let crease_trailers =
7036 window.with_element_namespace("crease_trailers", |window| {
7037 self.layout_crease_trailers(
7038 row_infos.iter().copied(),
7039 &snapshot,
7040 window,
7041 cx,
7042 )
7043 });
7044
7045 let display_hunks = self.layout_gutter_diff_hunks(
7046 line_height,
7047 &gutter_hitbox,
7048 start_row..end_row,
7049 &snapshot,
7050 window,
7051 cx,
7052 );
7053
7054 let mut line_layouts = Self::layout_lines(
7055 start_row..end_row,
7056 &snapshot,
7057 &self.style,
7058 editor_width,
7059 is_row_soft_wrapped,
7060 window,
7061 cx,
7062 );
7063
7064 let longest_line_blame_width = self
7065 .editor
7066 .update(cx, |editor, cx| {
7067 if !editor.show_git_blame_inline {
7068 return None;
7069 }
7070 let blame = editor.blame.as_ref()?;
7071 let blame_entry = blame
7072 .update(cx, |blame, cx| {
7073 let row_infos =
7074 snapshot.row_infos(snapshot.longest_row()).next()?;
7075 blame.blame_for_rows(&[row_infos], cx).next()
7076 })
7077 .flatten()?;
7078 let workspace = editor.workspace.as_ref().map(|(w, _)| w.to_owned());
7079 let mut element = render_inline_blame_entry(
7080 blame,
7081 blame_entry,
7082 &style,
7083 workspace,
7084 cx,
7085 );
7086 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7087 Some(
7088 element
7089 .layout_as_root(AvailableSpace::min_size(), window, cx)
7090 .width
7091 + inline_blame_padding,
7092 )
7093 })
7094 .unwrap_or(Pixels::ZERO);
7095
7096 let longest_line_width = layout_line(
7097 snapshot.longest_row(),
7098 &snapshot,
7099 &style,
7100 editor_width,
7101 is_row_soft_wrapped,
7102 window,
7103 cx,
7104 )
7105 .width;
7106
7107 let scrollbar_range_data = ScrollbarRangeData::new(
7108 scrollbar_bounds,
7109 letter_size,
7110 &snapshot,
7111 longest_line_width,
7112 longest_line_blame_width,
7113 &style,
7114 editor_width,
7115 cx,
7116 );
7117
7118 let scroll_range_bounds = scrollbar_range_data.scroll_range;
7119 let mut scroll_width = scroll_range_bounds.size.width;
7120
7121 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7122 snapshot.sticky_header_excerpt(start_row)
7123 } else {
7124 None
7125 };
7126 let sticky_header_excerpt_id =
7127 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7128
7129 let blocks = window.with_element_namespace("blocks", |window| {
7130 self.render_blocks(
7131 start_row..end_row,
7132 &snapshot,
7133 &hitbox,
7134 &text_hitbox,
7135 editor_width,
7136 &mut scroll_width,
7137 &gutter_dimensions,
7138 em_width,
7139 gutter_dimensions.full_width(),
7140 line_height,
7141 &line_layouts,
7142 &local_selections,
7143 &selected_buffer_ids,
7144 is_row_soft_wrapped,
7145 sticky_header_excerpt_id,
7146 window,
7147 cx,
7148 )
7149 });
7150 let mut blocks = match blocks {
7151 Ok(blocks) => blocks,
7152 Err(resized_blocks) => {
7153 self.editor.update(cx, |editor, cx| {
7154 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7155 });
7156 return self.prepaint(None, bounds, &mut (), window, cx);
7157 }
7158 };
7159
7160 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7161 window.with_element_namespace("blocks", |window| {
7162 self.layout_sticky_buffer_header(
7163 sticky_header_excerpt,
7164 scroll_position.y,
7165 line_height,
7166 &snapshot,
7167 &hitbox,
7168 &selected_buffer_ids,
7169 window,
7170 cx,
7171 )
7172 })
7173 });
7174
7175 let start_buffer_row =
7176 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7177 let end_buffer_row =
7178 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7179
7180 let scroll_max = point(
7181 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7182 max_row.as_f32(),
7183 );
7184
7185 self.editor.update(cx, |editor, cx| {
7186 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7187
7188 let autoscrolled = if autoscroll_horizontally {
7189 editor.autoscroll_horizontally(
7190 start_row,
7191 editor_width - (letter_size.width / 2.0),
7192 scroll_width,
7193 em_width,
7194 &line_layouts,
7195 cx,
7196 )
7197 } else {
7198 false
7199 };
7200
7201 if clamped || autoscrolled {
7202 snapshot = editor.snapshot(window, cx);
7203 scroll_position = snapshot.scroll_position();
7204 }
7205 });
7206
7207 let scroll_pixel_position = point(
7208 scroll_position.x * em_width,
7209 scroll_position.y * line_height,
7210 );
7211
7212 let indent_guides = self.layout_indent_guides(
7213 content_origin,
7214 text_hitbox.origin,
7215 start_buffer_row..end_buffer_row,
7216 scroll_pixel_position,
7217 line_height,
7218 &snapshot,
7219 window,
7220 cx,
7221 );
7222
7223 let crease_trailers =
7224 window.with_element_namespace("crease_trailers", |window| {
7225 self.prepaint_crease_trailers(
7226 crease_trailers,
7227 &line_layouts,
7228 line_height,
7229 content_origin,
7230 scroll_pixel_position,
7231 em_width,
7232 window,
7233 cx,
7234 )
7235 });
7236
7237 let mut inline_blame = None;
7238 if let Some(newest_selection_head) = newest_selection_head {
7239 let display_row = newest_selection_head.row();
7240 if (start_row..end_row).contains(&display_row) {
7241 let line_ix = display_row.minus(start_row) as usize;
7242 let row_info = &row_infos[line_ix];
7243 let line_layout = &line_layouts[line_ix];
7244 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7245 inline_blame = self.layout_inline_blame(
7246 display_row,
7247 row_info,
7248 line_layout,
7249 crease_trailer_layout,
7250 em_width,
7251 content_origin,
7252 scroll_pixel_position,
7253 line_height,
7254 window,
7255 cx,
7256 );
7257 }
7258 }
7259
7260 let blamed_display_rows = self.layout_blame_entries(
7261 &row_infos,
7262 em_width,
7263 scroll_position,
7264 line_height,
7265 &gutter_hitbox,
7266 gutter_dimensions.git_blame_entries_width,
7267 window,
7268 cx,
7269 );
7270
7271 let scroll_max = point(
7272 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7273 max_scroll_top,
7274 );
7275
7276 self.editor.update(cx, |editor, cx| {
7277 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7278
7279 let autoscrolled = if autoscroll_horizontally {
7280 editor.autoscroll_horizontally(
7281 start_row,
7282 editor_width - (letter_size.width / 2.0),
7283 scroll_width,
7284 em_width,
7285 &line_layouts,
7286 cx,
7287 )
7288 } else {
7289 false
7290 };
7291
7292 if clamped || autoscrolled {
7293 snapshot = editor.snapshot(window, cx);
7294 scroll_position = snapshot.scroll_position();
7295 }
7296 });
7297
7298 let line_elements = self.prepaint_lines(
7299 start_row,
7300 &mut line_layouts,
7301 line_height,
7302 scroll_pixel_position,
7303 content_origin,
7304 window,
7305 cx,
7306 );
7307
7308 let mut block_start_rows = HashSet::default();
7309
7310 window.with_element_namespace("blocks", |window| {
7311 self.layout_blocks(
7312 &mut blocks,
7313 &mut block_start_rows,
7314 &hitbox,
7315 line_height,
7316 scroll_pixel_position,
7317 window,
7318 cx,
7319 );
7320 });
7321
7322 let cursors = self.collect_cursors(&snapshot, cx);
7323 let visible_row_range = start_row..end_row;
7324 let non_visible_cursors = cursors
7325 .iter()
7326 .any(|c| !visible_row_range.contains(&c.0.row()));
7327
7328 let visible_cursors = self.layout_visible_cursors(
7329 &snapshot,
7330 &selections,
7331 &block_start_rows,
7332 start_row..end_row,
7333 &line_layouts,
7334 &text_hitbox,
7335 content_origin,
7336 scroll_position,
7337 scroll_pixel_position,
7338 line_height,
7339 em_width,
7340 em_advance,
7341 autoscroll_containing_element,
7342 window,
7343 cx,
7344 );
7345
7346 let scrollbars_layout = self.layout_scrollbars(
7347 &snapshot,
7348 scrollbar_range_data,
7349 scroll_position,
7350 non_visible_cursors,
7351 window,
7352 cx,
7353 );
7354
7355 let gutter_settings = EditorSettings::get_global(cx).gutter;
7356
7357 let rows_with_hunk_bounds = display_hunks
7358 .iter()
7359 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7360 .fold(
7361 HashMap::default(),
7362 |mut rows_with_hunk_bounds, (hunk, bounds)| {
7363 match hunk {
7364 DisplayDiffHunk::Folded { display_row } => {
7365 rows_with_hunk_bounds.insert(*display_row, bounds);
7366 }
7367 DisplayDiffHunk::Unfolded {
7368 display_row_range, ..
7369 } => {
7370 for display_row in display_row_range.iter_rows() {
7371 rows_with_hunk_bounds.insert(display_row, bounds);
7372 }
7373 }
7374 }
7375 rows_with_hunk_bounds
7376 },
7377 );
7378 let mut code_actions_indicator = None;
7379 if let Some(newest_selection_head) = newest_selection_head {
7380 let newest_selection_point =
7381 newest_selection_head.to_point(&snapshot.display_snapshot);
7382
7383 if (start_row..end_row).contains(&newest_selection_head.row()) {
7384 self.layout_cursor_popovers(
7385 line_height,
7386 &text_hitbox,
7387 content_origin,
7388 start_row,
7389 scroll_pixel_position,
7390 &line_layouts,
7391 newest_selection_head,
7392 newest_selection_point,
7393 &style,
7394 window,
7395 cx,
7396 );
7397
7398 let show_code_actions = snapshot
7399 .show_code_actions
7400 .unwrap_or(gutter_settings.code_actions);
7401 if show_code_actions {
7402 let newest_selection_point =
7403 newest_selection_head.to_point(&snapshot.display_snapshot);
7404 if !snapshot
7405 .is_line_folded(MultiBufferRow(newest_selection_point.row))
7406 {
7407 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7408 MultiBufferRow(newest_selection_point.row),
7409 );
7410 if let Some((buffer, range)) = buffer {
7411 let buffer_id = buffer.remote_id();
7412 let row = range.start.row;
7413 let has_test_indicator = self
7414 .editor
7415 .read(cx)
7416 .tasks
7417 .contains_key(&(buffer_id, row));
7418
7419 if !has_test_indicator {
7420 code_actions_indicator = self
7421 .layout_code_actions_indicator(
7422 line_height,
7423 newest_selection_head,
7424 scroll_pixel_position,
7425 &gutter_dimensions,
7426 &gutter_hitbox,
7427 &rows_with_hunk_bounds,
7428 window,
7429 cx,
7430 );
7431 }
7432 }
7433 }
7434 }
7435 }
7436 }
7437
7438 self.layout_gutter_menu(
7439 line_height,
7440 &text_hitbox,
7441 content_origin,
7442 scroll_pixel_position,
7443 gutter_dimensions.width - gutter_dimensions.left_padding,
7444 window,
7445 cx,
7446 );
7447
7448 let test_indicators = if gutter_settings.runnables {
7449 self.layout_run_indicators(
7450 line_height,
7451 start_row..end_row,
7452 scroll_pixel_position,
7453 &gutter_dimensions,
7454 &gutter_hitbox,
7455 &rows_with_hunk_bounds,
7456 &snapshot,
7457 window,
7458 cx,
7459 )
7460 } else {
7461 Vec::new()
7462 };
7463
7464 self.layout_signature_help(
7465 &hitbox,
7466 content_origin,
7467 scroll_pixel_position,
7468 newest_selection_head,
7469 start_row,
7470 &line_layouts,
7471 line_height,
7472 em_width,
7473 window,
7474 cx,
7475 );
7476
7477 if !cx.has_active_drag() {
7478 self.layout_hover_popovers(
7479 &snapshot,
7480 &hitbox,
7481 &text_hitbox,
7482 start_row..end_row,
7483 content_origin,
7484 scroll_pixel_position,
7485 &line_layouts,
7486 line_height,
7487 em_width,
7488 window,
7489 cx,
7490 );
7491 }
7492
7493 let inline_completion_popover = self.layout_edit_prediction_popover(
7494 &text_hitbox.bounds,
7495 content_origin,
7496 &snapshot,
7497 start_row..end_row,
7498 scroll_position.y,
7499 scroll_position.y + height_in_lines,
7500 &line_layouts,
7501 line_height,
7502 scroll_pixel_position,
7503 newest_selection_head,
7504 editor_width,
7505 &style,
7506 window,
7507 cx,
7508 );
7509
7510 let mouse_context_menu = self.layout_mouse_context_menu(
7511 &snapshot,
7512 start_row..end_row,
7513 content_origin,
7514 window,
7515 cx,
7516 );
7517
7518 window.with_element_namespace("crease_toggles", |window| {
7519 self.prepaint_crease_toggles(
7520 &mut crease_toggles,
7521 line_height,
7522 &gutter_dimensions,
7523 gutter_settings,
7524 scroll_pixel_position,
7525 &gutter_hitbox,
7526 window,
7527 cx,
7528 )
7529 });
7530
7531 let invisible_symbol_font_size = font_size / 2.;
7532 let tab_invisible = window
7533 .text_system()
7534 .shape_line(
7535 "→".into(),
7536 invisible_symbol_font_size,
7537 &[TextRun {
7538 len: "→".len(),
7539 font: self.style.text.font(),
7540 color: cx.theme().colors().editor_invisible,
7541 background_color: None,
7542 underline: None,
7543 strikethrough: None,
7544 }],
7545 )
7546 .unwrap();
7547 let space_invisible = window
7548 .text_system()
7549 .shape_line(
7550 "•".into(),
7551 invisible_symbol_font_size,
7552 &[TextRun {
7553 len: "•".len(),
7554 font: self.style.text.font(),
7555 color: cx.theme().colors().editor_invisible,
7556 background_color: None,
7557 underline: None,
7558 strikethrough: None,
7559 }],
7560 )
7561 .unwrap();
7562
7563 let mode = snapshot.mode;
7564
7565 let position_map = Rc::new(PositionMap {
7566 size: bounds.size,
7567 visible_row_range,
7568 scroll_pixel_position,
7569 scroll_max,
7570 line_layouts,
7571 line_height,
7572 em_width,
7573 em_advance,
7574 snapshot,
7575 gutter_hitbox: gutter_hitbox.clone(),
7576 text_hitbox: text_hitbox.clone(),
7577 });
7578
7579 self.editor.update(cx, |editor, _| {
7580 editor.last_position_map = Some(position_map.clone())
7581 });
7582
7583 let hunk_controls = self.layout_diff_hunk_controls(
7584 start_row..end_row,
7585 &row_infos,
7586 &text_hitbox,
7587 &position_map,
7588 newest_selection_head,
7589 line_height,
7590 scroll_pixel_position,
7591 &display_hunks,
7592 self.editor.clone(),
7593 window,
7594 cx,
7595 );
7596
7597 EditorLayout {
7598 mode,
7599 position_map,
7600 visible_display_row_range: start_row..end_row,
7601 wrap_guides,
7602 indent_guides,
7603 hitbox,
7604 gutter_hitbox,
7605 display_hunks,
7606 content_origin,
7607 scrollbars_layout,
7608 active_rows,
7609 highlighted_rows,
7610 highlighted_ranges,
7611 highlighted_gutter_ranges,
7612 redacted_ranges,
7613 line_elements,
7614 line_numbers,
7615 blamed_display_rows,
7616 inline_blame,
7617 blocks,
7618 cursors,
7619 visible_cursors,
7620 selections,
7621 inline_completion_popover,
7622 diff_hunk_controls: hunk_controls,
7623 mouse_context_menu,
7624 test_indicators,
7625 code_actions_indicator,
7626 crease_toggles,
7627 crease_trailers,
7628 tab_invisible,
7629 space_invisible,
7630 sticky_buffer_header,
7631 }
7632 })
7633 })
7634 })
7635 }
7636
7637 fn paint(
7638 &mut self,
7639 _: Option<&GlobalElementId>,
7640 bounds: Bounds<gpui::Pixels>,
7641 _: &mut Self::RequestLayoutState,
7642 layout: &mut Self::PrepaintState,
7643 window: &mut Window,
7644 cx: &mut App,
7645 ) {
7646 let focus_handle = self.editor.focus_handle(cx);
7647 let key_context = self
7648 .editor
7649 .update(cx, |editor, cx| editor.key_context(window, cx));
7650
7651 window.set_key_context(key_context);
7652 window.handle_input(
7653 &focus_handle,
7654 ElementInputHandler::new(bounds, self.editor.clone()),
7655 cx,
7656 );
7657 self.register_actions(window, cx);
7658 self.register_key_listeners(window, cx, layout);
7659
7660 let text_style = TextStyleRefinement {
7661 font_size: Some(self.style.text.font_size),
7662 line_height: Some(self.style.text.line_height),
7663 ..Default::default()
7664 };
7665 let rem_size = self.rem_size(cx);
7666 window.with_rem_size(rem_size, |window| {
7667 window.with_text_style(Some(text_style), |window| {
7668 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7669 self.paint_mouse_listeners(layout, window, cx);
7670 self.paint_background(layout, window, cx);
7671 self.paint_indent_guides(layout, window, cx);
7672
7673 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7674 self.paint_blamed_display_rows(layout, window, cx);
7675 self.paint_line_numbers(layout, window, cx);
7676 }
7677
7678 self.paint_text(layout, window, cx);
7679
7680 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7681 self.paint_gutter_highlights(layout, window, cx);
7682 self.paint_gutter_indicators(layout, window, cx);
7683 }
7684
7685 if !layout.blocks.is_empty() {
7686 window.with_element_namespace("blocks", |window| {
7687 self.paint_blocks(layout, window, cx);
7688 });
7689 }
7690
7691 window.with_element_namespace("blocks", |window| {
7692 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7693 sticky_header.paint(window, cx)
7694 }
7695 });
7696
7697 self.paint_scrollbars(layout, window, cx);
7698 self.paint_inline_completion_popover(layout, window, cx);
7699 self.paint_mouse_context_menu(layout, window, cx);
7700 });
7701 })
7702 })
7703 }
7704}
7705
7706pub(super) fn gutter_bounds(
7707 editor_bounds: Bounds<Pixels>,
7708 gutter_dimensions: GutterDimensions,
7709) -> Bounds<Pixels> {
7710 Bounds {
7711 origin: editor_bounds.origin,
7712 size: size(gutter_dimensions.width, editor_bounds.size.height),
7713 }
7714}
7715
7716struct ScrollbarRangeData {
7717 scrollbar_bounds: Bounds<Pixels>,
7718 scroll_range: Bounds<Pixels>,
7719 letter_size: Size<Pixels>,
7720}
7721
7722impl ScrollbarRangeData {
7723 #[allow(clippy::too_many_arguments)]
7724 pub fn new(
7725 scrollbar_bounds: Bounds<Pixels>,
7726 letter_size: Size<Pixels>,
7727 snapshot: &EditorSnapshot,
7728 longest_line_width: Pixels,
7729 longest_line_blame_width: Pixels,
7730 style: &EditorStyle,
7731 editor_width: Pixels,
7732 cx: &mut App,
7733 ) -> ScrollbarRangeData {
7734 // TODO: Simplify this function down, it requires a lot of parameters
7735 let max_row = snapshot.max_point().row();
7736 let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7737
7738 let settings = EditorSettings::get_global(cx);
7739 let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7740 ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7741 ScrollBeyondLastLine::Off => px(1.),
7742 ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7743 };
7744
7745 let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7746 letter_size.width + style.scrollbar_width
7747 } else {
7748 px(0.0)
7749 };
7750
7751 let overscroll = size(
7752 right_margin + longest_line_blame_width,
7753 letter_size.height * scroll_beyond_last_line,
7754 );
7755
7756 let scroll_range = Bounds {
7757 origin: scrollbar_bounds.origin,
7758 size: text_bounds_size + overscroll,
7759 };
7760
7761 ScrollbarRangeData {
7762 scrollbar_bounds,
7763 scroll_range,
7764 letter_size,
7765 }
7766 }
7767}
7768
7769impl IntoElement for EditorElement {
7770 type Element = Self;
7771
7772 fn into_element(self) -> Self::Element {
7773 self
7774 }
7775}
7776
7777pub struct EditorLayout {
7778 position_map: Rc<PositionMap>,
7779 hitbox: Hitbox,
7780 gutter_hitbox: Hitbox,
7781 content_origin: gpui::Point<Pixels>,
7782 scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7783 mode: EditorMode,
7784 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7785 indent_guides: Option<Vec<IndentGuideLayout>>,
7786 visible_display_row_range: Range<DisplayRow>,
7787 active_rows: BTreeMap<DisplayRow, bool>,
7788 highlighted_rows: BTreeMap<DisplayRow, gpui::Background>,
7789 line_elements: SmallVec<[AnyElement; 1]>,
7790 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7791 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7792 blamed_display_rows: Option<Vec<AnyElement>>,
7793 inline_blame: Option<AnyElement>,
7794 blocks: Vec<BlockLayout>,
7795 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7796 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7797 redacted_ranges: Vec<Range<DisplayPoint>>,
7798 cursors: Vec<(DisplayPoint, Hsla)>,
7799 visible_cursors: Vec<CursorLayout>,
7800 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7801 code_actions_indicator: Option<AnyElement>,
7802 test_indicators: Vec<AnyElement>,
7803 crease_toggles: Vec<Option<AnyElement>>,
7804 diff_hunk_controls: Vec<AnyElement>,
7805 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7806 inline_completion_popover: Option<AnyElement>,
7807 mouse_context_menu: Option<AnyElement>,
7808 tab_invisible: ShapedLine,
7809 space_invisible: ShapedLine,
7810 sticky_buffer_header: Option<AnyElement>,
7811}
7812
7813impl EditorLayout {
7814 fn line_end_overshoot(&self) -> Pixels {
7815 0.15 * self.position_map.line_height
7816 }
7817}
7818
7819struct LineNumberLayout {
7820 shaped_line: ShapedLine,
7821 hitbox: Option<Hitbox>,
7822 display_row: DisplayRow,
7823}
7824
7825struct ColoredRange<T> {
7826 start: T,
7827 end: T,
7828 color: Hsla,
7829}
7830
7831#[derive(Clone)]
7832struct ScrollbarLayout {
7833 hitbox: Hitbox,
7834 visible_range: Range<f32>,
7835 visible: bool,
7836 text_unit_size: Pixels,
7837 thumb_size: Pixels,
7838 axis: Axis,
7839}
7840
7841impl ScrollbarLayout {
7842 const BORDER_WIDTH: Pixels = px(1.0);
7843 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7844 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7845 // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7846
7847 fn thumb_bounds(&self) -> Bounds<Pixels> {
7848 match self.axis {
7849 Axis::Vertical => {
7850 let thumb_top = self.y_for_row(self.visible_range.start);
7851 let thumb_bottom = thumb_top + self.thumb_size;
7852 Bounds::from_corners(
7853 point(self.hitbox.left(), thumb_top),
7854 point(self.hitbox.right(), thumb_bottom),
7855 )
7856 }
7857 Axis::Horizontal => {
7858 let thumb_left =
7859 self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7860 let thumb_right = thumb_left + self.thumb_size;
7861 Bounds::from_corners(
7862 point(thumb_left, self.hitbox.top()),
7863 point(thumb_right, self.hitbox.bottom()),
7864 )
7865 }
7866 }
7867 }
7868
7869 fn y_for_row(&self, row: f32) -> Pixels {
7870 self.hitbox.top() + row * self.text_unit_size
7871 }
7872
7873 fn marker_quads_for_ranges(
7874 &self,
7875 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7876 column: Option<usize>,
7877 ) -> Vec<PaintQuad> {
7878 struct MinMax {
7879 min: Pixels,
7880 max: Pixels,
7881 }
7882 let (x_range, height_limit) = if let Some(column) = column {
7883 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7884 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7885 let end = start + column_width;
7886 (
7887 Range { start, end },
7888 MinMax {
7889 min: Self::MIN_MARKER_HEIGHT,
7890 max: px(f32::MAX),
7891 },
7892 )
7893 } else {
7894 (
7895 Range {
7896 start: Self::BORDER_WIDTH,
7897 end: self.hitbox.size.width,
7898 },
7899 MinMax {
7900 min: Self::LINE_MARKER_HEIGHT,
7901 max: Self::LINE_MARKER_HEIGHT,
7902 },
7903 )
7904 };
7905
7906 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7907 let mut pixel_ranges = row_ranges
7908 .into_iter()
7909 .map(|range| {
7910 let start_y = row_to_y(range.start);
7911 let end_y = row_to_y(range.end)
7912 + self
7913 .text_unit_size
7914 .max(height_limit.min)
7915 .min(height_limit.max);
7916 ColoredRange {
7917 start: start_y,
7918 end: end_y,
7919 color: range.color,
7920 }
7921 })
7922 .peekable();
7923
7924 let mut quads = Vec::new();
7925 while let Some(mut pixel_range) = pixel_ranges.next() {
7926 while let Some(next_pixel_range) = pixel_ranges.peek() {
7927 if pixel_range.end >= next_pixel_range.start - px(1.0)
7928 && pixel_range.color == next_pixel_range.color
7929 {
7930 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7931 pixel_ranges.next();
7932 } else {
7933 break;
7934 }
7935 }
7936
7937 let bounds = Bounds::from_corners(
7938 point(x_range.start, pixel_range.start),
7939 point(x_range.end, pixel_range.end),
7940 );
7941 quads.push(quad(
7942 bounds,
7943 Corners::default(),
7944 pixel_range.color,
7945 Edges::default(),
7946 Hsla::transparent_black(),
7947 ));
7948 }
7949
7950 quads
7951 }
7952}
7953
7954struct CreaseTrailerLayout {
7955 element: AnyElement,
7956 bounds: Bounds<Pixels>,
7957}
7958
7959pub(crate) struct PositionMap {
7960 pub size: Size<Pixels>,
7961 pub line_height: Pixels,
7962 pub scroll_pixel_position: gpui::Point<Pixels>,
7963 pub scroll_max: gpui::Point<f32>,
7964 pub em_width: Pixels,
7965 pub em_advance: Pixels,
7966 pub visible_row_range: Range<DisplayRow>,
7967 pub line_layouts: Vec<LineWithInvisibles>,
7968 pub snapshot: EditorSnapshot,
7969 pub text_hitbox: Hitbox,
7970 pub gutter_hitbox: Hitbox,
7971}
7972
7973#[derive(Debug, Copy, Clone)]
7974pub struct PointForPosition {
7975 pub previous_valid: DisplayPoint,
7976 pub next_valid: DisplayPoint,
7977 pub exact_unclipped: DisplayPoint,
7978 pub column_overshoot_after_line_end: u32,
7979}
7980
7981impl PointForPosition {
7982 pub fn as_valid(&self) -> Option<DisplayPoint> {
7983 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
7984 Some(self.previous_valid)
7985 } else {
7986 None
7987 }
7988 }
7989}
7990
7991impl PositionMap {
7992 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
7993 let text_bounds = self.text_hitbox.bounds;
7994 let scroll_position = self.snapshot.scroll_position();
7995 let position = position - text_bounds.origin;
7996 let y = position.y.max(px(0.)).min(self.size.height);
7997 let x = position.x + (scroll_position.x * self.em_width);
7998 let row = ((y / self.line_height) + scroll_position.y) as u32;
7999
8000 let (column, x_overshoot_after_line_end) = if let Some(line) = self
8001 .line_layouts
8002 .get(row as usize - scroll_position.y as usize)
8003 {
8004 if let Some(ix) = line.index_for_x(x) {
8005 (ix as u32, px(0.))
8006 } else {
8007 (line.len as u32, px(0.).max(x - line.width))
8008 }
8009 } else {
8010 (0, x)
8011 };
8012
8013 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8014 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8015 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8016
8017 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8018 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8019 PointForPosition {
8020 previous_valid,
8021 next_valid,
8022 exact_unclipped,
8023 column_overshoot_after_line_end,
8024 }
8025 }
8026}
8027
8028struct BlockLayout {
8029 id: BlockId,
8030 row: Option<DisplayRow>,
8031 element: AnyElement,
8032 available_space: Size<AvailableSpace>,
8033 style: BlockStyle,
8034}
8035
8036fn layout_line(
8037 row: DisplayRow,
8038 snapshot: &EditorSnapshot,
8039 style: &EditorStyle,
8040 text_width: Pixels,
8041 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8042 window: &mut Window,
8043 cx: &mut App,
8044) -> LineWithInvisibles {
8045 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8046 LineWithInvisibles::from_chunks(
8047 chunks,
8048 &style,
8049 MAX_LINE_LEN,
8050 1,
8051 snapshot.mode,
8052 text_width,
8053 is_row_soft_wrapped,
8054 window,
8055 cx,
8056 )
8057 .pop()
8058 .unwrap()
8059}
8060
8061#[derive(Debug)]
8062pub struct IndentGuideLayout {
8063 origin: gpui::Point<Pixels>,
8064 length: Pixels,
8065 single_indent_width: Pixels,
8066 depth: u32,
8067 active: bool,
8068 settings: IndentGuideSettings,
8069}
8070
8071pub struct CursorLayout {
8072 origin: gpui::Point<Pixels>,
8073 block_width: Pixels,
8074 line_height: Pixels,
8075 color: Hsla,
8076 shape: CursorShape,
8077 block_text: Option<ShapedLine>,
8078 cursor_name: Option<AnyElement>,
8079}
8080
8081#[derive(Debug)]
8082pub struct CursorName {
8083 string: SharedString,
8084 color: Hsla,
8085 is_top_row: bool,
8086}
8087
8088impl CursorLayout {
8089 pub fn new(
8090 origin: gpui::Point<Pixels>,
8091 block_width: Pixels,
8092 line_height: Pixels,
8093 color: Hsla,
8094 shape: CursorShape,
8095 block_text: Option<ShapedLine>,
8096 ) -> CursorLayout {
8097 CursorLayout {
8098 origin,
8099 block_width,
8100 line_height,
8101 color,
8102 shape,
8103 block_text,
8104 cursor_name: None,
8105 }
8106 }
8107
8108 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8109 Bounds {
8110 origin: self.origin + origin,
8111 size: size(self.block_width, self.line_height),
8112 }
8113 }
8114
8115 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8116 match self.shape {
8117 CursorShape::Bar => Bounds {
8118 origin: self.origin + origin,
8119 size: size(px(2.0), self.line_height),
8120 },
8121 CursorShape::Block | CursorShape::Hollow => Bounds {
8122 origin: self.origin + origin,
8123 size: size(self.block_width, self.line_height),
8124 },
8125 CursorShape::Underline => Bounds {
8126 origin: self.origin
8127 + origin
8128 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8129 size: size(self.block_width, px(2.0)),
8130 },
8131 }
8132 }
8133
8134 pub fn layout(
8135 &mut self,
8136 origin: gpui::Point<Pixels>,
8137 cursor_name: Option<CursorName>,
8138 window: &mut Window,
8139 cx: &mut App,
8140 ) {
8141 if let Some(cursor_name) = cursor_name {
8142 let bounds = self.bounds(origin);
8143 let text_size = self.line_height / 1.5;
8144
8145 let name_origin = if cursor_name.is_top_row {
8146 point(bounds.right() - px(1.), bounds.top())
8147 } else {
8148 match self.shape {
8149 CursorShape::Bar => point(
8150 bounds.right() - px(2.),
8151 bounds.top() - text_size / 2. - px(1.),
8152 ),
8153 _ => point(
8154 bounds.right() - px(1.),
8155 bounds.top() - text_size / 2. - px(1.),
8156 ),
8157 }
8158 };
8159 let mut name_element = div()
8160 .bg(self.color)
8161 .text_size(text_size)
8162 .px_0p5()
8163 .line_height(text_size + px(2.))
8164 .text_color(cursor_name.color)
8165 .child(cursor_name.string.clone())
8166 .into_any_element();
8167
8168 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8169
8170 self.cursor_name = Some(name_element);
8171 }
8172 }
8173
8174 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8175 let bounds = self.bounds(origin);
8176
8177 //Draw background or border quad
8178 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8179 outline(bounds, self.color)
8180 } else {
8181 fill(bounds, self.color)
8182 };
8183
8184 if let Some(name) = &mut self.cursor_name {
8185 name.paint(window, cx);
8186 }
8187
8188 window.paint_quad(cursor);
8189
8190 if let Some(block_text) = &self.block_text {
8191 block_text
8192 .paint(self.origin + origin, self.line_height, window, cx)
8193 .log_err();
8194 }
8195 }
8196
8197 pub fn shape(&self) -> CursorShape {
8198 self.shape
8199 }
8200}
8201
8202#[derive(Debug)]
8203pub struct HighlightedRange {
8204 pub start_y: Pixels,
8205 pub line_height: Pixels,
8206 pub lines: Vec<HighlightedRangeLine>,
8207 pub color: Hsla,
8208 pub corner_radius: Pixels,
8209}
8210
8211#[derive(Debug)]
8212pub struct HighlightedRangeLine {
8213 pub start_x: Pixels,
8214 pub end_x: Pixels,
8215}
8216
8217impl HighlightedRange {
8218 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8219 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8220 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8221 self.paint_lines(
8222 self.start_y + self.line_height,
8223 &self.lines[1..],
8224 bounds,
8225 window,
8226 );
8227 } else {
8228 self.paint_lines(self.start_y, &self.lines, bounds, window);
8229 }
8230 }
8231
8232 fn paint_lines(
8233 &self,
8234 start_y: Pixels,
8235 lines: &[HighlightedRangeLine],
8236 _bounds: Bounds<Pixels>,
8237 window: &mut Window,
8238 ) {
8239 if lines.is_empty() {
8240 return;
8241 }
8242
8243 let first_line = lines.first().unwrap();
8244 let last_line = lines.last().unwrap();
8245
8246 let first_top_left = point(first_line.start_x, start_y);
8247 let first_top_right = point(first_line.end_x, start_y);
8248
8249 let curve_height = point(Pixels::ZERO, self.corner_radius);
8250 let curve_width = |start_x: Pixels, end_x: Pixels| {
8251 let max = (end_x - start_x) / 2.;
8252 let width = if max < self.corner_radius {
8253 max
8254 } else {
8255 self.corner_radius
8256 };
8257
8258 point(width, Pixels::ZERO)
8259 };
8260
8261 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8262 let mut builder = gpui::PathBuilder::fill();
8263 builder.move_to(first_top_right - top_curve_width);
8264 builder.curve_to(first_top_right + curve_height, first_top_right);
8265
8266 let mut iter = lines.iter().enumerate().peekable();
8267 while let Some((ix, line)) = iter.next() {
8268 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8269
8270 if let Some((_, next_line)) = iter.peek() {
8271 let next_top_right = point(next_line.end_x, bottom_right.y);
8272
8273 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8274 Ordering::Equal => {
8275 builder.line_to(bottom_right);
8276 }
8277 Ordering::Less => {
8278 let curve_width = curve_width(next_top_right.x, bottom_right.x);
8279 builder.line_to(bottom_right - curve_height);
8280 if self.corner_radius > Pixels::ZERO {
8281 builder.curve_to(bottom_right - curve_width, bottom_right);
8282 }
8283 builder.line_to(next_top_right + curve_width);
8284 if self.corner_radius > Pixels::ZERO {
8285 builder.curve_to(next_top_right + curve_height, next_top_right);
8286 }
8287 }
8288 Ordering::Greater => {
8289 let curve_width = curve_width(bottom_right.x, next_top_right.x);
8290 builder.line_to(bottom_right - curve_height);
8291 if self.corner_radius > Pixels::ZERO {
8292 builder.curve_to(bottom_right + curve_width, bottom_right);
8293 }
8294 builder.line_to(next_top_right - curve_width);
8295 if self.corner_radius > Pixels::ZERO {
8296 builder.curve_to(next_top_right + curve_height, next_top_right);
8297 }
8298 }
8299 }
8300 } else {
8301 let curve_width = curve_width(line.start_x, line.end_x);
8302 builder.line_to(bottom_right - curve_height);
8303 if self.corner_radius > Pixels::ZERO {
8304 builder.curve_to(bottom_right - curve_width, bottom_right);
8305 }
8306
8307 let bottom_left = point(line.start_x, bottom_right.y);
8308 builder.line_to(bottom_left + curve_width);
8309 if self.corner_radius > Pixels::ZERO {
8310 builder.curve_to(bottom_left - curve_height, bottom_left);
8311 }
8312 }
8313 }
8314
8315 if first_line.start_x > last_line.start_x {
8316 let curve_width = curve_width(last_line.start_x, first_line.start_x);
8317 let second_top_left = point(last_line.start_x, start_y + self.line_height);
8318 builder.line_to(second_top_left + curve_height);
8319 if self.corner_radius > Pixels::ZERO {
8320 builder.curve_to(second_top_left + curve_width, second_top_left);
8321 }
8322 let first_bottom_left = point(first_line.start_x, second_top_left.y);
8323 builder.line_to(first_bottom_left - curve_width);
8324 if self.corner_radius > Pixels::ZERO {
8325 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8326 }
8327 }
8328
8329 builder.line_to(first_top_left + curve_height);
8330 if self.corner_radius > Pixels::ZERO {
8331 builder.curve_to(first_top_left + top_curve_width, first_top_left);
8332 }
8333 builder.line_to(first_top_right - top_curve_width);
8334
8335 if let Ok(path) = builder.build() {
8336 window.paint_path(path, self.color);
8337 }
8338 }
8339}
8340
8341enum CursorPopoverType {
8342 CodeContextMenu,
8343 EditPrediction,
8344}
8345
8346pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8347 (delta.pow(1.5) / 100.0).into()
8348}
8349
8350fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8351 (delta.pow(1.2) / 300.0).into()
8352}
8353
8354pub fn register_action<T: Action>(
8355 editor: &Entity<Editor>,
8356 window: &mut Window,
8357 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8358) {
8359 let editor = editor.clone();
8360 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8361 let action = action.downcast_ref().unwrap();
8362 if phase == DispatchPhase::Bubble {
8363 editor.update(cx, |editor, cx| {
8364 listener(editor, action, window, cx);
8365 })
8366 }
8367 })
8368}
8369
8370fn compute_auto_height_layout(
8371 editor: &mut Editor,
8372 max_lines: usize,
8373 max_line_number_width: Pixels,
8374 known_dimensions: Size<Option<Pixels>>,
8375 available_width: AvailableSpace,
8376 window: &mut Window,
8377 cx: &mut Context<Editor>,
8378) -> Option<Size<Pixels>> {
8379 let width = known_dimensions.width.or({
8380 if let AvailableSpace::Definite(available_width) = available_width {
8381 Some(available_width)
8382 } else {
8383 None
8384 }
8385 })?;
8386 if let Some(height) = known_dimensions.height {
8387 return Some(size(width, height));
8388 }
8389
8390 let style = editor.style.as_ref().unwrap();
8391 let font_id = window.text_system().resolve_font(&style.text.font());
8392 let font_size = style.text.font_size.to_pixels(window.rem_size());
8393 let line_height = style.text.line_height_in_pixels(window.rem_size());
8394 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8395
8396 let mut snapshot = editor.snapshot(window, cx);
8397 let gutter_dimensions = snapshot
8398 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8399 .unwrap_or_default();
8400
8401 editor.gutter_dimensions = gutter_dimensions;
8402 let text_width = width - gutter_dimensions.width;
8403 let overscroll = size(em_width, px(0.));
8404
8405 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8406 if editor.set_wrap_width(Some(editor_width), cx) {
8407 snapshot = editor.snapshot(window, cx);
8408 }
8409
8410 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8411 let height = scroll_height
8412 .max(line_height)
8413 .min(line_height * max_lines as f32);
8414
8415 Some(size(width, height))
8416}
8417
8418#[cfg(test)]
8419mod tests {
8420 use super::*;
8421 use crate::{
8422 display_map::{BlockPlacement, BlockProperties},
8423 editor_tests::{init_test, update_test_language_settings},
8424 Editor, MultiBuffer,
8425 };
8426 use gpui::{TestAppContext, VisualTestContext};
8427 use language::language_settings;
8428 use log::info;
8429 use similar::DiffableStr;
8430 use std::num::NonZeroU32;
8431 use util::test::sample_text;
8432
8433 #[gpui::test]
8434 fn test_shape_line_numbers(cx: &mut TestAppContext) {
8435 init_test(cx, |_| {});
8436 let window = cx.add_window(|window, cx| {
8437 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8438 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8439 });
8440
8441 let editor = window.root(cx).unwrap();
8442 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8443 let line_height = window
8444 .update(cx, |_, window, _| {
8445 style.text.line_height_in_pixels(window.rem_size())
8446 })
8447 .unwrap();
8448 let element = EditorElement::new(&editor, style);
8449 let snapshot = window
8450 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8451 .unwrap();
8452
8453 let layouts = cx
8454 .update_window(*window, |_, window, cx| {
8455 element.layout_line_numbers(
8456 None,
8457 GutterDimensions {
8458 left_padding: Pixels::ZERO,
8459 right_padding: Pixels::ZERO,
8460 width: px(30.0),
8461 margin: Pixels::ZERO,
8462 git_blame_entries_width: None,
8463 },
8464 line_height,
8465 gpui::Point::default(),
8466 DisplayRow(0)..DisplayRow(6),
8467 &(0..6)
8468 .map(|row| RowInfo {
8469 buffer_row: Some(row),
8470 ..Default::default()
8471 })
8472 .collect::<Vec<_>>(),
8473 Some(DisplayPoint::new(DisplayRow(0), 0)),
8474 &snapshot,
8475 window,
8476 cx,
8477 )
8478 })
8479 .unwrap();
8480 assert_eq!(layouts.len(), 6);
8481
8482 let relative_rows = window
8483 .update(cx, |editor, window, cx| {
8484 let snapshot = editor.snapshot(window, cx);
8485 element.calculate_relative_line_numbers(
8486 &snapshot,
8487 &(DisplayRow(0)..DisplayRow(6)),
8488 Some(DisplayRow(3)),
8489 )
8490 })
8491 .unwrap();
8492 assert_eq!(relative_rows[&DisplayRow(0)], 3);
8493 assert_eq!(relative_rows[&DisplayRow(1)], 2);
8494 assert_eq!(relative_rows[&DisplayRow(2)], 1);
8495 // current line has no relative number
8496 assert_eq!(relative_rows[&DisplayRow(4)], 1);
8497 assert_eq!(relative_rows[&DisplayRow(5)], 2);
8498
8499 // works if cursor is before screen
8500 let relative_rows = window
8501 .update(cx, |editor, window, cx| {
8502 let snapshot = editor.snapshot(window, cx);
8503 element.calculate_relative_line_numbers(
8504 &snapshot,
8505 &(DisplayRow(3)..DisplayRow(6)),
8506 Some(DisplayRow(1)),
8507 )
8508 })
8509 .unwrap();
8510 assert_eq!(relative_rows.len(), 3);
8511 assert_eq!(relative_rows[&DisplayRow(3)], 2);
8512 assert_eq!(relative_rows[&DisplayRow(4)], 3);
8513 assert_eq!(relative_rows[&DisplayRow(5)], 4);
8514
8515 // works if cursor is after screen
8516 let relative_rows = window
8517 .update(cx, |editor, window, cx| {
8518 let snapshot = editor.snapshot(window, cx);
8519 element.calculate_relative_line_numbers(
8520 &snapshot,
8521 &(DisplayRow(0)..DisplayRow(3)),
8522 Some(DisplayRow(6)),
8523 )
8524 })
8525 .unwrap();
8526 assert_eq!(relative_rows.len(), 3);
8527 assert_eq!(relative_rows[&DisplayRow(0)], 5);
8528 assert_eq!(relative_rows[&DisplayRow(1)], 4);
8529 assert_eq!(relative_rows[&DisplayRow(2)], 3);
8530 }
8531
8532 #[gpui::test]
8533 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8534 init_test(cx, |_| {});
8535
8536 let window = cx.add_window(|window, cx| {
8537 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8538 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8539 });
8540 let cx = &mut VisualTestContext::from_window(*window, cx);
8541 let editor = window.root(cx).unwrap();
8542 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8543
8544 window
8545 .update(cx, |editor, window, cx| {
8546 editor.cursor_shape = CursorShape::Block;
8547 editor.change_selections(None, window, cx, |s| {
8548 s.select_ranges([
8549 Point::new(0, 0)..Point::new(1, 0),
8550 Point::new(3, 2)..Point::new(3, 3),
8551 Point::new(5, 6)..Point::new(6, 0),
8552 ]);
8553 });
8554 })
8555 .unwrap();
8556
8557 let (_, state) = cx.draw(
8558 point(px(500.), px(500.)),
8559 size(px(500.), px(500.)),
8560 |_, _| EditorElement::new(&editor, style),
8561 );
8562
8563 assert_eq!(state.selections.len(), 1);
8564 let local_selections = &state.selections[0].1;
8565 assert_eq!(local_selections.len(), 3);
8566 // moves cursor back one line
8567 assert_eq!(
8568 local_selections[0].head,
8569 DisplayPoint::new(DisplayRow(0), 6)
8570 );
8571 assert_eq!(
8572 local_selections[0].range,
8573 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8574 );
8575
8576 // moves cursor back one column
8577 assert_eq!(
8578 local_selections[1].range,
8579 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8580 );
8581 assert_eq!(
8582 local_selections[1].head,
8583 DisplayPoint::new(DisplayRow(3), 2)
8584 );
8585
8586 // leaves cursor on the max point
8587 assert_eq!(
8588 local_selections[2].range,
8589 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8590 );
8591 assert_eq!(
8592 local_selections[2].head,
8593 DisplayPoint::new(DisplayRow(6), 0)
8594 );
8595
8596 // active lines does not include 1 (even though the range of the selection does)
8597 assert_eq!(
8598 state.active_rows.keys().cloned().collect::<Vec<_>>(),
8599 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8600 );
8601
8602 // multi-buffer support
8603 // in DisplayPoint coordinates, this is what we're dealing with:
8604 // 0: [[file
8605 // 1: header
8606 // 2: section]]
8607 // 3: aaaaaa
8608 // 4: bbbbbb
8609 // 5: cccccc
8610 // 6:
8611 // 7: [[footer]]
8612 // 8: [[header]]
8613 // 9: ffffff
8614 // 10: gggggg
8615 // 11: hhhhhh
8616 // 12:
8617 // 13: [[footer]]
8618 // 14: [[file
8619 // 15: header
8620 // 16: section]]
8621 // 17: bbbbbb
8622 // 18: cccccc
8623 // 19: dddddd
8624 // 20: [[footer]]
8625 let window = cx.add_window(|window, cx| {
8626 let buffer = MultiBuffer::build_multi(
8627 [
8628 (
8629 &(sample_text(8, 6, 'a') + "\n"),
8630 vec![
8631 Point::new(0, 0)..Point::new(3, 0),
8632 Point::new(4, 0)..Point::new(7, 0),
8633 ],
8634 ),
8635 (
8636 &(sample_text(8, 6, 'a') + "\n"),
8637 vec![Point::new(1, 0)..Point::new(3, 0)],
8638 ),
8639 ],
8640 cx,
8641 );
8642 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8643 });
8644 let editor = window.root(cx).unwrap();
8645 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8646 let _state = window.update(cx, |editor, window, cx| {
8647 editor.cursor_shape = CursorShape::Block;
8648 editor.change_selections(None, window, cx, |s| {
8649 s.select_display_ranges([
8650 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8651 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8652 ]);
8653 });
8654 });
8655
8656 let (_, state) = cx.draw(
8657 point(px(500.), px(500.)),
8658 size(px(500.), px(500.)),
8659 |_, _| EditorElement::new(&editor, style),
8660 );
8661 assert_eq!(state.selections.len(), 1);
8662 let local_selections = &state.selections[0].1;
8663 assert_eq!(local_selections.len(), 2);
8664
8665 // moves cursor on excerpt boundary back a line
8666 // and doesn't allow selection to bleed through
8667 assert_eq!(
8668 local_selections[0].range,
8669 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8670 );
8671 assert_eq!(
8672 local_selections[0].head,
8673 DisplayPoint::new(DisplayRow(6), 0)
8674 );
8675 // moves cursor on buffer boundary back two lines
8676 // and doesn't allow selection to bleed through
8677 assert_eq!(
8678 local_selections[1].range,
8679 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8680 );
8681 assert_eq!(
8682 local_selections[1].head,
8683 DisplayPoint::new(DisplayRow(12), 0)
8684 );
8685 }
8686
8687 #[gpui::test]
8688 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8689 init_test(cx, |_| {});
8690
8691 let window = cx.add_window(|window, cx| {
8692 let buffer = MultiBuffer::build_simple("", cx);
8693 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8694 });
8695 let cx = &mut VisualTestContext::from_window(*window, cx);
8696 let editor = window.root(cx).unwrap();
8697 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8698 window
8699 .update(cx, |editor, window, cx| {
8700 editor.set_placeholder_text("hello", cx);
8701 editor.insert_blocks(
8702 [BlockProperties {
8703 style: BlockStyle::Fixed,
8704 placement: BlockPlacement::Above(Anchor::min()),
8705 height: 3,
8706 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8707 priority: 0,
8708 }],
8709 None,
8710 cx,
8711 );
8712
8713 // Blur the editor so that it displays placeholder text.
8714 window.blur();
8715 })
8716 .unwrap();
8717
8718 let (_, state) = cx.draw(
8719 point(px(500.), px(500.)),
8720 size(px(500.), px(500.)),
8721 |_, _| EditorElement::new(&editor, style),
8722 );
8723 assert_eq!(state.position_map.line_layouts.len(), 4);
8724 assert_eq!(state.line_numbers.len(), 1);
8725 assert_eq!(
8726 state
8727 .line_numbers
8728 .get(&MultiBufferRow(0))
8729 .and_then(|line_number| line_number.shaped_line.text.as_str()),
8730 Some("1")
8731 );
8732 }
8733
8734 #[gpui::test]
8735 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8736 const TAB_SIZE: u32 = 4;
8737
8738 let input_text = "\t \t|\t| a b";
8739 let expected_invisibles = vec![
8740 Invisible::Tab {
8741 line_start_offset: 0,
8742 line_end_offset: TAB_SIZE as usize,
8743 },
8744 Invisible::Whitespace {
8745 line_offset: TAB_SIZE as usize,
8746 },
8747 Invisible::Tab {
8748 line_start_offset: TAB_SIZE as usize + 1,
8749 line_end_offset: TAB_SIZE as usize * 2,
8750 },
8751 Invisible::Tab {
8752 line_start_offset: TAB_SIZE as usize * 2 + 1,
8753 line_end_offset: TAB_SIZE as usize * 3,
8754 },
8755 Invisible::Whitespace {
8756 line_offset: TAB_SIZE as usize * 3 + 1,
8757 },
8758 Invisible::Whitespace {
8759 line_offset: TAB_SIZE as usize * 3 + 3,
8760 },
8761 ];
8762 assert_eq!(
8763 expected_invisibles.len(),
8764 input_text
8765 .chars()
8766 .filter(|initial_char| initial_char.is_whitespace())
8767 .count(),
8768 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8769 );
8770
8771 for show_line_numbers in [true, false] {
8772 init_test(cx, |s| {
8773 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8774 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8775 });
8776
8777 let actual_invisibles = collect_invisibles_from_new_editor(
8778 cx,
8779 EditorMode::Full,
8780 input_text,
8781 px(500.0),
8782 show_line_numbers,
8783 );
8784
8785 assert_eq!(expected_invisibles, actual_invisibles);
8786 }
8787 }
8788
8789 #[gpui::test]
8790 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8791 init_test(cx, |s| {
8792 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8793 s.defaults.tab_size = NonZeroU32::new(4);
8794 });
8795
8796 for editor_mode_without_invisibles in [
8797 EditorMode::SingleLine { auto_width: false },
8798 EditorMode::AutoHeight { max_lines: 100 },
8799 ] {
8800 for show_line_numbers in [true, false] {
8801 let invisibles = collect_invisibles_from_new_editor(
8802 cx,
8803 editor_mode_without_invisibles,
8804 "\t\t\t| | a b",
8805 px(500.0),
8806 show_line_numbers,
8807 );
8808 assert!(invisibles.is_empty(),
8809 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8810 }
8811 }
8812 }
8813
8814 #[gpui::test]
8815 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8816 let tab_size = 4;
8817 let input_text = "a\tbcd ".repeat(9);
8818 let repeated_invisibles = [
8819 Invisible::Tab {
8820 line_start_offset: 1,
8821 line_end_offset: tab_size as usize,
8822 },
8823 Invisible::Whitespace {
8824 line_offset: tab_size as usize + 3,
8825 },
8826 Invisible::Whitespace {
8827 line_offset: tab_size as usize + 4,
8828 },
8829 Invisible::Whitespace {
8830 line_offset: tab_size as usize + 5,
8831 },
8832 Invisible::Whitespace {
8833 line_offset: tab_size as usize + 6,
8834 },
8835 Invisible::Whitespace {
8836 line_offset: tab_size as usize + 7,
8837 },
8838 ];
8839 let expected_invisibles = std::iter::once(repeated_invisibles)
8840 .cycle()
8841 .take(9)
8842 .flatten()
8843 .collect::<Vec<_>>();
8844 assert_eq!(
8845 expected_invisibles.len(),
8846 input_text
8847 .chars()
8848 .filter(|initial_char| initial_char.is_whitespace())
8849 .count(),
8850 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8851 );
8852 info!("Expected invisibles: {expected_invisibles:?}");
8853
8854 init_test(cx, |_| {});
8855
8856 // Put the same string with repeating whitespace pattern into editors of various size,
8857 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8858 let resize_step = 10.0;
8859 let mut editor_width = 200.0;
8860 while editor_width <= 1000.0 {
8861 for show_line_numbers in [true, false] {
8862 update_test_language_settings(cx, |s| {
8863 s.defaults.tab_size = NonZeroU32::new(tab_size);
8864 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8865 s.defaults.preferred_line_length = Some(editor_width as u32);
8866 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8867 });
8868
8869 let actual_invisibles = collect_invisibles_from_new_editor(
8870 cx,
8871 EditorMode::Full,
8872 &input_text,
8873 px(editor_width),
8874 show_line_numbers,
8875 );
8876
8877 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8878 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8879 let mut i = 0;
8880 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8881 i = actual_index;
8882 match expected_invisibles.get(i) {
8883 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8884 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8885 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8886 _ => {
8887 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8888 }
8889 },
8890 None => {
8891 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8892 }
8893 }
8894 }
8895 let missing_expected_invisibles = &expected_invisibles[i + 1..];
8896 assert!(
8897 missing_expected_invisibles.is_empty(),
8898 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8899 );
8900
8901 editor_width += resize_step;
8902 }
8903 }
8904 }
8905
8906 fn collect_invisibles_from_new_editor(
8907 cx: &mut TestAppContext,
8908 editor_mode: EditorMode,
8909 input_text: &str,
8910 editor_width: Pixels,
8911 show_line_numbers: bool,
8912 ) -> Vec<Invisible> {
8913 info!(
8914 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8915 editor_width.0
8916 );
8917 let window = cx.add_window(|window, cx| {
8918 let buffer = MultiBuffer::build_simple(input_text, cx);
8919 Editor::new(editor_mode, buffer, None, true, window, cx)
8920 });
8921 let cx = &mut VisualTestContext::from_window(*window, cx);
8922 let editor = window.root(cx).unwrap();
8923
8924 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8925 window
8926 .update(cx, |editor, _, cx| {
8927 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8928 editor.set_wrap_width(Some(editor_width), cx);
8929 editor.set_show_line_numbers(show_line_numbers, cx);
8930 })
8931 .unwrap();
8932 let (_, state) = cx.draw(
8933 point(px(500.), px(500.)),
8934 size(px(500.), px(500.)),
8935 |_, _| EditorElement::new(&editor, style),
8936 );
8937 state
8938 .position_map
8939 .line_layouts
8940 .iter()
8941 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8942 .cloned()
8943 .collect()
8944 }
8945}
8946
8947fn diff_hunk_controls(
8948 row: u32,
8949 hunk_range: Range<Anchor>,
8950 line_height: Pixels,
8951 editor: &Entity<Editor>,
8952 cx: &mut App,
8953) -> AnyElement {
8954 h_flex()
8955 .h(line_height)
8956 .mr_1()
8957 .gap_1()
8958 .px_1()
8959 .pb_1()
8960 .border_b_1()
8961 .border_color(cx.theme().colors().border_variant)
8962 .rounded_b_lg()
8963 .bg(cx.theme().colors().editor_background)
8964 .gap_1()
8965 .child(
8966 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
8967 .shape(IconButtonShape::Square)
8968 .icon_size(IconSize::Small)
8969 // .disabled(!has_multiple_hunks)
8970 .tooltip({
8971 let focus_handle = editor.focus_handle(cx);
8972 move |window, cx| {
8973 Tooltip::for_action_in("Next Hunk", &GoToHunk, &focus_handle, window, cx)
8974 }
8975 })
8976 .on_click({
8977 let editor = editor.clone();
8978 move |_event, window, cx| {
8979 editor.update(cx, |editor, cx| {
8980 let snapshot = editor.snapshot(window, cx);
8981 let position = hunk_range.end.to_point(&snapshot.buffer_snapshot);
8982 editor.go_to_hunk_after_position(&snapshot, position, window, cx);
8983 editor.expand_selected_diff_hunks(cx);
8984 });
8985 }
8986 }),
8987 )
8988 .child(
8989 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
8990 .shape(IconButtonShape::Square)
8991 .icon_size(IconSize::Small)
8992 // .disabled(!has_multiple_hunks)
8993 .tooltip({
8994 let focus_handle = editor.focus_handle(cx);
8995 move |window, cx| {
8996 Tooltip::for_action_in(
8997 "Previous Hunk",
8998 &GoToPrevHunk,
8999 &focus_handle,
9000 window,
9001 cx,
9002 )
9003 }
9004 })
9005 .on_click({
9006 let editor = editor.clone();
9007 move |_event, window, cx| {
9008 editor.update(cx, |editor, cx| {
9009 let snapshot = editor.snapshot(window, cx);
9010 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9011 editor.go_to_hunk_before_position(&snapshot, point, window, cx);
9012 editor.expand_selected_diff_hunks(cx);
9013 });
9014 }
9015 }),
9016 )
9017 .child(
9018 IconButton::new("discard", IconName::Undo)
9019 .shape(IconButtonShape::Square)
9020 .icon_size(IconSize::Small)
9021 .tooltip({
9022 let focus_handle = editor.focus_handle(cx);
9023 move |window, cx| {
9024 Tooltip::for_action_in(
9025 "Discard Hunk",
9026 &RevertSelectedHunks,
9027 &focus_handle,
9028 window,
9029 cx,
9030 )
9031 }
9032 })
9033 .on_click({
9034 let editor = editor.clone();
9035 move |_event, window, cx| {
9036 editor.update(cx, |editor, cx| {
9037 let snapshot = editor.snapshot(window, cx);
9038 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
9039 editor.revert_hunks_in_ranges([point..point].into_iter(), window, cx);
9040 });
9041 }
9042 }),
9043 )
9044 .into_any_element()
9045}