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