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