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