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