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, Some(&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, Some(&hitbox));
5162 } else {
5163 window.set_cursor_style(CursorStyle::PointingHand, Some(&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, Some(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_cursor_style(CursorStyle::None, 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 Some(&layout.position_map.text_hitbox),
5464 );
5465 } else {
5466 window.set_cursor_style(
5467 CursorStyle::IBeam,
5468 Some(&layout.position_map.text_hitbox),
5469 );
5470 };
5471
5472 self.paint_lines_background(layout, window, cx);
5473 let invisible_display_ranges = self.paint_highlights(layout, window);
5474 self.paint_lines(&invisible_display_ranges, layout, window, cx);
5475 self.paint_redactions(layout, window);
5476 self.paint_cursors(layout, window, cx);
5477 self.paint_inline_diagnostics(layout, window, cx);
5478 self.paint_inline_blame(layout, window, cx);
5479 self.paint_inline_code_actions(layout, window, cx);
5480 self.paint_diff_hunk_controls(layout, window, cx);
5481 window.with_element_namespace("crease_trailers", |window| {
5482 for trailer in layout.crease_trailers.iter_mut().flatten() {
5483 trailer.element.paint(window, cx);
5484 }
5485 });
5486 },
5487 )
5488 }
5489
5490 fn paint_highlights(
5491 &mut self,
5492 layout: &mut EditorLayout,
5493 window: &mut Window,
5494 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
5495 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5496 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
5497 let line_end_overshoot = 0.15 * layout.position_map.line_height;
5498 for (range, color) in &layout.highlighted_ranges {
5499 self.paint_highlighted_range(
5500 range.clone(),
5501 *color,
5502 Pixels::ZERO,
5503 line_end_overshoot,
5504 layout,
5505 window,
5506 );
5507 }
5508
5509 let corner_radius = 0.15 * layout.position_map.line_height;
5510
5511 for (player_color, selections) in &layout.selections {
5512 for selection in selections.iter() {
5513 self.paint_highlighted_range(
5514 selection.range.clone(),
5515 player_color.selection,
5516 corner_radius,
5517 corner_radius * 2.,
5518 layout,
5519 window,
5520 );
5521
5522 if selection.is_local && !selection.range.is_empty() {
5523 invisible_display_ranges.push(selection.range.clone());
5524 }
5525 }
5526 }
5527 invisible_display_ranges
5528 })
5529 }
5530
5531 fn paint_lines(
5532 &mut self,
5533 invisible_display_ranges: &[Range<DisplayPoint>],
5534 layout: &mut EditorLayout,
5535 window: &mut Window,
5536 cx: &mut App,
5537 ) {
5538 let whitespace_setting = self
5539 .editor
5540 .read(cx)
5541 .buffer
5542 .read(cx)
5543 .language_settings(cx)
5544 .show_whitespaces;
5545
5546 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5547 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5548 line_with_invisibles.draw(
5549 layout,
5550 row,
5551 layout.content_origin,
5552 whitespace_setting,
5553 invisible_display_ranges,
5554 window,
5555 cx,
5556 )
5557 }
5558
5559 for line_element in &mut layout.line_elements {
5560 line_element.paint(window, cx);
5561 }
5562 }
5563
5564 fn paint_lines_background(
5565 &mut self,
5566 layout: &mut EditorLayout,
5567 window: &mut Window,
5568 cx: &mut App,
5569 ) {
5570 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5571 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5572 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
5573 }
5574 }
5575
5576 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
5577 if layout.redacted_ranges.is_empty() {
5578 return;
5579 }
5580
5581 let line_end_overshoot = layout.line_end_overshoot();
5582
5583 // A softer than perfect black
5584 let redaction_color = gpui::rgb(0x0e1111);
5585
5586 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5587 for range in layout.redacted_ranges.iter() {
5588 self.paint_highlighted_range(
5589 range.clone(),
5590 redaction_color.into(),
5591 Pixels::ZERO,
5592 line_end_overshoot,
5593 layout,
5594 window,
5595 );
5596 }
5597 });
5598 }
5599
5600 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5601 for cursor in &mut layout.visible_cursors {
5602 cursor.paint(layout.content_origin, window, cx);
5603 }
5604 }
5605
5606 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5607 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
5608 return;
5609 };
5610
5611 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
5612 let hitbox = &scrollbar_layout.hitbox;
5613 if scrollbars_layout.visible {
5614 let scrollbar_edges = match axis {
5615 ScrollbarAxis::Horizontal => Edges {
5616 top: Pixels::ZERO,
5617 right: Pixels::ZERO,
5618 bottom: Pixels::ZERO,
5619 left: Pixels::ZERO,
5620 },
5621 ScrollbarAxis::Vertical => Edges {
5622 top: Pixels::ZERO,
5623 right: Pixels::ZERO,
5624 bottom: Pixels::ZERO,
5625 left: ScrollbarLayout::BORDER_WIDTH,
5626 },
5627 };
5628
5629 window.paint_layer(hitbox.bounds, |window| {
5630 window.paint_quad(quad(
5631 hitbox.bounds,
5632 Corners::default(),
5633 cx.theme().colors().scrollbar_track_background,
5634 scrollbar_edges,
5635 cx.theme().colors().scrollbar_track_border,
5636 BorderStyle::Solid,
5637 ));
5638
5639 if axis == ScrollbarAxis::Vertical {
5640 let fast_markers =
5641 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5642 // Refresh slow scrollbar markers in the background. Below, we
5643 // paint whatever markers have already been computed.
5644 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5645
5646 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5647 for marker in markers.iter().chain(&fast_markers) {
5648 let mut marker = marker.clone();
5649 marker.bounds.origin += hitbox.origin;
5650 window.paint_quad(marker);
5651 }
5652 }
5653
5654 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
5655 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
5656 ScrollbarThumbState::Dragging => {
5657 cx.theme().colors().scrollbar_thumb_active_background
5658 }
5659 ScrollbarThumbState::Hovered => {
5660 cx.theme().colors().scrollbar_thumb_hover_background
5661 }
5662 ScrollbarThumbState::Idle => {
5663 cx.theme().colors().scrollbar_thumb_background
5664 }
5665 };
5666 window.paint_quad(quad(
5667 thumb_bounds,
5668 Corners::default(),
5669 scrollbar_thumb_color,
5670 scrollbar_edges,
5671 cx.theme().colors().scrollbar_thumb_border,
5672 BorderStyle::Solid,
5673 ));
5674
5675 window.set_cursor_style(CursorStyle::Arrow, Some(&hitbox));
5676 }
5677 })
5678 }
5679 }
5680
5681 window.on_mouse_event({
5682 let editor = self.editor.clone();
5683 let scrollbars_layout = scrollbars_layout.clone();
5684
5685 let mut mouse_position = window.mouse_position();
5686 move |event: &MouseMoveEvent, phase, window, cx| {
5687 if phase == DispatchPhase::Capture {
5688 return;
5689 }
5690
5691 editor.update(cx, |editor, cx| {
5692 if let Some((scrollbar_layout, axis)) = event
5693 .pressed_button
5694 .filter(|button| *button == MouseButton::Left)
5695 .and(editor.scroll_manager.dragging_scrollbar_axis())
5696 .and_then(|axis| {
5697 scrollbars_layout
5698 .iter_scrollbars()
5699 .find(|(_, a)| *a == axis)
5700 })
5701 {
5702 let ScrollbarLayout {
5703 hitbox,
5704 text_unit_size,
5705 ..
5706 } = scrollbar_layout;
5707
5708 let old_position = mouse_position.along(axis);
5709 let new_position = event.position.along(axis);
5710 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
5711 .contains(&old_position)
5712 {
5713 let position = editor.scroll_position(cx).apply_along(axis, |p| {
5714 (p + (new_position - old_position) / *text_unit_size).max(0.)
5715 });
5716 editor.set_scroll_position(position, window, cx);
5717 }
5718
5719 editor.scroll_manager.show_scrollbars(window, cx);
5720 cx.stop_propagation();
5721 } else if let Some((layout, axis)) = scrollbars_layout
5722 .get_hovered_axis(window)
5723 .filter(|_| !event.dragging())
5724 {
5725 if layout.thumb_hovered(&event.position) {
5726 editor
5727 .scroll_manager
5728 .set_hovered_scroll_thumb_axis(axis, cx);
5729 } else {
5730 editor.scroll_manager.reset_scrollbar_state(cx);
5731 }
5732
5733 editor.scroll_manager.show_scrollbars(window, cx);
5734 } else {
5735 editor.scroll_manager.reset_scrollbar_state(cx);
5736 }
5737
5738 mouse_position = event.position;
5739 })
5740 }
5741 });
5742
5743 if self.editor.read(cx).scroll_manager.any_scrollbar_dragged() {
5744 window.on_mouse_event({
5745 let editor = self.editor.clone();
5746 move |_: &MouseUpEvent, phase, window, cx| {
5747 if phase == DispatchPhase::Capture {
5748 return;
5749 }
5750
5751 editor.update(cx, |editor, cx| {
5752 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
5753 editor
5754 .scroll_manager
5755 .set_hovered_scroll_thumb_axis(axis, cx);
5756 } else {
5757 editor.scroll_manager.reset_scrollbar_state(cx);
5758 }
5759 cx.stop_propagation();
5760 });
5761 }
5762 });
5763 } else {
5764 window.on_mouse_event({
5765 let editor = self.editor.clone();
5766
5767 move |event: &MouseDownEvent, phase, window, cx| {
5768 if phase == DispatchPhase::Capture {
5769 return;
5770 }
5771 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
5772 else {
5773 return;
5774 };
5775
5776 let ScrollbarLayout {
5777 hitbox,
5778 visible_range,
5779 text_unit_size,
5780 thumb_bounds,
5781 ..
5782 } = scrollbar_layout;
5783
5784 let Some(thumb_bounds) = thumb_bounds else {
5785 return;
5786 };
5787
5788 editor.update(cx, |editor, cx| {
5789 editor
5790 .scroll_manager
5791 .set_dragged_scroll_thumb_axis(axis, cx);
5792
5793 let event_position = event.position.along(axis);
5794
5795 if event_position < thumb_bounds.origin.along(axis)
5796 || thumb_bounds.bottom_right().along(axis) < event_position
5797 {
5798 let center_position = ((event_position - hitbox.origin.along(axis))
5799 / *text_unit_size)
5800 .round() as u32;
5801 let start_position = center_position.saturating_sub(
5802 (visible_range.end - visible_range.start) as u32 / 2,
5803 );
5804
5805 let position = editor
5806 .scroll_position(cx)
5807 .apply_along(axis, |_| start_position as f32);
5808
5809 editor.set_scroll_position(position, window, cx);
5810 } else {
5811 editor.scroll_manager.show_scrollbars(window, cx);
5812 }
5813
5814 cx.stop_propagation();
5815 });
5816 }
5817 });
5818 }
5819 }
5820
5821 fn collect_fast_scrollbar_markers(
5822 &self,
5823 layout: &EditorLayout,
5824 scrollbar_layout: &ScrollbarLayout,
5825 cx: &mut App,
5826 ) -> Vec<PaintQuad> {
5827 const LIMIT: usize = 100;
5828 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5829 return vec![];
5830 }
5831 let cursor_ranges = layout
5832 .cursors
5833 .iter()
5834 .map(|(point, color)| ColoredRange {
5835 start: point.row(),
5836 end: point.row(),
5837 color: *color,
5838 })
5839 .collect_vec();
5840 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5841 }
5842
5843 fn refresh_slow_scrollbar_markers(
5844 &self,
5845 layout: &EditorLayout,
5846 scrollbar_layout: &ScrollbarLayout,
5847 window: &mut Window,
5848 cx: &mut App,
5849 ) {
5850 self.editor.update(cx, |editor, cx| {
5851 if !editor.is_singleton(cx)
5852 || !editor
5853 .scrollbar_marker_state
5854 .should_refresh(scrollbar_layout.hitbox.size)
5855 {
5856 return;
5857 }
5858
5859 let scrollbar_layout = scrollbar_layout.clone();
5860 let background_highlights = editor.background_highlights.clone();
5861 let snapshot = layout.position_map.snapshot.clone();
5862 let theme = cx.theme().clone();
5863 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5864
5865 editor.scrollbar_marker_state.dirty = false;
5866 editor.scrollbar_marker_state.pending_refresh =
5867 Some(cx.spawn_in(window, async move |editor, cx| {
5868 let scrollbar_size = scrollbar_layout.hitbox.size;
5869 let scrollbar_markers = cx
5870 .background_spawn(async move {
5871 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5872 let mut marker_quads = Vec::new();
5873 if scrollbar_settings.git_diff {
5874 let marker_row_ranges =
5875 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5876 let start_display_row =
5877 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5878 .to_display_point(&snapshot.display_snapshot)
5879 .row();
5880 let mut end_display_row =
5881 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5882 .to_display_point(&snapshot.display_snapshot)
5883 .row();
5884 if end_display_row != start_display_row {
5885 end_display_row.0 -= 1;
5886 }
5887 let color = match &hunk.status().kind {
5888 DiffHunkStatusKind::Added => {
5889 theme.colors().version_control_added
5890 }
5891 DiffHunkStatusKind::Modified => {
5892 theme.colors().version_control_modified
5893 }
5894 DiffHunkStatusKind::Deleted => {
5895 theme.colors().version_control_deleted
5896 }
5897 };
5898 ColoredRange {
5899 start: start_display_row,
5900 end: end_display_row,
5901 color,
5902 }
5903 });
5904
5905 marker_quads.extend(
5906 scrollbar_layout
5907 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5908 );
5909 }
5910
5911 for (background_highlight_id, (_, background_ranges)) in
5912 background_highlights.iter()
5913 {
5914 let is_search_highlights = *background_highlight_id
5915 == TypeId::of::<BufferSearchHighlights>();
5916 let is_text_highlights = *background_highlight_id
5917 == TypeId::of::<SelectedTextHighlight>();
5918 let is_symbol_occurrences = *background_highlight_id
5919 == TypeId::of::<DocumentHighlightRead>()
5920 || *background_highlight_id
5921 == TypeId::of::<DocumentHighlightWrite>();
5922 if (is_search_highlights && scrollbar_settings.search_results)
5923 || (is_text_highlights && scrollbar_settings.selected_text)
5924 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5925 {
5926 let mut color = theme.status().info;
5927 if is_symbol_occurrences {
5928 color.fade_out(0.5);
5929 }
5930 let marker_row_ranges = background_ranges.iter().map(|range| {
5931 let display_start = range
5932 .start
5933 .to_display_point(&snapshot.display_snapshot);
5934 let display_end =
5935 range.end.to_display_point(&snapshot.display_snapshot);
5936 ColoredRange {
5937 start: display_start.row(),
5938 end: display_end.row(),
5939 color,
5940 }
5941 });
5942 marker_quads.extend(
5943 scrollbar_layout
5944 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5945 );
5946 }
5947 }
5948
5949 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5950 let diagnostics = snapshot
5951 .buffer_snapshot
5952 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5953 // Don't show diagnostics the user doesn't care about
5954 .filter(|diagnostic| {
5955 match (
5956 scrollbar_settings.diagnostics,
5957 diagnostic.diagnostic.severity,
5958 ) {
5959 (ScrollbarDiagnostics::All, _) => true,
5960 (
5961 ScrollbarDiagnostics::Error,
5962 lsp::DiagnosticSeverity::ERROR,
5963 ) => true,
5964 (
5965 ScrollbarDiagnostics::Warning,
5966 lsp::DiagnosticSeverity::ERROR
5967 | lsp::DiagnosticSeverity::WARNING,
5968 ) => true,
5969 (
5970 ScrollbarDiagnostics::Information,
5971 lsp::DiagnosticSeverity::ERROR
5972 | lsp::DiagnosticSeverity::WARNING
5973 | lsp::DiagnosticSeverity::INFORMATION,
5974 ) => true,
5975 (_, _) => false,
5976 }
5977 })
5978 // We want to sort by severity, in order to paint the most severe diagnostics last.
5979 .sorted_by_key(|diagnostic| {
5980 std::cmp::Reverse(diagnostic.diagnostic.severity)
5981 });
5982
5983 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5984 let start_display = diagnostic
5985 .range
5986 .start
5987 .to_display_point(&snapshot.display_snapshot);
5988 let end_display = diagnostic
5989 .range
5990 .end
5991 .to_display_point(&snapshot.display_snapshot);
5992 let color = match diagnostic.diagnostic.severity {
5993 lsp::DiagnosticSeverity::ERROR => theme.status().error,
5994 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
5995 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
5996 _ => theme.status().hint,
5997 };
5998 ColoredRange {
5999 start: start_display.row(),
6000 end: end_display.row(),
6001 color,
6002 }
6003 });
6004 marker_quads.extend(
6005 scrollbar_layout
6006 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
6007 );
6008 }
6009
6010 Arc::from(marker_quads)
6011 })
6012 .await;
6013
6014 editor.update(cx, |editor, cx| {
6015 editor.scrollbar_marker_state.markers = scrollbar_markers;
6016 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
6017 editor.scrollbar_marker_state.pending_refresh = None;
6018 cx.notify();
6019 })?;
6020
6021 Ok(())
6022 }));
6023 });
6024 }
6025
6026 fn paint_highlighted_range(
6027 &self,
6028 range: Range<DisplayPoint>,
6029 color: Hsla,
6030 corner_radius: Pixels,
6031 line_end_overshoot: Pixels,
6032 layout: &EditorLayout,
6033 window: &mut Window,
6034 ) {
6035 let start_row = layout.visible_display_row_range.start;
6036 let end_row = layout.visible_display_row_range.end;
6037 if range.start != range.end {
6038 let row_range = if range.end.column() == 0 {
6039 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
6040 } else {
6041 cmp::max(range.start.row(), start_row)
6042 ..cmp::min(range.end.row().next_row(), end_row)
6043 };
6044
6045 let highlighted_range = HighlightedRange {
6046 color,
6047 line_height: layout.position_map.line_height,
6048 corner_radius,
6049 start_y: layout.content_origin.y
6050 + row_range.start.as_f32() * layout.position_map.line_height
6051 - layout.position_map.scroll_pixel_position.y,
6052 lines: row_range
6053 .iter_rows()
6054 .map(|row| {
6055 let line_layout =
6056 &layout.position_map.line_layouts[row.minus(start_row) as usize];
6057 HighlightedRangeLine {
6058 start_x: if row == range.start.row() {
6059 layout.content_origin.x
6060 + line_layout.x_for_index(range.start.column() as usize)
6061 - layout.position_map.scroll_pixel_position.x
6062 } else {
6063 layout.content_origin.x
6064 - layout.position_map.scroll_pixel_position.x
6065 },
6066 end_x: if row == range.end.row() {
6067 layout.content_origin.x
6068 + line_layout.x_for_index(range.end.column() as usize)
6069 - layout.position_map.scroll_pixel_position.x
6070 } else {
6071 layout.content_origin.x + line_layout.width + line_end_overshoot
6072 - layout.position_map.scroll_pixel_position.x
6073 },
6074 }
6075 })
6076 .collect(),
6077 };
6078
6079 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
6080 }
6081 }
6082
6083 fn paint_inline_diagnostics(
6084 &mut self,
6085 layout: &mut EditorLayout,
6086 window: &mut Window,
6087 cx: &mut App,
6088 ) {
6089 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
6090 inline_diagnostic.1.paint(window, cx);
6091 }
6092 }
6093
6094 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6095 if let Some(mut inline_blame) = layout.inline_blame.take() {
6096 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6097 inline_blame.paint(window, cx);
6098 })
6099 }
6100 }
6101
6102 fn paint_inline_code_actions(
6103 &mut self,
6104 layout: &mut EditorLayout,
6105 window: &mut Window,
6106 cx: &mut App,
6107 ) {
6108 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
6109 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6110 inline_code_actions.paint(window, cx);
6111 })
6112 }
6113 }
6114
6115 fn paint_diff_hunk_controls(
6116 &mut self,
6117 layout: &mut EditorLayout,
6118 window: &mut Window,
6119 cx: &mut App,
6120 ) {
6121 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
6122 diff_hunk_control.paint(window, cx);
6123 }
6124 }
6125
6126 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6127 if let Some(mut layout) = layout.minimap.take() {
6128 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
6129
6130 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
6131 window.with_element_namespace("minimap", |window| {
6132 layout.minimap.paint(window, cx);
6133 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
6134 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
6135 ScrollbarThumbState::Idle => {
6136 cx.theme().colors().minimap_thumb_background
6137 }
6138 ScrollbarThumbState::Hovered => {
6139 cx.theme().colors().minimap_thumb_hover_background
6140 }
6141 ScrollbarThumbState::Dragging => {
6142 cx.theme().colors().minimap_thumb_active_background
6143 }
6144 };
6145 let minimap_thumb_border = match layout.thumb_border_style {
6146 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
6147 MinimapThumbBorder::LeftOnly => Edges {
6148 left: ScrollbarLayout::BORDER_WIDTH,
6149 ..Default::default()
6150 },
6151 MinimapThumbBorder::LeftOpen => Edges {
6152 right: ScrollbarLayout::BORDER_WIDTH,
6153 top: ScrollbarLayout::BORDER_WIDTH,
6154 bottom: ScrollbarLayout::BORDER_WIDTH,
6155 ..Default::default()
6156 },
6157 MinimapThumbBorder::RightOpen => Edges {
6158 left: ScrollbarLayout::BORDER_WIDTH,
6159 top: ScrollbarLayout::BORDER_WIDTH,
6160 bottom: ScrollbarLayout::BORDER_WIDTH,
6161 ..Default::default()
6162 },
6163 MinimapThumbBorder::None => Default::default(),
6164 };
6165
6166 window.paint_layer(minimap_hitbox.bounds, |window| {
6167 window.paint_quad(quad(
6168 thumb_bounds,
6169 Corners::default(),
6170 minimap_thumb_color,
6171 minimap_thumb_border,
6172 cx.theme().colors().minimap_thumb_border,
6173 BorderStyle::Solid,
6174 ));
6175 });
6176 }
6177 });
6178 });
6179
6180 window.set_cursor_style(CursorStyle::Arrow, Some(&minimap_hitbox));
6181
6182 let minimap_axis = ScrollbarAxis::Vertical;
6183 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
6184 .min(layout.minimap_line_height);
6185
6186 let mut mouse_position = window.mouse_position();
6187
6188 window.on_mouse_event({
6189 let editor = self.editor.clone();
6190
6191 let minimap_hitbox = minimap_hitbox.clone();
6192
6193 move |event: &MouseMoveEvent, phase, window, cx| {
6194 if phase == DispatchPhase::Capture {
6195 return;
6196 }
6197
6198 editor.update(cx, |editor, cx| {
6199 if event.pressed_button == Some(MouseButton::Left)
6200 && editor.scroll_manager.is_dragging_minimap()
6201 {
6202 let old_position = mouse_position.along(minimap_axis);
6203 let new_position = event.position.along(minimap_axis);
6204 if (minimap_hitbox.origin.along(minimap_axis)
6205 ..minimap_hitbox.bottom_right().along(minimap_axis))
6206 .contains(&old_position)
6207 {
6208 let position =
6209 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
6210 (p + (new_position - old_position) / pixels_per_line)
6211 .max(0.)
6212 });
6213 editor.set_scroll_position(position, window, cx);
6214 }
6215 cx.stop_propagation();
6216 } else {
6217 if minimap_hitbox.is_hovered(window) {
6218 editor.scroll_manager.set_is_hovering_minimap_thumb(
6219 !event.dragging()
6220 && layout
6221 .thumb_layout
6222 .thumb_bounds
6223 .is_some_and(|bounds| bounds.contains(&event.position)),
6224 cx,
6225 );
6226
6227 // Stop hover events from propagating to the
6228 // underlying editor if the minimap hitbox is hovered
6229 if !event.dragging() {
6230 cx.stop_propagation();
6231 }
6232 } else {
6233 editor.scroll_manager.hide_minimap_thumb(cx);
6234 }
6235 }
6236 mouse_position = event.position;
6237 });
6238 }
6239 });
6240
6241 if self.editor.read(cx).scroll_manager.is_dragging_minimap() {
6242 window.on_mouse_event({
6243 let editor = self.editor.clone();
6244 move |event: &MouseUpEvent, phase, window, cx| {
6245 if phase == DispatchPhase::Capture {
6246 return;
6247 }
6248
6249 editor.update(cx, |editor, cx| {
6250 if minimap_hitbox.is_hovered(window) {
6251 editor.scroll_manager.set_is_hovering_minimap_thumb(
6252 layout
6253 .thumb_layout
6254 .thumb_bounds
6255 .is_some_and(|bounds| bounds.contains(&event.position)),
6256 cx,
6257 );
6258 } else {
6259 editor.scroll_manager.hide_minimap_thumb(cx);
6260 }
6261 cx.stop_propagation();
6262 });
6263 }
6264 });
6265 } else {
6266 window.on_mouse_event({
6267 let editor = self.editor.clone();
6268
6269 move |event: &MouseDownEvent, phase, window, cx| {
6270 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
6271 return;
6272 }
6273
6274 let event_position = event.position;
6275
6276 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
6277 return;
6278 };
6279
6280 editor.update(cx, |editor, cx| {
6281 if !thumb_bounds.contains(&event_position) {
6282 let click_position =
6283 event_position.relative_to(&minimap_hitbox.origin).y;
6284
6285 let top_position = (click_position
6286 - thumb_bounds.size.along(minimap_axis) / 2.0)
6287 .max(Pixels::ZERO);
6288
6289 let scroll_offset = (layout.minimap_scroll_top
6290 + top_position / layout.minimap_line_height)
6291 .min(layout.max_scroll_top);
6292
6293 let scroll_position = editor
6294 .scroll_position(cx)
6295 .apply_along(minimap_axis, |_| scroll_offset);
6296 editor.set_scroll_position(scroll_position, window, cx);
6297 }
6298
6299 editor.scroll_manager.set_is_dragging_minimap(cx);
6300 cx.stop_propagation();
6301 });
6302 }
6303 });
6304 }
6305 }
6306 }
6307
6308 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6309 for mut block in layout.blocks.drain(..) {
6310 if block.overlaps_gutter {
6311 block.element.paint(window, cx);
6312 } else {
6313 let mut bounds = layout.hitbox.bounds;
6314 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
6315 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6316 block.element.paint(window, cx);
6317 })
6318 }
6319 }
6320 }
6321
6322 fn paint_inline_completion_popover(
6323 &mut self,
6324 layout: &mut EditorLayout,
6325 window: &mut Window,
6326 cx: &mut App,
6327 ) {
6328 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
6329 inline_completion_popover.paint(window, cx);
6330 }
6331 }
6332
6333 fn paint_mouse_context_menu(
6334 &mut self,
6335 layout: &mut EditorLayout,
6336 window: &mut Window,
6337 cx: &mut App,
6338 ) {
6339 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
6340 mouse_context_menu.paint(window, cx);
6341 }
6342 }
6343
6344 fn paint_scroll_wheel_listener(
6345 &mut self,
6346 layout: &EditorLayout,
6347 window: &mut Window,
6348 cx: &mut App,
6349 ) {
6350 window.on_mouse_event({
6351 let position_map = layout.position_map.clone();
6352 let editor = self.editor.clone();
6353 let hitbox = layout.hitbox.clone();
6354 let mut delta = ScrollDelta::default();
6355
6356 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
6357 // accidentally turn off their scrolling.
6358 let base_scroll_sensitivity =
6359 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
6360
6361 // Use a minimum fast_scroll_sensitivity for same reason above
6362 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
6363 .fast_scroll_sensitivity
6364 .max(0.01);
6365
6366 move |event: &ScrollWheelEvent, phase, window, cx| {
6367 let scroll_sensitivity = {
6368 if event.modifiers.alt {
6369 fast_scroll_sensitivity
6370 } else {
6371 base_scroll_sensitivity
6372 }
6373 };
6374
6375 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
6376 delta = delta.coalesce(event.delta);
6377 editor.update(cx, |editor, cx| {
6378 let position_map: &PositionMap = &position_map;
6379
6380 let line_height = position_map.line_height;
6381 let max_glyph_width = position_map.em_width;
6382 let (delta, axis) = match delta {
6383 gpui::ScrollDelta::Pixels(mut pixels) => {
6384 //Trackpad
6385 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
6386 (pixels, axis)
6387 }
6388
6389 gpui::ScrollDelta::Lines(lines) => {
6390 //Not trackpad
6391 let pixels =
6392 point(lines.x * max_glyph_width, lines.y * line_height);
6393 (pixels, None)
6394 }
6395 };
6396
6397 let current_scroll_position = position_map.snapshot.scroll_position();
6398 let x = (current_scroll_position.x * max_glyph_width
6399 - (delta.x * scroll_sensitivity))
6400 / max_glyph_width;
6401 let y = (current_scroll_position.y * line_height
6402 - (delta.y * scroll_sensitivity))
6403 / line_height;
6404 let mut scroll_position =
6405 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
6406 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
6407 if forbid_vertical_scroll {
6408 scroll_position.y = current_scroll_position.y;
6409 }
6410
6411 if scroll_position != current_scroll_position {
6412 editor.scroll(scroll_position, axis, window, cx);
6413 cx.stop_propagation();
6414 } else if y < 0. {
6415 // Due to clamping, we may fail to detect cases of overscroll to the top;
6416 // We want the scroll manager to get an update in such cases and detect the change of direction
6417 // on the next frame.
6418 cx.notify();
6419 }
6420 });
6421 }
6422 }
6423 });
6424 }
6425
6426 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
6427 if self.editor.read(cx).mode.is_minimap() {
6428 return;
6429 }
6430
6431 self.paint_scroll_wheel_listener(layout, window, cx);
6432
6433 window.on_mouse_event({
6434 let position_map = layout.position_map.clone();
6435 let editor = self.editor.clone();
6436 let diff_hunk_range =
6437 layout
6438 .display_hunks
6439 .iter()
6440 .find_map(|(hunk, hunk_hitbox)| match hunk {
6441 DisplayDiffHunk::Folded { .. } => None,
6442 DisplayDiffHunk::Unfolded {
6443 multi_buffer_range, ..
6444 } => {
6445 if hunk_hitbox
6446 .as_ref()
6447 .map(|hitbox| hitbox.is_hovered(window))
6448 .unwrap_or(false)
6449 {
6450 Some(multi_buffer_range.clone())
6451 } else {
6452 None
6453 }
6454 }
6455 });
6456 let line_numbers = layout.line_numbers.clone();
6457
6458 move |event: &MouseDownEvent, phase, window, cx| {
6459 if phase == DispatchPhase::Bubble {
6460 match event.button {
6461 MouseButton::Left => editor.update(cx, |editor, cx| {
6462 let pending_mouse_down = editor
6463 .pending_mouse_down
6464 .get_or_insert_with(Default::default)
6465 .clone();
6466
6467 *pending_mouse_down.borrow_mut() = Some(event.clone());
6468
6469 Self::mouse_left_down(
6470 editor,
6471 event,
6472 diff_hunk_range.clone(),
6473 &position_map,
6474 line_numbers.as_ref(),
6475 window,
6476 cx,
6477 );
6478 }),
6479 MouseButton::Right => editor.update(cx, |editor, cx| {
6480 Self::mouse_right_down(editor, event, &position_map, window, cx);
6481 }),
6482 MouseButton::Middle => editor.update(cx, |editor, cx| {
6483 Self::mouse_middle_down(editor, event, &position_map, window, cx);
6484 }),
6485 _ => {}
6486 };
6487 }
6488 }
6489 });
6490
6491 window.on_mouse_event({
6492 let editor = self.editor.clone();
6493 let position_map = layout.position_map.clone();
6494
6495 move |event: &MouseUpEvent, phase, window, cx| {
6496 if phase == DispatchPhase::Bubble {
6497 editor.update(cx, |editor, cx| {
6498 Self::mouse_up(editor, event, &position_map, window, cx)
6499 });
6500 }
6501 }
6502 });
6503
6504 window.on_mouse_event({
6505 let editor = self.editor.clone();
6506 let position_map = layout.position_map.clone();
6507 let mut captured_mouse_down = None;
6508
6509 move |event: &MouseUpEvent, phase, window, cx| match phase {
6510 // Clear the pending mouse down during the capture phase,
6511 // so that it happens even if another event handler stops
6512 // propagation.
6513 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
6514 let pending_mouse_down = editor
6515 .pending_mouse_down
6516 .get_or_insert_with(Default::default)
6517 .clone();
6518
6519 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
6520 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
6521 captured_mouse_down = pending_mouse_down.take();
6522 window.refresh();
6523 }
6524 }),
6525 // Fire click handlers during the bubble phase.
6526 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
6527 if let Some(mouse_down) = captured_mouse_down.take() {
6528 let event = ClickEvent {
6529 down: mouse_down,
6530 up: event.clone(),
6531 };
6532 Self::click(editor, &event, &position_map, window, cx);
6533 }
6534 }),
6535 }
6536 });
6537
6538 window.on_mouse_event({
6539 let position_map = layout.position_map.clone();
6540 let editor = self.editor.clone();
6541
6542 move |event: &MouseMoveEvent, phase, window, cx| {
6543 if phase == DispatchPhase::Bubble {
6544 editor.update(cx, |editor, cx| {
6545 if editor.hover_state.focused(window, cx) {
6546 return;
6547 }
6548 if event.pressed_button == Some(MouseButton::Left)
6549 || event.pressed_button == Some(MouseButton::Middle)
6550 {
6551 Self::mouse_dragged(editor, event, &position_map, window, cx)
6552 }
6553
6554 Self::mouse_moved(editor, event, &position_map, window, cx)
6555 });
6556 }
6557 }
6558 });
6559 }
6560
6561 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
6562 bounds.top_right().x - self.style.scrollbar_width
6563 }
6564
6565 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
6566 let style = &self.style;
6567 let font_size = style.text.font_size.to_pixels(window.rem_size());
6568 let layout = window.text_system().shape_line(
6569 SharedString::from(" ".repeat(column)),
6570 font_size,
6571 &[TextRun {
6572 len: column,
6573 font: style.text.font(),
6574 color: Hsla::default(),
6575 background_color: None,
6576 underline: None,
6577 strikethrough: None,
6578 }],
6579 );
6580
6581 layout.width
6582 }
6583
6584 fn max_line_number_width(
6585 &self,
6586 snapshot: &EditorSnapshot,
6587 window: &mut Window,
6588 cx: &mut App,
6589 ) -> Pixels {
6590 let digit_count = snapshot.widest_line_number().ilog10() + 1;
6591 self.column_pixels(digit_count as usize, window, cx)
6592 }
6593
6594 fn shape_line_number(
6595 &self,
6596 text: SharedString,
6597 color: Hsla,
6598 window: &mut Window,
6599 ) -> ShapedLine {
6600 let run = TextRun {
6601 len: text.len(),
6602 font: self.style.text.font(),
6603 color,
6604 background_color: None,
6605 underline: None,
6606 strikethrough: None,
6607 };
6608 window.text_system().shape_line(
6609 text,
6610 self.style.text.font_size.to_pixels(window.rem_size()),
6611 &[run],
6612 )
6613 }
6614
6615 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
6616 let unstaged = status.has_secondary_hunk();
6617 let unstaged_hollow = ProjectSettings::get_global(cx)
6618 .git
6619 .hunk_style
6620 .map_or(false, |style| {
6621 matches!(style, GitHunkStyleSetting::UnstagedHollow)
6622 });
6623
6624 unstaged == unstaged_hollow
6625 }
6626}
6627
6628fn header_jump_data(
6629 snapshot: &EditorSnapshot,
6630 block_row_start: DisplayRow,
6631 height: u32,
6632 for_excerpt: &ExcerptInfo,
6633) -> JumpData {
6634 let range = &for_excerpt.range;
6635 let buffer = &for_excerpt.buffer;
6636 let jump_anchor = range.primary.start;
6637
6638 let excerpt_start = range.context.start;
6639 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
6640 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
6641 0
6642 } else {
6643 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
6644 jump_position.row.saturating_sub(excerpt_start_point.row)
6645 };
6646
6647 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
6648 .saturating_sub(
6649 snapshot
6650 .scroll_anchor
6651 .scroll_position(&snapshot.display_snapshot)
6652 .y as u32,
6653 );
6654
6655 JumpData::MultiBufferPoint {
6656 excerpt_id: for_excerpt.id,
6657 anchor: jump_anchor,
6658 position: jump_position,
6659 line_offset_from_top,
6660 }
6661}
6662
6663pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
6664
6665impl AcceptEditPredictionBinding {
6666 pub fn keystroke(&self) -> Option<&Keystroke> {
6667 if let Some(binding) = self.0.as_ref() {
6668 match &binding.keystrokes() {
6669 [keystroke] => Some(keystroke),
6670 _ => None,
6671 }
6672 } else {
6673 None
6674 }
6675 }
6676}
6677
6678fn prepaint_gutter_button(
6679 button: IconButton,
6680 row: DisplayRow,
6681 line_height: Pixels,
6682 gutter_dimensions: &GutterDimensions,
6683 scroll_pixel_position: gpui::Point<Pixels>,
6684 gutter_hitbox: &Hitbox,
6685 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
6686 window: &mut Window,
6687 cx: &mut App,
6688) -> AnyElement {
6689 let mut button = button.into_any_element();
6690
6691 let available_space = size(
6692 AvailableSpace::MinContent,
6693 AvailableSpace::Definite(line_height),
6694 );
6695 let indicator_size = button.layout_as_root(available_space, window, cx);
6696
6697 let blame_width = gutter_dimensions.git_blame_entries_width;
6698 let gutter_width = display_hunks
6699 .binary_search_by(|(hunk, _)| match hunk {
6700 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
6701 DisplayDiffHunk::Unfolded {
6702 display_row_range, ..
6703 } => {
6704 if display_row_range.end <= row {
6705 Ordering::Less
6706 } else if display_row_range.start > row {
6707 Ordering::Greater
6708 } else {
6709 Ordering::Equal
6710 }
6711 }
6712 })
6713 .ok()
6714 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
6715 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
6716
6717 let mut x = left_offset;
6718 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
6719 - indicator_size.width
6720 - left_offset;
6721 x += available_width / 2.;
6722
6723 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
6724 y += (line_height - indicator_size.height) / 2.;
6725
6726 button.prepaint_as_root(
6727 gutter_hitbox.origin + point(x, y),
6728 available_space,
6729 window,
6730 cx,
6731 );
6732 button
6733}
6734
6735fn render_inline_blame_entry(
6736 blame_entry: BlameEntry,
6737 style: &EditorStyle,
6738 cx: &mut App,
6739) -> Option<AnyElement> {
6740 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6741 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
6742}
6743
6744fn render_blame_entry_popover(
6745 blame_entry: BlameEntry,
6746 scroll_handle: ScrollHandle,
6747 commit_message: Option<ParsedCommitMessage>,
6748 markdown: Entity<Markdown>,
6749 workspace: WeakEntity<Workspace>,
6750 blame: &Entity<GitBlame>,
6751 window: &mut Window,
6752 cx: &mut App,
6753) -> Option<AnyElement> {
6754 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6755 let blame = blame.read(cx);
6756 let repository = blame.repository(cx)?.clone();
6757 renderer.render_blame_entry_popover(
6758 blame_entry,
6759 scroll_handle,
6760 commit_message,
6761 markdown,
6762 repository,
6763 workspace,
6764 window,
6765 cx,
6766 )
6767}
6768
6769fn render_blame_entry(
6770 ix: usize,
6771 blame: &Entity<GitBlame>,
6772 blame_entry: BlameEntry,
6773 style: &EditorStyle,
6774 last_used_color: &mut Option<(PlayerColor, Oid)>,
6775 editor: Entity<Editor>,
6776 workspace: Entity<Workspace>,
6777 renderer: Arc<dyn BlameRenderer>,
6778 cx: &mut App,
6779) -> Option<AnyElement> {
6780 let mut sha_color = cx
6781 .theme()
6782 .players()
6783 .color_for_participant(blame_entry.sha.into());
6784
6785 // If the last color we used is the same as the one we get for this line, but
6786 // the commit SHAs are different, then we try again to get a different color.
6787 match *last_used_color {
6788 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
6789 let index: u32 = blame_entry.sha.into();
6790 sha_color = cx.theme().players().color_for_participant(index + 1);
6791 }
6792 _ => {}
6793 };
6794 last_used_color.replace((sha_color, blame_entry.sha));
6795
6796 let blame = blame.read(cx);
6797 let details = blame.details_for_entry(&blame_entry);
6798 let repository = blame.repository(cx)?;
6799 renderer.render_blame_entry(
6800 &style.text,
6801 blame_entry,
6802 details,
6803 repository,
6804 workspace.downgrade(),
6805 editor,
6806 ix,
6807 sha_color.cursor,
6808 cx,
6809 )
6810}
6811
6812#[derive(Debug)]
6813pub(crate) struct LineWithInvisibles {
6814 fragments: SmallVec<[LineFragment; 1]>,
6815 invisibles: Vec<Invisible>,
6816 len: usize,
6817 pub(crate) width: Pixels,
6818 font_size: Pixels,
6819}
6820
6821enum LineFragment {
6822 Text(ShapedLine),
6823 Element {
6824 id: FoldId,
6825 element: Option<AnyElement>,
6826 size: Size<Pixels>,
6827 len: usize,
6828 },
6829}
6830
6831impl fmt::Debug for LineFragment {
6832 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6833 match self {
6834 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6835 LineFragment::Element { size, len, .. } => f
6836 .debug_struct("Element")
6837 .field("size", size)
6838 .field("len", len)
6839 .finish(),
6840 }
6841 }
6842}
6843
6844impl LineWithInvisibles {
6845 fn from_chunks<'a>(
6846 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6847 editor_style: &EditorStyle,
6848 max_line_len: usize,
6849 max_line_count: usize,
6850 editor_mode: &EditorMode,
6851 text_width: Pixels,
6852 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6853 window: &mut Window,
6854 cx: &mut App,
6855 ) -> Vec<Self> {
6856 let text_style = &editor_style.text;
6857 let mut layouts = Vec::with_capacity(max_line_count);
6858 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6859 let mut line = String::new();
6860 let mut invisibles = Vec::new();
6861 let mut width = Pixels::ZERO;
6862 let mut len = 0;
6863 let mut styles = Vec::new();
6864 let mut non_whitespace_added = false;
6865 let mut row = 0;
6866 let mut line_exceeded_max_len = false;
6867 let font_size = text_style.font_size.to_pixels(window.rem_size());
6868
6869 let ellipsis = SharedString::from("⋯");
6870
6871 for highlighted_chunk in chunks.chain([HighlightedChunk {
6872 text: "\n",
6873 style: None,
6874 is_tab: false,
6875 is_inlay: false,
6876 replacement: None,
6877 }]) {
6878 if let Some(replacement) = highlighted_chunk.replacement {
6879 if !line.is_empty() {
6880 let shaped_line =
6881 window
6882 .text_system()
6883 .shape_line(line.clone().into(), font_size, &styles);
6884 width += shaped_line.width;
6885 len += shaped_line.len;
6886 fragments.push(LineFragment::Text(shaped_line));
6887 line.clear();
6888 styles.clear();
6889 }
6890
6891 match replacement {
6892 ChunkReplacement::Renderer(renderer) => {
6893 let available_width = if renderer.constrain_width {
6894 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6895 ellipsis.clone()
6896 } else {
6897 SharedString::from(Arc::from(highlighted_chunk.text))
6898 };
6899 let shaped_line = window.text_system().shape_line(
6900 chunk,
6901 font_size,
6902 &[text_style.to_run(highlighted_chunk.text.len())],
6903 );
6904 AvailableSpace::Definite(shaped_line.width)
6905 } else {
6906 AvailableSpace::MinContent
6907 };
6908
6909 let mut element = (renderer.render)(&mut ChunkRendererContext {
6910 context: cx,
6911 window,
6912 max_width: text_width,
6913 });
6914 let line_height = text_style.line_height_in_pixels(window.rem_size());
6915 let size = element.layout_as_root(
6916 size(available_width, AvailableSpace::Definite(line_height)),
6917 window,
6918 cx,
6919 );
6920
6921 width += size.width;
6922 len += highlighted_chunk.text.len();
6923 fragments.push(LineFragment::Element {
6924 id: renderer.id,
6925 element: Some(element),
6926 size,
6927 len: highlighted_chunk.text.len(),
6928 });
6929 }
6930 ChunkReplacement::Str(x) => {
6931 let text_style = if let Some(style) = highlighted_chunk.style {
6932 Cow::Owned(text_style.clone().highlight(style))
6933 } else {
6934 Cow::Borrowed(text_style)
6935 };
6936
6937 let run = TextRun {
6938 len: x.len(),
6939 font: text_style.font(),
6940 color: text_style.color,
6941 background_color: text_style.background_color,
6942 underline: text_style.underline,
6943 strikethrough: text_style.strikethrough,
6944 };
6945 let line_layout = window
6946 .text_system()
6947 .shape_line(x, font_size, &[run])
6948 .with_len(highlighted_chunk.text.len());
6949
6950 width += line_layout.width;
6951 len += highlighted_chunk.text.len();
6952 fragments.push(LineFragment::Text(line_layout))
6953 }
6954 }
6955 } else {
6956 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6957 if ix > 0 {
6958 let shaped_line = window.text_system().shape_line(
6959 line.clone().into(),
6960 font_size,
6961 &styles,
6962 );
6963 width += shaped_line.width;
6964 len += shaped_line.len;
6965 fragments.push(LineFragment::Text(shaped_line));
6966 layouts.push(Self {
6967 width: mem::take(&mut width),
6968 len: mem::take(&mut len),
6969 fragments: mem::take(&mut fragments),
6970 invisibles: std::mem::take(&mut invisibles),
6971 font_size,
6972 });
6973
6974 line.clear();
6975 styles.clear();
6976 row += 1;
6977 line_exceeded_max_len = false;
6978 non_whitespace_added = false;
6979 if row == max_line_count {
6980 return layouts;
6981 }
6982 }
6983
6984 if !line_chunk.is_empty() && !line_exceeded_max_len {
6985 let text_style = if let Some(style) = highlighted_chunk.style {
6986 Cow::Owned(text_style.clone().highlight(style))
6987 } else {
6988 Cow::Borrowed(text_style)
6989 };
6990
6991 if line.len() + line_chunk.len() > max_line_len {
6992 let mut chunk_len = max_line_len - line.len();
6993 while !line_chunk.is_char_boundary(chunk_len) {
6994 chunk_len -= 1;
6995 }
6996 line_chunk = &line_chunk[..chunk_len];
6997 line_exceeded_max_len = true;
6998 }
6999
7000 styles.push(TextRun {
7001 len: line_chunk.len(),
7002 font: text_style.font(),
7003 color: text_style.color,
7004 background_color: text_style.background_color,
7005 underline: text_style.underline,
7006 strikethrough: text_style.strikethrough,
7007 });
7008
7009 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
7010 // Line wrap pads its contents with fake whitespaces,
7011 // avoid printing them
7012 let is_soft_wrapped = is_row_soft_wrapped(row);
7013 if highlighted_chunk.is_tab {
7014 if non_whitespace_added || !is_soft_wrapped {
7015 invisibles.push(Invisible::Tab {
7016 line_start_offset: line.len(),
7017 line_end_offset: line.len() + line_chunk.len(),
7018 });
7019 }
7020 } else {
7021 invisibles.extend(line_chunk.char_indices().filter_map(
7022 |(index, c)| {
7023 let is_whitespace = c.is_whitespace();
7024 non_whitespace_added |= !is_whitespace;
7025 if is_whitespace
7026 && (non_whitespace_added || !is_soft_wrapped)
7027 {
7028 Some(Invisible::Whitespace {
7029 line_offset: line.len() + index,
7030 })
7031 } else {
7032 None
7033 }
7034 },
7035 ))
7036 }
7037 }
7038
7039 line.push_str(line_chunk);
7040 }
7041 }
7042 }
7043 }
7044
7045 layouts
7046 }
7047
7048 fn prepaint(
7049 &mut self,
7050 line_height: Pixels,
7051 scroll_pixel_position: gpui::Point<Pixels>,
7052 row: DisplayRow,
7053 content_origin: gpui::Point<Pixels>,
7054 line_elements: &mut SmallVec<[AnyElement; 1]>,
7055 window: &mut Window,
7056 cx: &mut App,
7057 ) {
7058 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
7059 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
7060 for fragment in &mut self.fragments {
7061 match fragment {
7062 LineFragment::Text(line) => {
7063 fragment_origin.x += line.width;
7064 }
7065 LineFragment::Element { element, size, .. } => {
7066 let mut element = element
7067 .take()
7068 .expect("you can't prepaint LineWithInvisibles twice");
7069
7070 // Center the element vertically within the line.
7071 let mut element_origin = fragment_origin;
7072 element_origin.y += (line_height - size.height) / 2.;
7073 element.prepaint_at(element_origin, window, cx);
7074 line_elements.push(element);
7075
7076 fragment_origin.x += size.width;
7077 }
7078 }
7079 }
7080 }
7081
7082 fn draw(
7083 &self,
7084 layout: &EditorLayout,
7085 row: DisplayRow,
7086 content_origin: gpui::Point<Pixels>,
7087 whitespace_setting: ShowWhitespaceSetting,
7088 selection_ranges: &[Range<DisplayPoint>],
7089 window: &mut Window,
7090 cx: &mut App,
7091 ) {
7092 let line_height = layout.position_map.line_height;
7093 let line_y = line_height
7094 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7095
7096 let mut fragment_origin =
7097 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7098
7099 for fragment in &self.fragments {
7100 match fragment {
7101 LineFragment::Text(line) => {
7102 line.paint(fragment_origin, line_height, window, cx)
7103 .log_err();
7104 fragment_origin.x += line.width;
7105 }
7106 LineFragment::Element { size, .. } => {
7107 fragment_origin.x += size.width;
7108 }
7109 }
7110 }
7111
7112 self.draw_invisibles(
7113 selection_ranges,
7114 layout,
7115 content_origin,
7116 line_y,
7117 row,
7118 line_height,
7119 whitespace_setting,
7120 window,
7121 cx,
7122 );
7123 }
7124
7125 fn draw_background(
7126 &self,
7127 layout: &EditorLayout,
7128 row: DisplayRow,
7129 content_origin: gpui::Point<Pixels>,
7130 window: &mut Window,
7131 cx: &mut App,
7132 ) {
7133 let line_height = layout.position_map.line_height;
7134 let line_y = line_height
7135 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7136
7137 let mut fragment_origin =
7138 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7139
7140 for fragment in &self.fragments {
7141 match fragment {
7142 LineFragment::Text(line) => {
7143 line.paint_background(fragment_origin, line_height, window, cx)
7144 .log_err();
7145 fragment_origin.x += line.width;
7146 }
7147 LineFragment::Element { size, .. } => {
7148 fragment_origin.x += size.width;
7149 }
7150 }
7151 }
7152 }
7153
7154 fn draw_invisibles(
7155 &self,
7156 selection_ranges: &[Range<DisplayPoint>],
7157 layout: &EditorLayout,
7158 content_origin: gpui::Point<Pixels>,
7159 line_y: Pixels,
7160 row: DisplayRow,
7161 line_height: Pixels,
7162 whitespace_setting: ShowWhitespaceSetting,
7163 window: &mut Window,
7164 cx: &mut App,
7165 ) {
7166 let extract_whitespace_info = |invisible: &Invisible| {
7167 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
7168 Invisible::Tab {
7169 line_start_offset,
7170 line_end_offset,
7171 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
7172 Invisible::Whitespace { line_offset } => {
7173 (*line_offset, line_offset + 1, &layout.space_invisible)
7174 }
7175 };
7176
7177 let x_offset = self.x_for_index(token_offset);
7178 let invisible_offset =
7179 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
7180 let origin = content_origin
7181 + gpui::point(
7182 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
7183 line_y,
7184 );
7185
7186 (
7187 [token_offset, token_end_offset],
7188 Box::new(move |window: &mut Window, cx: &mut App| {
7189 invisible_symbol
7190 .paint(origin, line_height, window, cx)
7191 .log_err();
7192 }),
7193 )
7194 };
7195
7196 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
7197 match whitespace_setting {
7198 ShowWhitespaceSetting::None => (),
7199 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
7200 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
7201 let invisible_point = DisplayPoint::new(row, start as u32);
7202 if !selection_ranges
7203 .iter()
7204 .any(|region| region.start <= invisible_point && invisible_point < region.end)
7205 {
7206 return;
7207 }
7208
7209 paint(window, cx);
7210 }),
7211
7212 // For a whitespace to be on a boundary, any of the following conditions need to be met:
7213 // - It is a tab
7214 // - It is adjacent to an edge (start or end)
7215 // - It is adjacent to a whitespace (left or right)
7216 ShowWhitespaceSetting::Boundary => {
7217 // 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
7218 // the above cases.
7219 // Note: We zip in the original `invisibles` to check for tab equality
7220 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
7221 for (([start, end], paint), invisible) in
7222 invisible_iter.zip_eq(self.invisibles.iter())
7223 {
7224 let should_render = match (&last_seen, invisible) {
7225 (_, Invisible::Tab { .. }) => true,
7226 (Some((_, last_end, _)), _) => *last_end == start,
7227 _ => false,
7228 };
7229
7230 if should_render || start == 0 || end == self.len {
7231 paint(window, cx);
7232
7233 // Since we are scanning from the left, we will skip over the first available whitespace that is part
7234 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
7235 if let Some((should_render_last, last_end, paint_last)) = last_seen {
7236 // Note that we need to make sure that the last one is actually adjacent
7237 if !should_render_last && last_end == start {
7238 paint_last(window, cx);
7239 }
7240 }
7241 }
7242
7243 // Manually render anything within a selection
7244 let invisible_point = DisplayPoint::new(row, start as u32);
7245 if selection_ranges.iter().any(|region| {
7246 region.start <= invisible_point && invisible_point < region.end
7247 }) {
7248 paint(window, cx);
7249 }
7250
7251 last_seen = Some((should_render, end, paint));
7252 }
7253 }
7254 }
7255 }
7256
7257 pub fn x_for_index(&self, index: usize) -> Pixels {
7258 let mut fragment_start_x = Pixels::ZERO;
7259 let mut fragment_start_index = 0;
7260
7261 for fragment in &self.fragments {
7262 match fragment {
7263 LineFragment::Text(shaped_line) => {
7264 let fragment_end_index = fragment_start_index + shaped_line.len;
7265 if index < fragment_end_index {
7266 return fragment_start_x
7267 + shaped_line.x_for_index(index - fragment_start_index);
7268 }
7269 fragment_start_x += shaped_line.width;
7270 fragment_start_index = fragment_end_index;
7271 }
7272 LineFragment::Element { len, size, .. } => {
7273 let fragment_end_index = fragment_start_index + len;
7274 if index < fragment_end_index {
7275 return fragment_start_x;
7276 }
7277 fragment_start_x += size.width;
7278 fragment_start_index = fragment_end_index;
7279 }
7280 }
7281 }
7282
7283 fragment_start_x
7284 }
7285
7286 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
7287 let mut fragment_start_x = Pixels::ZERO;
7288 let mut fragment_start_index = 0;
7289
7290 for fragment in &self.fragments {
7291 match fragment {
7292 LineFragment::Text(shaped_line) => {
7293 let fragment_end_x = fragment_start_x + shaped_line.width;
7294 if x < fragment_end_x {
7295 return Some(
7296 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
7297 );
7298 }
7299 fragment_start_x = fragment_end_x;
7300 fragment_start_index += shaped_line.len;
7301 }
7302 LineFragment::Element { len, size, .. } => {
7303 let fragment_end_x = fragment_start_x + size.width;
7304 if x < fragment_end_x {
7305 return Some(fragment_start_index);
7306 }
7307 fragment_start_index += len;
7308 fragment_start_x = fragment_end_x;
7309 }
7310 }
7311 }
7312
7313 None
7314 }
7315
7316 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
7317 let mut fragment_start_index = 0;
7318
7319 for fragment in &self.fragments {
7320 match fragment {
7321 LineFragment::Text(shaped_line) => {
7322 let fragment_end_index = fragment_start_index + shaped_line.len;
7323 if index < fragment_end_index {
7324 return shaped_line.font_id_for_index(index - fragment_start_index);
7325 }
7326 fragment_start_index = fragment_end_index;
7327 }
7328 LineFragment::Element { len, .. } => {
7329 let fragment_end_index = fragment_start_index + len;
7330 if index < fragment_end_index {
7331 return None;
7332 }
7333 fragment_start_index = fragment_end_index;
7334 }
7335 }
7336 }
7337
7338 None
7339 }
7340}
7341
7342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7343enum Invisible {
7344 /// A tab character
7345 ///
7346 /// A tab character is internally represented by spaces (configured by the user's tab width)
7347 /// aligned to the nearest column, so it's necessary to store the start and end offset for
7348 /// adjacency checks.
7349 Tab {
7350 line_start_offset: usize,
7351 line_end_offset: usize,
7352 },
7353 Whitespace {
7354 line_offset: usize,
7355 },
7356}
7357
7358impl EditorElement {
7359 /// Returns the rem size to use when rendering the [`EditorElement`].
7360 ///
7361 /// This allows UI elements to scale based on the `buffer_font_size`.
7362 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
7363 match self.editor.read(cx).mode {
7364 EditorMode::Full {
7365 scale_ui_elements_with_buffer_font_size: true,
7366 ..
7367 }
7368 | EditorMode::Minimap { .. } => {
7369 let buffer_font_size = self.style.text.font_size;
7370 match buffer_font_size {
7371 AbsoluteLength::Pixels(pixels) => {
7372 let rem_size_scale = {
7373 // Our default UI font size is 14px on a 16px base scale.
7374 // This means the default UI font size is 0.875rems.
7375 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
7376
7377 // We then determine the delta between a single rem and the default font
7378 // size scale.
7379 let default_font_size_delta = 1. - default_font_size_scale;
7380
7381 // Finally, we add this delta to 1rem to get the scale factor that
7382 // should be used to scale up the UI.
7383 1. + default_font_size_delta
7384 };
7385
7386 Some(pixels * rem_size_scale)
7387 }
7388 AbsoluteLength::Rems(rems) => {
7389 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
7390 }
7391 }
7392 }
7393 // We currently use single-line and auto-height editors in UI contexts,
7394 // so we don't want to scale everything with the buffer font size, as it
7395 // ends up looking off.
7396 _ => None,
7397 }
7398 }
7399
7400 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
7401 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
7402 parent.upgrade()
7403 } else {
7404 Some(self.editor.clone())
7405 }
7406 }
7407}
7408
7409impl Element for EditorElement {
7410 type RequestLayoutState = ();
7411 type PrepaintState = EditorLayout;
7412
7413 fn id(&self) -> Option<ElementId> {
7414 None
7415 }
7416
7417 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
7418 None
7419 }
7420
7421 fn request_layout(
7422 &mut self,
7423 _: Option<&GlobalElementId>,
7424 __inspector_id: Option<&gpui::InspectorElementId>,
7425 window: &mut Window,
7426 cx: &mut App,
7427 ) -> (gpui::LayoutId, ()) {
7428 let rem_size = self.rem_size(cx);
7429 window.with_rem_size(rem_size, |window| {
7430 self.editor.update(cx, |editor, cx| {
7431 editor.set_style(self.style.clone(), window, cx);
7432
7433 let layout_id = match editor.mode {
7434 EditorMode::SingleLine { auto_width } => {
7435 let rem_size = window.rem_size();
7436
7437 let height = self.style.text.line_height_in_pixels(rem_size);
7438 if auto_width {
7439 let editor_handle = cx.entity().clone();
7440 let style = self.style.clone();
7441 window.request_measured_layout(
7442 Style::default(),
7443 move |_, _, window, cx| {
7444 let editor_snapshot = editor_handle
7445 .update(cx, |editor, cx| editor.snapshot(window, cx));
7446 let line = Self::layout_lines(
7447 DisplayRow(0)..DisplayRow(1),
7448 &editor_snapshot,
7449 &style,
7450 px(f32::MAX),
7451 |_| false, // Single lines never soft wrap
7452 window,
7453 cx,
7454 )
7455 .pop()
7456 .unwrap();
7457
7458 let font_id =
7459 window.text_system().resolve_font(&style.text.font());
7460 let font_size =
7461 style.text.font_size.to_pixels(window.rem_size());
7462 let em_width =
7463 window.text_system().em_width(font_id, font_size).unwrap();
7464
7465 size(line.width + em_width, height)
7466 },
7467 )
7468 } else {
7469 let mut style = Style::default();
7470 style.size.height = height.into();
7471 style.size.width = relative(1.).into();
7472 window.request_layout(style, None, cx)
7473 }
7474 }
7475 EditorMode::AutoHeight { max_lines } => {
7476 let editor_handle = cx.entity().clone();
7477 let max_line_number_width =
7478 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
7479 window.request_measured_layout(
7480 Style::default(),
7481 move |known_dimensions, available_space, window, cx| {
7482 editor_handle
7483 .update(cx, |editor, cx| {
7484 compute_auto_height_layout(
7485 editor,
7486 max_lines,
7487 max_line_number_width,
7488 known_dimensions,
7489 available_space.width,
7490 window,
7491 cx,
7492 )
7493 })
7494 .unwrap_or_default()
7495 },
7496 )
7497 }
7498 EditorMode::Minimap { .. } => {
7499 let mut style = Style::default();
7500 style.size.width = relative(1.).into();
7501 style.size.height = relative(1.).into();
7502 window.request_layout(style, None, cx)
7503 }
7504 EditorMode::Full {
7505 sized_by_content, ..
7506 } => {
7507 let mut style = Style::default();
7508 style.size.width = relative(1.).into();
7509 if sized_by_content {
7510 let snapshot = editor.snapshot(window, cx);
7511 let line_height =
7512 self.style.text.line_height_in_pixels(window.rem_size());
7513 let scroll_height =
7514 (snapshot.max_point().row().next_row().0 as f32) * line_height;
7515 style.size.height = scroll_height.into();
7516 } else {
7517 style.size.height = relative(1.).into();
7518 }
7519 window.request_layout(style, None, cx)
7520 }
7521 };
7522
7523 (layout_id, ())
7524 })
7525 })
7526 }
7527
7528 fn prepaint(
7529 &mut self,
7530 _: Option<&GlobalElementId>,
7531 _inspector_id: Option<&gpui::InspectorElementId>,
7532 bounds: Bounds<Pixels>,
7533 _: &mut Self::RequestLayoutState,
7534 window: &mut Window,
7535 cx: &mut App,
7536 ) -> Self::PrepaintState {
7537 let text_style = TextStyleRefinement {
7538 font_size: Some(self.style.text.font_size),
7539 line_height: Some(self.style.text.line_height),
7540 ..Default::default()
7541 };
7542 let focus_handle = self.editor.focus_handle(cx);
7543 window.set_view_id(self.editor.entity_id());
7544 window.set_focus_handle(&focus_handle, cx);
7545
7546 let rem_size = self.rem_size(cx);
7547 window.with_rem_size(rem_size, |window| {
7548 window.with_text_style(Some(text_style), |window| {
7549 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7550 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
7551 (editor.snapshot(window, cx), editor.read_only(cx))
7552 });
7553 let style = self.style.clone();
7554
7555 let font_id = window.text_system().resolve_font(&style.text.font());
7556 let font_size = style.text.font_size.to_pixels(window.rem_size());
7557 let line_height = style.text.line_height_in_pixels(window.rem_size());
7558 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
7559 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
7560
7561 let glyph_grid_cell = size(em_width, line_height);
7562
7563 let gutter_dimensions = snapshot
7564 .gutter_dimensions(
7565 font_id,
7566 font_size,
7567 self.max_line_number_width(&snapshot, window, cx),
7568 cx,
7569 )
7570 .or_else(|| {
7571 self.editor.read(cx).offset_content.then(|| {
7572 GutterDimensions::default_with_margin(font_id, font_size, cx)
7573 })
7574 })
7575 .unwrap_or_default();
7576 let text_width = bounds.size.width - gutter_dimensions.width;
7577
7578 let settings = EditorSettings::get_global(cx);
7579 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
7580 let vertical_scrollbar_width = (scrollbars_shown
7581 && settings.scrollbar.axes.vertical
7582 && self.editor.read(cx).show_scrollbars.vertical)
7583 .then_some(style.scrollbar_width)
7584 .unwrap_or_default();
7585 let minimap_width = self
7586 .editor
7587 .read(cx)
7588 .minimap()
7589 .is_some()
7590 .then(|| match settings.minimap.show {
7591 ShowMinimap::Auto => {
7592 scrollbars_shown.then_some(MinimapLayout::MINIMAP_WIDTH)
7593 }
7594 _ => Some(MinimapLayout::MINIMAP_WIDTH),
7595 })
7596 .flatten()
7597 .filter(|minimap_width| {
7598 text_width - vertical_scrollbar_width - *minimap_width > *minimap_width
7599 })
7600 .unwrap_or_default();
7601
7602 let right_margin = minimap_width + vertical_scrollbar_width;
7603
7604 let editor_width =
7605 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
7606
7607 let editor_margins = EditorMargins {
7608 gutter: gutter_dimensions,
7609 right: right_margin,
7610 };
7611
7612 // Offset the content_bounds from the text_bounds by the gutter margin (which
7613 // is roughly half a character wide) to make hit testing work more like how we want.
7614 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
7615
7616 let editor_content_width = editor_width - content_offset.x;
7617
7618 snapshot = self.editor.update(cx, |editor, cx| {
7619 editor.last_bounds = Some(bounds);
7620 editor.gutter_dimensions = gutter_dimensions;
7621 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
7622
7623 if matches!(
7624 editor.mode,
7625 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
7626 ) {
7627 snapshot
7628 } else {
7629 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
7630 let wrap_width = match editor.soft_wrap_mode(cx) {
7631 SoftWrap::GitDiff => None,
7632 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
7633 SoftWrap::EditorWidth => Some(editor_content_width),
7634 SoftWrap::Column(column) => Some(wrap_width_for(column)),
7635 SoftWrap::Bounded(column) => {
7636 Some(editor_content_width.min(wrap_width_for(column)))
7637 }
7638 };
7639
7640 if editor.set_wrap_width(wrap_width, cx) {
7641 editor.snapshot(window, cx)
7642 } else {
7643 snapshot
7644 }
7645 }
7646 });
7647
7648 let wrap_guides = self
7649 .editor
7650 .read(cx)
7651 .wrap_guides(cx)
7652 .iter()
7653 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
7654 .collect::<SmallVec<[_; 2]>>();
7655
7656 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
7657 let gutter_hitbox = window.insert_hitbox(
7658 gutter_bounds(bounds, gutter_dimensions),
7659 HitboxBehavior::Normal,
7660 );
7661 let text_hitbox = window.insert_hitbox(
7662 Bounds {
7663 origin: gutter_hitbox.top_right(),
7664 size: size(text_width, bounds.size.height),
7665 },
7666 HitboxBehavior::Normal,
7667 );
7668
7669 let content_origin = text_hitbox.origin + content_offset;
7670
7671 let editor_text_bounds =
7672 Bounds::from_corners(content_origin, bounds.bottom_right());
7673
7674 let height_in_lines = editor_text_bounds.size.height / line_height;
7675
7676 let max_row = snapshot.max_point().row().as_f32();
7677
7678 // The max scroll position for the top of the window
7679 let max_scroll_top = if matches!(
7680 snapshot.mode,
7681 EditorMode::SingleLine { .. }
7682 | EditorMode::AutoHeight { .. }
7683 | EditorMode::Full {
7684 sized_by_content: true,
7685 ..
7686 }
7687 ) {
7688 (max_row - height_in_lines + 1.).max(0.)
7689 } else {
7690 let settings = EditorSettings::get_global(cx);
7691 match settings.scroll_beyond_last_line {
7692 ScrollBeyondLastLine::OnePage => max_row,
7693 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
7694 ScrollBeyondLastLine::VerticalScrollMargin => {
7695 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
7696 .max(0.)
7697 }
7698 }
7699 };
7700
7701 // TODO: Autoscrolling for both axes
7702 let mut autoscroll_request = None;
7703 let mut autoscroll_containing_element = false;
7704 let mut autoscroll_horizontally = false;
7705 self.editor.update(cx, |editor, cx| {
7706 autoscroll_request = editor.autoscroll_request();
7707 autoscroll_containing_element =
7708 autoscroll_request.is_some() || editor.has_pending_selection();
7709 // TODO: Is this horizontal or vertical?!
7710 autoscroll_horizontally = editor.autoscroll_vertically(
7711 bounds,
7712 line_height,
7713 max_scroll_top,
7714 window,
7715 cx,
7716 );
7717 snapshot = editor.snapshot(window, cx);
7718 });
7719
7720 let mut scroll_position = snapshot.scroll_position();
7721 // The scroll position is a fractional point, the whole number of which represents
7722 // the top of the window in terms of display rows.
7723 let start_row = DisplayRow(scroll_position.y as u32);
7724 let max_row = snapshot.max_point().row();
7725 let end_row = cmp::min(
7726 (scroll_position.y + height_in_lines).ceil() as u32,
7727 max_row.next_row().0,
7728 );
7729 let end_row = DisplayRow(end_row);
7730
7731 let row_infos = snapshot
7732 .row_infos(start_row)
7733 .take((start_row..end_row).len())
7734 .collect::<Vec<RowInfo>>();
7735 let is_row_soft_wrapped = |row: usize| {
7736 row_infos
7737 .get(row)
7738 .map_or(true, |info| info.buffer_row.is_none())
7739 };
7740
7741 let start_anchor = if start_row == Default::default() {
7742 Anchor::min()
7743 } else {
7744 snapshot.buffer_snapshot.anchor_before(
7745 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
7746 )
7747 };
7748 let end_anchor = if end_row > max_row {
7749 Anchor::max()
7750 } else {
7751 snapshot.buffer_snapshot.anchor_before(
7752 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
7753 )
7754 };
7755
7756 let mut highlighted_rows = self
7757 .editor
7758 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
7759
7760 let is_light = cx.theme().appearance().is_light();
7761
7762 for (ix, row_info) in row_infos.iter().enumerate() {
7763 let Some(diff_status) = row_info.diff_status else {
7764 continue;
7765 };
7766
7767 let background_color = match diff_status.kind {
7768 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
7769 DiffHunkStatusKind::Deleted => {
7770 cx.theme().colors().version_control_deleted
7771 }
7772 DiffHunkStatusKind::Modified => {
7773 debug_panic!("modified diff status for row info");
7774 continue;
7775 }
7776 };
7777
7778 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
7779
7780 let hollow_highlight = LineHighlight {
7781 background: (background_color.opacity(if is_light {
7782 0.08
7783 } else {
7784 0.06
7785 }))
7786 .into(),
7787 border: Some(if is_light {
7788 background_color.opacity(0.48)
7789 } else {
7790 background_color.opacity(0.36)
7791 }),
7792 include_gutter: true,
7793 type_id: None,
7794 };
7795
7796 let filled_highlight = LineHighlight {
7797 background: solid_background(background_color.opacity(hunk_opacity)),
7798 border: None,
7799 include_gutter: true,
7800 type_id: None,
7801 };
7802
7803 let background = if Self::diff_hunk_hollow(diff_status, cx) {
7804 hollow_highlight
7805 } else {
7806 filled_highlight
7807 };
7808
7809 highlighted_rows
7810 .entry(start_row + DisplayRow(ix as u32))
7811 .or_insert(background);
7812 }
7813
7814 let highlighted_ranges = self
7815 .editor_with_selections(cx)
7816 .map(|editor| {
7817 editor.read(cx).background_highlights_in_range(
7818 start_anchor..end_anchor,
7819 &snapshot.display_snapshot,
7820 cx.theme().colors(),
7821 )
7822 })
7823 .unwrap_or_default();
7824 let highlighted_gutter_ranges =
7825 self.editor.read(cx).gutter_highlights_in_range(
7826 start_anchor..end_anchor,
7827 &snapshot.display_snapshot,
7828 cx,
7829 );
7830
7831 let redacted_ranges = self.editor.read(cx).redacted_ranges(
7832 start_anchor..end_anchor,
7833 &snapshot.display_snapshot,
7834 cx,
7835 );
7836
7837 let (local_selections, selected_buffer_ids): (
7838 Vec<Selection<Point>>,
7839 Vec<BufferId>,
7840 ) = self
7841 .editor_with_selections(cx)
7842 .map(|editor| {
7843 editor.update(cx, |editor, cx| {
7844 let all_selections = editor.selections.all::<Point>(cx);
7845 let selected_buffer_ids = if editor.is_singleton(cx) {
7846 Vec::new()
7847 } else {
7848 let mut selected_buffer_ids =
7849 Vec::with_capacity(all_selections.len());
7850
7851 for selection in all_selections {
7852 for buffer_id in snapshot
7853 .buffer_snapshot
7854 .buffer_ids_for_range(selection.range())
7855 {
7856 if selected_buffer_ids.last() != Some(&buffer_id) {
7857 selected_buffer_ids.push(buffer_id);
7858 }
7859 }
7860 }
7861
7862 selected_buffer_ids
7863 };
7864
7865 let mut selections = editor
7866 .selections
7867 .disjoint_in_range(start_anchor..end_anchor, cx);
7868 selections.extend(editor.selections.pending(cx));
7869
7870 (selections, selected_buffer_ids)
7871 })
7872 })
7873 .unwrap_or_default();
7874
7875 let (selections, mut active_rows, newest_selection_head) = self
7876 .layout_selections(
7877 start_anchor,
7878 end_anchor,
7879 &local_selections,
7880 &snapshot,
7881 start_row,
7882 end_row,
7883 window,
7884 cx,
7885 );
7886 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
7887 editor.active_breakpoints(start_row..end_row, window, cx)
7888 });
7889 if cx.has_flag::<DebuggerFeatureFlag>() {
7890 for (display_row, (_, bp, state)) in &breakpoint_rows {
7891 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
7892 active_rows.entry(*display_row).or_default().breakpoint = true;
7893 }
7894 }
7895 }
7896
7897 let line_numbers = self.layout_line_numbers(
7898 Some(&gutter_hitbox),
7899 gutter_dimensions,
7900 line_height,
7901 scroll_position,
7902 start_row..end_row,
7903 &row_infos,
7904 &active_rows,
7905 newest_selection_head,
7906 &snapshot,
7907 window,
7908 cx,
7909 );
7910
7911 // We add the gutter breakpoint indicator to breakpoint_rows after painting
7912 // line numbers so we don't paint a line number debug accent color if a user
7913 // has their mouse over that line when a breakpoint isn't there
7914 if cx.has_flag::<DebuggerFeatureFlag>() {
7915 self.editor.update(cx, |editor, _| {
7916 if let Some(phantom_breakpoint) = &mut editor
7917 .gutter_breakpoint_indicator
7918 .0
7919 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
7920 {
7921 // Is there a non-phantom breakpoint on this line?
7922 phantom_breakpoint.collides_with_existing_breakpoint = true;
7923 breakpoint_rows
7924 .entry(phantom_breakpoint.display_row)
7925 .or_insert_with(|| {
7926 let position = snapshot.display_point_to_anchor(
7927 DisplayPoint::new(phantom_breakpoint.display_row, 0),
7928 Bias::Right,
7929 );
7930 let breakpoint = Breakpoint::new_standard();
7931 phantom_breakpoint.collides_with_existing_breakpoint =
7932 false;
7933 (position, breakpoint, None)
7934 });
7935 }
7936 })
7937 }
7938
7939 let mut expand_toggles =
7940 window.with_element_namespace("expand_toggles", |window| {
7941 self.layout_expand_toggles(
7942 &gutter_hitbox,
7943 gutter_dimensions,
7944 em_width,
7945 line_height,
7946 scroll_position,
7947 &row_infos,
7948 window,
7949 cx,
7950 )
7951 });
7952
7953 let mut crease_toggles =
7954 window.with_element_namespace("crease_toggles", |window| {
7955 self.layout_crease_toggles(
7956 start_row..end_row,
7957 &row_infos,
7958 &active_rows,
7959 &snapshot,
7960 window,
7961 cx,
7962 )
7963 });
7964 let crease_trailers =
7965 window.with_element_namespace("crease_trailers", |window| {
7966 self.layout_crease_trailers(
7967 row_infos.iter().copied(),
7968 &snapshot,
7969 window,
7970 cx,
7971 )
7972 });
7973
7974 let display_hunks = self.layout_gutter_diff_hunks(
7975 line_height,
7976 &gutter_hitbox,
7977 start_row..end_row,
7978 &snapshot,
7979 window,
7980 cx,
7981 );
7982
7983 let mut line_layouts = Self::layout_lines(
7984 start_row..end_row,
7985 &snapshot,
7986 &self.style,
7987 editor_width,
7988 is_row_soft_wrapped,
7989 window,
7990 cx,
7991 );
7992 let new_fold_widths = line_layouts
7993 .iter()
7994 .flat_map(|layout| &layout.fragments)
7995 .filter_map(|fragment| {
7996 if let LineFragment::Element { id, size, .. } = fragment {
7997 Some((*id, size.width))
7998 } else {
7999 None
8000 }
8001 });
8002 if self.editor.update(cx, |editor, cx| {
8003 editor.update_fold_widths(new_fold_widths, cx)
8004 }) {
8005 // If the fold widths have changed, we need to prepaint
8006 // the element again to account for any changes in
8007 // wrapping.
8008 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8009 }
8010
8011 let longest_line_blame_width = self
8012 .editor
8013 .update(cx, |editor, cx| {
8014 if !editor.show_git_blame_inline {
8015 return None;
8016 }
8017 let blame = editor.blame.as_ref()?;
8018 let blame_entry = blame
8019 .update(cx, |blame, cx| {
8020 let row_infos =
8021 snapshot.row_infos(snapshot.longest_row()).next()?;
8022 blame.blame_for_rows(&[row_infos], cx).next()
8023 })
8024 .flatten()?;
8025 let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
8026 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
8027 Some(
8028 element
8029 .layout_as_root(AvailableSpace::min_size(), window, cx)
8030 .width
8031 + inline_blame_padding,
8032 )
8033 })
8034 .unwrap_or(Pixels::ZERO);
8035
8036 let longest_line_width = layout_line(
8037 snapshot.longest_row(),
8038 &snapshot,
8039 &style,
8040 editor_width,
8041 is_row_soft_wrapped,
8042 window,
8043 cx,
8044 )
8045 .width;
8046
8047 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
8048 text_hitbox.bounds,
8049 glyph_grid_cell,
8050 size(longest_line_width, max_row.as_f32() * line_height),
8051 longest_line_blame_width,
8052 editor_width,
8053 EditorSettings::get_global(cx),
8054 );
8055
8056 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
8057
8058 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
8059 snapshot.sticky_header_excerpt(scroll_position.y)
8060 } else {
8061 None
8062 };
8063 let sticky_header_excerpt_id =
8064 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
8065
8066 let blocks = window.with_element_namespace("blocks", |window| {
8067 self.render_blocks(
8068 start_row..end_row,
8069 &snapshot,
8070 &hitbox,
8071 &text_hitbox,
8072 editor_width,
8073 &mut scroll_width,
8074 &editor_margins,
8075 em_width,
8076 gutter_dimensions.full_width(),
8077 line_height,
8078 &mut line_layouts,
8079 &local_selections,
8080 &selected_buffer_ids,
8081 is_row_soft_wrapped,
8082 sticky_header_excerpt_id,
8083 window,
8084 cx,
8085 )
8086 });
8087 let (mut blocks, row_block_types) = match blocks {
8088 Ok(blocks) => blocks,
8089 Err(resized_blocks) => {
8090 self.editor.update(cx, |editor, cx| {
8091 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
8092 });
8093 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8094 }
8095 };
8096
8097 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
8098 window.with_element_namespace("blocks", |window| {
8099 self.layout_sticky_buffer_header(
8100 sticky_header_excerpt,
8101 scroll_position.y,
8102 line_height,
8103 right_margin,
8104 &snapshot,
8105 &hitbox,
8106 &selected_buffer_ids,
8107 &blocks,
8108 window,
8109 cx,
8110 )
8111 })
8112 });
8113
8114 let start_buffer_row =
8115 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
8116 let end_buffer_row =
8117 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
8118
8119 let scroll_max = point(
8120 ((scroll_width - editor_content_width) / em_width).max(0.0),
8121 max_scroll_top,
8122 );
8123
8124 self.editor.update(cx, |editor, cx| {
8125 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
8126
8127 let autoscrolled = if autoscroll_horizontally {
8128 editor.autoscroll_horizontally(
8129 start_row,
8130 editor_content_width,
8131 scroll_width,
8132 em_width,
8133 &line_layouts,
8134 cx,
8135 )
8136 } else {
8137 false
8138 };
8139
8140 if clamped || autoscrolled {
8141 snapshot = editor.snapshot(window, cx);
8142 scroll_position = snapshot.scroll_position();
8143 }
8144 });
8145
8146 let scroll_pixel_position = point(
8147 scroll_position.x * em_width,
8148 scroll_position.y * line_height,
8149 );
8150
8151 let indent_guides = self.layout_indent_guides(
8152 content_origin,
8153 text_hitbox.origin,
8154 start_buffer_row..end_buffer_row,
8155 scroll_pixel_position,
8156 line_height,
8157 &snapshot,
8158 window,
8159 cx,
8160 );
8161
8162 let crease_trailers =
8163 window.with_element_namespace("crease_trailers", |window| {
8164 self.prepaint_crease_trailers(
8165 crease_trailers,
8166 &line_layouts,
8167 line_height,
8168 content_origin,
8169 scroll_pixel_position,
8170 em_width,
8171 window,
8172 cx,
8173 )
8174 });
8175
8176 let (inline_completion_popover, inline_completion_popover_origin) = self
8177 .editor
8178 .update(cx, |editor, cx| {
8179 editor.render_edit_prediction_popover(
8180 &text_hitbox.bounds,
8181 content_origin,
8182 right_margin,
8183 &snapshot,
8184 start_row..end_row,
8185 scroll_position.y,
8186 scroll_position.y + height_in_lines,
8187 &line_layouts,
8188 line_height,
8189 scroll_pixel_position,
8190 newest_selection_head,
8191 editor_width,
8192 &style,
8193 window,
8194 cx,
8195 )
8196 })
8197 .unzip();
8198
8199 let mut inline_diagnostics = self.layout_inline_diagnostics(
8200 &line_layouts,
8201 &crease_trailers,
8202 &row_block_types,
8203 content_origin,
8204 scroll_pixel_position,
8205 inline_completion_popover_origin,
8206 start_row,
8207 end_row,
8208 line_height,
8209 em_width,
8210 &style,
8211 window,
8212 cx,
8213 );
8214
8215 let mut inline_blame = None;
8216 let mut inline_code_actions = None;
8217 if let Some(newest_selection_head) = newest_selection_head {
8218 let display_row = newest_selection_head.row();
8219 if (start_row..end_row).contains(&display_row)
8220 && !row_block_types.contains_key(&display_row)
8221 {
8222 inline_code_actions = self.layout_inline_code_actions(
8223 newest_selection_head,
8224 content_origin,
8225 scroll_pixel_position,
8226 line_height,
8227 &snapshot,
8228 window,
8229 cx,
8230 );
8231
8232 let line_ix = display_row.minus(start_row) as usize;
8233 let row_info = &row_infos[line_ix];
8234 let line_layout = &line_layouts[line_ix];
8235 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
8236
8237 inline_blame = self.layout_inline_blame(
8238 display_row,
8239 row_info,
8240 line_layout,
8241 crease_trailer_layout,
8242 em_width,
8243 content_origin,
8244 scroll_pixel_position,
8245 line_height,
8246 &text_hitbox,
8247 window,
8248 cx,
8249 );
8250 if inline_blame.is_some() {
8251 // Blame overrides inline diagnostics
8252 inline_diagnostics.remove(&display_row);
8253 }
8254 }
8255 }
8256
8257 let blamed_display_rows = self.layout_blame_entries(
8258 &row_infos,
8259 em_width,
8260 scroll_position,
8261 line_height,
8262 &gutter_hitbox,
8263 gutter_dimensions.git_blame_entries_width,
8264 window,
8265 cx,
8266 );
8267
8268 self.editor.update(cx, |editor, cx| {
8269 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
8270
8271 let autoscrolled = if autoscroll_horizontally {
8272 editor.autoscroll_horizontally(
8273 start_row,
8274 editor_content_width,
8275 scroll_width,
8276 em_width,
8277 &line_layouts,
8278 cx,
8279 )
8280 } else {
8281 false
8282 };
8283
8284 if clamped || autoscrolled {
8285 snapshot = editor.snapshot(window, cx);
8286 scroll_position = snapshot.scroll_position();
8287 }
8288 });
8289
8290 let line_elements = self.prepaint_lines(
8291 start_row,
8292 &mut line_layouts,
8293 line_height,
8294 scroll_pixel_position,
8295 content_origin,
8296 window,
8297 cx,
8298 );
8299
8300 window.with_element_namespace("blocks", |window| {
8301 self.layout_blocks(
8302 &mut blocks,
8303 &hitbox,
8304 line_height,
8305 scroll_pixel_position,
8306 window,
8307 cx,
8308 );
8309 });
8310
8311 let cursors = self.collect_cursors(&snapshot, cx);
8312 let visible_row_range = start_row..end_row;
8313 let non_visible_cursors = cursors
8314 .iter()
8315 .any(|c| !visible_row_range.contains(&c.0.row()));
8316
8317 let visible_cursors = self.layout_visible_cursors(
8318 &snapshot,
8319 &selections,
8320 &row_block_types,
8321 start_row..end_row,
8322 &line_layouts,
8323 &text_hitbox,
8324 content_origin,
8325 scroll_position,
8326 scroll_pixel_position,
8327 line_height,
8328 em_width,
8329 em_advance,
8330 autoscroll_containing_element,
8331 window,
8332 cx,
8333 );
8334
8335 let scrollbars_layout = self.layout_scrollbars(
8336 &snapshot,
8337 &scrollbar_layout_information,
8338 content_offset,
8339 scroll_position,
8340 non_visible_cursors,
8341 right_margin,
8342 editor_width,
8343 window,
8344 cx,
8345 );
8346
8347 let gutter_settings = EditorSettings::get_global(cx).gutter;
8348
8349 let context_menu_layout =
8350 if let Some(newest_selection_head) = newest_selection_head {
8351 let newest_selection_point =
8352 newest_selection_head.to_point(&snapshot.display_snapshot);
8353 if (start_row..end_row).contains(&newest_selection_head.row()) {
8354 self.layout_cursor_popovers(
8355 line_height,
8356 &text_hitbox,
8357 content_origin,
8358 right_margin,
8359 start_row,
8360 scroll_pixel_position,
8361 &line_layouts,
8362 newest_selection_head,
8363 newest_selection_point,
8364 &style,
8365 window,
8366 cx,
8367 )
8368 } else {
8369 None
8370 }
8371 } else {
8372 None
8373 };
8374
8375 self.layout_gutter_menu(
8376 line_height,
8377 &text_hitbox,
8378 content_origin,
8379 right_margin,
8380 scroll_pixel_position,
8381 gutter_dimensions.width - gutter_dimensions.left_padding,
8382 window,
8383 cx,
8384 );
8385
8386 let test_indicators = if gutter_settings.runnables {
8387 self.layout_run_indicators(
8388 line_height,
8389 start_row..end_row,
8390 &row_infos,
8391 scroll_pixel_position,
8392 &gutter_dimensions,
8393 &gutter_hitbox,
8394 &display_hunks,
8395 &snapshot,
8396 &mut breakpoint_rows,
8397 window,
8398 cx,
8399 )
8400 } else {
8401 Vec::new()
8402 };
8403
8404 let show_breakpoints = snapshot
8405 .show_breakpoints
8406 .unwrap_or(gutter_settings.breakpoints);
8407 let breakpoints = if cx.has_flag::<DebuggerFeatureFlag>() && show_breakpoints {
8408 self.layout_breakpoints(
8409 line_height,
8410 start_row..end_row,
8411 scroll_pixel_position,
8412 &gutter_dimensions,
8413 &gutter_hitbox,
8414 &display_hunks,
8415 &snapshot,
8416 breakpoint_rows,
8417 &row_infos,
8418 window,
8419 cx,
8420 )
8421 } else {
8422 vec![]
8423 };
8424
8425 self.layout_signature_help(
8426 &hitbox,
8427 content_origin,
8428 scroll_pixel_position,
8429 newest_selection_head,
8430 start_row,
8431 &line_layouts,
8432 line_height,
8433 em_width,
8434 context_menu_layout,
8435 window,
8436 cx,
8437 );
8438
8439 if !cx.has_active_drag() {
8440 self.layout_hover_popovers(
8441 &snapshot,
8442 &hitbox,
8443 start_row..end_row,
8444 content_origin,
8445 scroll_pixel_position,
8446 &line_layouts,
8447 line_height,
8448 em_width,
8449 context_menu_layout,
8450 window,
8451 cx,
8452 );
8453 }
8454
8455 let mouse_context_menu = self.layout_mouse_context_menu(
8456 &snapshot,
8457 start_row..end_row,
8458 content_origin,
8459 window,
8460 cx,
8461 );
8462
8463 window.with_element_namespace("crease_toggles", |window| {
8464 self.prepaint_crease_toggles(
8465 &mut crease_toggles,
8466 line_height,
8467 &gutter_dimensions,
8468 gutter_settings,
8469 scroll_pixel_position,
8470 &gutter_hitbox,
8471 window,
8472 cx,
8473 )
8474 });
8475
8476 window.with_element_namespace("expand_toggles", |window| {
8477 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
8478 });
8479
8480 let minimap = window.with_element_namespace("minimap", |window| {
8481 self.layout_minimap(
8482 &snapshot,
8483 minimap_width,
8484 scroll_position,
8485 &scrollbar_layout_information,
8486 scrollbars_layout.as_ref(),
8487 window,
8488 cx,
8489 )
8490 });
8491
8492 let invisible_symbol_font_size = font_size / 2.;
8493 let tab_invisible = window.text_system().shape_line(
8494 "→".into(),
8495 invisible_symbol_font_size,
8496 &[TextRun {
8497 len: "→".len(),
8498 font: self.style.text.font(),
8499 color: cx.theme().colors().editor_invisible,
8500 background_color: None,
8501 underline: None,
8502 strikethrough: None,
8503 }],
8504 );
8505 let space_invisible = window.text_system().shape_line(
8506 "•".into(),
8507 invisible_symbol_font_size,
8508 &[TextRun {
8509 len: "•".len(),
8510 font: self.style.text.font(),
8511 color: cx.theme().colors().editor_invisible,
8512 background_color: None,
8513 underline: None,
8514 strikethrough: None,
8515 }],
8516 );
8517
8518 let mode = snapshot.mode.clone();
8519
8520 let position_map = Rc::new(PositionMap {
8521 size: bounds.size,
8522 visible_row_range,
8523 scroll_pixel_position,
8524 scroll_max,
8525 line_layouts,
8526 line_height,
8527 em_width,
8528 em_advance,
8529 snapshot,
8530 gutter_hitbox: gutter_hitbox.clone(),
8531 text_hitbox: text_hitbox.clone(),
8532 });
8533
8534 self.editor.update(cx, |editor, _| {
8535 editor.last_position_map = Some(position_map.clone())
8536 });
8537
8538 let diff_hunk_controls = if is_read_only {
8539 vec![]
8540 } else {
8541 self.layout_diff_hunk_controls(
8542 start_row..end_row,
8543 &row_infos,
8544 &text_hitbox,
8545 &position_map,
8546 newest_selection_head,
8547 line_height,
8548 right_margin,
8549 scroll_pixel_position,
8550 &display_hunks,
8551 &highlighted_rows,
8552 self.editor.clone(),
8553 window,
8554 cx,
8555 )
8556 };
8557
8558 EditorLayout {
8559 mode,
8560 position_map,
8561 visible_display_row_range: start_row..end_row,
8562 wrap_guides,
8563 indent_guides,
8564 hitbox,
8565 gutter_hitbox,
8566 display_hunks,
8567 content_origin,
8568 scrollbars_layout,
8569 minimap,
8570 active_rows,
8571 highlighted_rows,
8572 highlighted_ranges,
8573 highlighted_gutter_ranges,
8574 redacted_ranges,
8575 line_elements,
8576 line_numbers,
8577 blamed_display_rows,
8578 inline_diagnostics,
8579 inline_blame,
8580 inline_code_actions,
8581 blocks,
8582 cursors,
8583 visible_cursors,
8584 selections,
8585 inline_completion_popover,
8586 diff_hunk_controls,
8587 mouse_context_menu,
8588 test_indicators,
8589 breakpoints,
8590 crease_toggles,
8591 crease_trailers,
8592 tab_invisible,
8593 space_invisible,
8594 sticky_buffer_header,
8595 expand_toggles,
8596 }
8597 })
8598 })
8599 })
8600 }
8601
8602 fn paint(
8603 &mut self,
8604 _: Option<&GlobalElementId>,
8605 __inspector_id: Option<&gpui::InspectorElementId>,
8606 bounds: Bounds<gpui::Pixels>,
8607 _: &mut Self::RequestLayoutState,
8608 layout: &mut Self::PrepaintState,
8609 window: &mut Window,
8610 cx: &mut App,
8611 ) {
8612 let focus_handle = self.editor.focus_handle(cx);
8613 let key_context = self
8614 .editor
8615 .update(cx, |editor, cx| editor.key_context(window, cx));
8616
8617 window.set_key_context(key_context);
8618 window.handle_input(
8619 &focus_handle,
8620 ElementInputHandler::new(bounds, self.editor.clone()),
8621 cx,
8622 );
8623 self.register_actions(window, cx);
8624 self.register_key_listeners(window, cx, layout);
8625
8626 let text_style = TextStyleRefinement {
8627 font_size: Some(self.style.text.font_size),
8628 line_height: Some(self.style.text.line_height),
8629 ..Default::default()
8630 };
8631 let rem_size = self.rem_size(cx);
8632 window.with_rem_size(rem_size, |window| {
8633 window.with_text_style(Some(text_style), |window| {
8634 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8635 self.paint_mouse_listeners(layout, window, cx);
8636 self.paint_background(layout, window, cx);
8637 self.paint_indent_guides(layout, window, cx);
8638
8639 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8640 self.paint_blamed_display_rows(layout, window, cx);
8641 self.paint_line_numbers(layout, window, cx);
8642 }
8643
8644 self.paint_text(layout, window, cx);
8645
8646 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8647 self.paint_gutter_highlights(layout, window, cx);
8648 self.paint_gutter_indicators(layout, window, cx);
8649 }
8650
8651 if !layout.blocks.is_empty() {
8652 window.with_element_namespace("blocks", |window| {
8653 self.paint_blocks(layout, window, cx);
8654 });
8655 }
8656
8657 window.with_element_namespace("blocks", |window| {
8658 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
8659 sticky_header.paint(window, cx)
8660 }
8661 });
8662
8663 self.paint_minimap(layout, window, cx);
8664 self.paint_scrollbars(layout, window, cx);
8665 self.paint_inline_completion_popover(layout, window, cx);
8666 self.paint_mouse_context_menu(layout, window, cx);
8667 });
8668 })
8669 })
8670 }
8671}
8672
8673pub(super) fn gutter_bounds(
8674 editor_bounds: Bounds<Pixels>,
8675 gutter_dimensions: GutterDimensions,
8676) -> Bounds<Pixels> {
8677 Bounds {
8678 origin: editor_bounds.origin,
8679 size: size(gutter_dimensions.width, editor_bounds.size.height),
8680 }
8681}
8682
8683#[derive(Clone, Copy)]
8684struct ContextMenuLayout {
8685 y_flipped: bool,
8686 bounds: Bounds<Pixels>,
8687}
8688
8689/// Holds information required for layouting the editor scrollbars.
8690struct ScrollbarLayoutInformation {
8691 /// The bounds of the editor area (excluding the content offset).
8692 editor_bounds: Bounds<Pixels>,
8693 /// The available range to scroll within the document.
8694 scroll_range: Size<Pixels>,
8695 /// The space available for one glyph in the editor.
8696 glyph_grid_cell: Size<Pixels>,
8697}
8698
8699impl ScrollbarLayoutInformation {
8700 pub fn new(
8701 editor_bounds: Bounds<Pixels>,
8702 glyph_grid_cell: Size<Pixels>,
8703 document_size: Size<Pixels>,
8704 longest_line_blame_width: Pixels,
8705 editor_width: Pixels,
8706 settings: &EditorSettings,
8707 ) -> Self {
8708 let vertical_overscroll = match settings.scroll_beyond_last_line {
8709 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
8710 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
8711 ScrollBeyondLastLine::VerticalScrollMargin => {
8712 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
8713 }
8714 };
8715
8716 let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
8717 glyph_grid_cell.width
8718 } else {
8719 px(0.0)
8720 };
8721
8722 let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
8723
8724 let scroll_range = document_size + overscroll;
8725
8726 ScrollbarLayoutInformation {
8727 editor_bounds,
8728 scroll_range,
8729 glyph_grid_cell,
8730 }
8731 }
8732}
8733
8734impl IntoElement for EditorElement {
8735 type Element = Self;
8736
8737 fn into_element(self) -> Self::Element {
8738 self
8739 }
8740}
8741
8742pub struct EditorLayout {
8743 position_map: Rc<PositionMap>,
8744 hitbox: Hitbox,
8745 gutter_hitbox: Hitbox,
8746 content_origin: gpui::Point<Pixels>,
8747 scrollbars_layout: Option<EditorScrollbars>,
8748 minimap: Option<MinimapLayout>,
8749 mode: EditorMode,
8750 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
8751 indent_guides: Option<Vec<IndentGuideLayout>>,
8752 visible_display_row_range: Range<DisplayRow>,
8753 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
8754 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
8755 line_elements: SmallVec<[AnyElement; 1]>,
8756 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
8757 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
8758 blamed_display_rows: Option<Vec<AnyElement>>,
8759 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
8760 inline_blame: Option<AnyElement>,
8761 inline_code_actions: Option<AnyElement>,
8762 blocks: Vec<BlockLayout>,
8763 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
8764 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
8765 redacted_ranges: Vec<Range<DisplayPoint>>,
8766 cursors: Vec<(DisplayPoint, Hsla)>,
8767 visible_cursors: Vec<CursorLayout>,
8768 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
8769 test_indicators: Vec<AnyElement>,
8770 breakpoints: Vec<AnyElement>,
8771 crease_toggles: Vec<Option<AnyElement>>,
8772 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
8773 diff_hunk_controls: Vec<AnyElement>,
8774 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
8775 inline_completion_popover: Option<AnyElement>,
8776 mouse_context_menu: Option<AnyElement>,
8777 tab_invisible: ShapedLine,
8778 space_invisible: ShapedLine,
8779 sticky_buffer_header: Option<AnyElement>,
8780}
8781
8782impl EditorLayout {
8783 fn line_end_overshoot(&self) -> Pixels {
8784 0.15 * self.position_map.line_height
8785 }
8786}
8787
8788struct LineNumberLayout {
8789 shaped_line: ShapedLine,
8790 hitbox: Option<Hitbox>,
8791}
8792
8793struct ColoredRange<T> {
8794 start: T,
8795 end: T,
8796 color: Hsla,
8797}
8798
8799impl Along for ScrollbarAxes {
8800 type Unit = bool;
8801
8802 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
8803 match axis {
8804 ScrollbarAxis::Horizontal => self.horizontal,
8805 ScrollbarAxis::Vertical => self.vertical,
8806 }
8807 }
8808
8809 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
8810 match axis {
8811 ScrollbarAxis::Horizontal => ScrollbarAxes {
8812 horizontal: f(self.horizontal),
8813 vertical: self.vertical,
8814 },
8815 ScrollbarAxis::Vertical => ScrollbarAxes {
8816 horizontal: self.horizontal,
8817 vertical: f(self.vertical),
8818 },
8819 }
8820 }
8821}
8822
8823#[derive(Clone)]
8824struct EditorScrollbars {
8825 pub vertical: Option<ScrollbarLayout>,
8826 pub horizontal: Option<ScrollbarLayout>,
8827 pub visible: bool,
8828}
8829
8830impl EditorScrollbars {
8831 pub fn from_scrollbar_axes(
8832 settings_visibility: ScrollbarAxes,
8833 layout_information: &ScrollbarLayoutInformation,
8834 content_offset: gpui::Point<Pixels>,
8835 scroll_position: gpui::Point<f32>,
8836 scrollbar_width: Pixels,
8837 right_margin: Pixels,
8838 editor_width: Pixels,
8839 show_scrollbars: bool,
8840 scrollbar_state: Option<&ActiveScrollbarState>,
8841 window: &mut Window,
8842 ) -> Self {
8843 let ScrollbarLayoutInformation {
8844 editor_bounds,
8845 scroll_range,
8846 glyph_grid_cell,
8847 } = layout_information;
8848
8849 let viewport_size = size(editor_width, editor_bounds.size.height);
8850
8851 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
8852 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
8853 Corner::BottomLeft,
8854 editor_bounds.bottom_left(),
8855 size(
8856 // The horizontal viewport size differs from the space available for the
8857 // horizontal scrollbar, so we have to manually stich it together here.
8858 editor_bounds.size.width - right_margin,
8859 scrollbar_width,
8860 ),
8861 ),
8862 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
8863 Corner::TopRight,
8864 editor_bounds.top_right(),
8865 size(scrollbar_width, viewport_size.height),
8866 ),
8867 };
8868
8869 let mut create_scrollbar_layout = |axis| {
8870 settings_visibility
8871 .along(axis)
8872 .then(|| {
8873 (
8874 viewport_size.along(axis) - content_offset.along(axis),
8875 scroll_range.along(axis),
8876 )
8877 })
8878 .filter(|(viewport_size, scroll_range)| {
8879 // The scrollbar should only be rendered if the content does
8880 // not entirely fit into the editor
8881 // However, this only applies to the horizontal scrollbar, as information about the
8882 // vertical scrollbar layout is always needed for scrollbar diagnostics.
8883 axis != ScrollbarAxis::Horizontal || viewport_size < scroll_range
8884 })
8885 .map(|(viewport_size, scroll_range)| {
8886 ScrollbarLayout::new(
8887 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
8888 viewport_size,
8889 scroll_range,
8890 glyph_grid_cell.along(axis),
8891 content_offset.along(axis),
8892 scroll_position.along(axis),
8893 show_scrollbars,
8894 axis,
8895 )
8896 .with_thumb_state(
8897 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
8898 )
8899 })
8900 };
8901
8902 Self {
8903 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
8904 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
8905 visible: show_scrollbars,
8906 }
8907 }
8908
8909 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
8910 [
8911 (&self.vertical, ScrollbarAxis::Vertical),
8912 (&self.horizontal, ScrollbarAxis::Horizontal),
8913 ]
8914 .into_iter()
8915 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
8916 }
8917
8918 /// Returns the currently hovered scrollbar axis, if any.
8919 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
8920 self.iter_scrollbars()
8921 .find(|s| s.0.hitbox.is_hovered(window))
8922 }
8923}
8924
8925#[derive(Clone)]
8926struct ScrollbarLayout {
8927 hitbox: Hitbox,
8928 visible_range: Range<f32>,
8929 text_unit_size: Pixels,
8930 thumb_bounds: Option<Bounds<Pixels>>,
8931 thumb_state: ScrollbarThumbState,
8932}
8933
8934impl ScrollbarLayout {
8935 const BORDER_WIDTH: Pixels = px(1.0);
8936 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
8937 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
8938 const MIN_THUMB_SIZE: Pixels = px(25.0);
8939
8940 fn new(
8941 scrollbar_track_hitbox: Hitbox,
8942 viewport_size: Pixels,
8943 scroll_range: Pixels,
8944 glyph_space: Pixels,
8945 content_offset: Pixels,
8946 scroll_position: f32,
8947 show_thumb: bool,
8948 axis: ScrollbarAxis,
8949 ) -> Self {
8950 let track_bounds = scrollbar_track_hitbox.bounds;
8951 // The length of the track available to the scrollbar thumb. We deliberately
8952 // exclude the content size here so that the thumb aligns with the content.
8953 let track_length = track_bounds.size.along(axis) - content_offset;
8954
8955 Self::new_with_hitbox_and_track_length(
8956 scrollbar_track_hitbox,
8957 track_length,
8958 viewport_size,
8959 scroll_range,
8960 glyph_space,
8961 content_offset,
8962 scroll_position,
8963 show_thumb,
8964 axis,
8965 )
8966 }
8967
8968 fn for_minimap(
8969 minimap_track_hitbox: Hitbox,
8970 visible_lines: f32,
8971 total_editor_lines: f32,
8972 minimap_line_height: Pixels,
8973 scroll_position: f32,
8974 minimap_scroll_top: f32,
8975 show_thumb: bool,
8976 ) -> Self {
8977 // The scrollbar thumb size is calculated as
8978 // (visible_content/total_content) × scrollbar_track_length.
8979 //
8980 // For the minimap's thumb layout, we leverage this by setting the
8981 // scrollbar track length to the entire document size (using minimap line
8982 // height). This creates a thumb that exactly represents the editor
8983 // viewport scaled to minimap proportions.
8984 //
8985 // We adjust the thumb position relative to `minimap_scroll_top` to
8986 // accommodate for the deliberately oversized track.
8987 //
8988 // This approach ensures that the minimap thumb accurately reflects the
8989 // editor's current scroll position whilst nicely synchronizing the minimap
8990 // thumb and scrollbar thumb.
8991 let scroll_range = total_editor_lines * minimap_line_height;
8992 let viewport_size = visible_lines * minimap_line_height;
8993
8994 let track_top_offset = -minimap_scroll_top * minimap_line_height;
8995
8996 Self::new_with_hitbox_and_track_length(
8997 minimap_track_hitbox,
8998 scroll_range,
8999 viewport_size,
9000 scroll_range,
9001 minimap_line_height,
9002 track_top_offset,
9003 scroll_position,
9004 show_thumb,
9005 ScrollbarAxis::Vertical,
9006 )
9007 }
9008
9009 fn new_with_hitbox_and_track_length(
9010 scrollbar_track_hitbox: Hitbox,
9011 track_length: Pixels,
9012 viewport_size: Pixels,
9013 scroll_range: Pixels,
9014 glyph_space: Pixels,
9015 content_offset: Pixels,
9016 scroll_position: f32,
9017 show_thumb: bool,
9018 axis: ScrollbarAxis,
9019 ) -> Self {
9020 let text_units_per_page = viewport_size / glyph_space;
9021 let visible_range = scroll_position..scroll_position + text_units_per_page;
9022 let total_text_units = scroll_range / glyph_space;
9023
9024 let thumb_percentage = text_units_per_page / total_text_units;
9025 let thumb_size = (track_length * thumb_percentage)
9026 .max(ScrollbarLayout::MIN_THUMB_SIZE)
9027 .min(track_length);
9028
9029 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
9030
9031 let content_larger_than_viewport = text_unit_divisor > 0.;
9032
9033 let text_unit_size = if content_larger_than_viewport {
9034 (track_length - thumb_size) / text_unit_divisor
9035 } else {
9036 glyph_space
9037 };
9038
9039 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
9040 Self::thumb_bounds(
9041 &scrollbar_track_hitbox,
9042 content_offset,
9043 visible_range.start,
9044 text_unit_size,
9045 thumb_size,
9046 axis,
9047 )
9048 });
9049
9050 ScrollbarLayout {
9051 hitbox: scrollbar_track_hitbox,
9052 visible_range,
9053 text_unit_size,
9054 thumb_bounds,
9055 thumb_state: Default::default(),
9056 }
9057 }
9058
9059 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
9060 if let Some(thumb_state) = thumb_state {
9061 Self {
9062 thumb_state,
9063 ..self
9064 }
9065 } else {
9066 self
9067 }
9068 }
9069
9070 fn thumb_bounds(
9071 scrollbar_track: &Hitbox,
9072 content_offset: Pixels,
9073 visible_range_start: f32,
9074 text_unit_size: Pixels,
9075 thumb_size: Pixels,
9076 axis: ScrollbarAxis,
9077 ) -> Bounds<Pixels> {
9078 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
9079 origin + content_offset + visible_range_start * text_unit_size
9080 });
9081 Bounds::new(
9082 thumb_origin,
9083 scrollbar_track.size.apply_along(axis, |_| thumb_size),
9084 )
9085 }
9086
9087 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
9088 self.thumb_bounds
9089 .is_some_and(|bounds| bounds.contains(position))
9090 }
9091
9092 fn marker_quads_for_ranges(
9093 &self,
9094 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
9095 column: Option<usize>,
9096 ) -> Vec<PaintQuad> {
9097 struct MinMax {
9098 min: Pixels,
9099 max: Pixels,
9100 }
9101 let (x_range, height_limit) = if let Some(column) = column {
9102 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
9103 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
9104 let end = start + column_width;
9105 (
9106 Range { start, end },
9107 MinMax {
9108 min: Self::MIN_MARKER_HEIGHT,
9109 max: px(f32::MAX),
9110 },
9111 )
9112 } else {
9113 (
9114 Range {
9115 start: Self::BORDER_WIDTH,
9116 end: self.hitbox.size.width,
9117 },
9118 MinMax {
9119 min: Self::LINE_MARKER_HEIGHT,
9120 max: Self::LINE_MARKER_HEIGHT,
9121 },
9122 )
9123 };
9124
9125 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
9126 let mut pixel_ranges = row_ranges
9127 .into_iter()
9128 .map(|range| {
9129 let start_y = row_to_y(range.start);
9130 let end_y = row_to_y(range.end)
9131 + self
9132 .text_unit_size
9133 .max(height_limit.min)
9134 .min(height_limit.max);
9135 ColoredRange {
9136 start: start_y,
9137 end: end_y,
9138 color: range.color,
9139 }
9140 })
9141 .peekable();
9142
9143 let mut quads = Vec::new();
9144 while let Some(mut pixel_range) = pixel_ranges.next() {
9145 while let Some(next_pixel_range) = pixel_ranges.peek() {
9146 if pixel_range.end >= next_pixel_range.start - px(1.0)
9147 && pixel_range.color == next_pixel_range.color
9148 {
9149 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
9150 pixel_ranges.next();
9151 } else {
9152 break;
9153 }
9154 }
9155
9156 let bounds = Bounds::from_corners(
9157 point(x_range.start, pixel_range.start),
9158 point(x_range.end, pixel_range.end),
9159 );
9160 quads.push(quad(
9161 bounds,
9162 Corners::default(),
9163 pixel_range.color,
9164 Edges::default(),
9165 Hsla::transparent_black(),
9166 BorderStyle::default(),
9167 ));
9168 }
9169
9170 quads
9171 }
9172}
9173
9174struct MinimapLayout {
9175 pub minimap: AnyElement,
9176 pub thumb_layout: ScrollbarLayout,
9177 pub minimap_scroll_top: f32,
9178 pub minimap_line_height: Pixels,
9179 pub thumb_border_style: MinimapThumbBorder,
9180 pub max_scroll_top: f32,
9181}
9182
9183impl MinimapLayout {
9184 const MINIMAP_WIDTH: Pixels = px(100.);
9185 /// Calculates the scroll top offset the minimap editor has to have based on the
9186 /// current scroll progress.
9187 fn calculate_minimap_top_offset(
9188 document_lines: f32,
9189 visible_editor_lines: f32,
9190 visible_minimap_lines: f32,
9191 scroll_position: f32,
9192 ) -> f32 {
9193 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
9194 if non_visible_document_lines == 0. {
9195 0.
9196 } else {
9197 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
9198 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
9199 }
9200 }
9201}
9202
9203struct CreaseTrailerLayout {
9204 element: AnyElement,
9205 bounds: Bounds<Pixels>,
9206}
9207
9208pub(crate) struct PositionMap {
9209 pub size: Size<Pixels>,
9210 pub line_height: Pixels,
9211 pub scroll_pixel_position: gpui::Point<Pixels>,
9212 pub scroll_max: gpui::Point<f32>,
9213 pub em_width: Pixels,
9214 pub em_advance: Pixels,
9215 pub visible_row_range: Range<DisplayRow>,
9216 pub line_layouts: Vec<LineWithInvisibles>,
9217 pub snapshot: EditorSnapshot,
9218 pub text_hitbox: Hitbox,
9219 pub gutter_hitbox: Hitbox,
9220}
9221
9222#[derive(Debug, Copy, Clone)]
9223pub struct PointForPosition {
9224 pub previous_valid: DisplayPoint,
9225 pub next_valid: DisplayPoint,
9226 pub exact_unclipped: DisplayPoint,
9227 pub column_overshoot_after_line_end: u32,
9228}
9229
9230impl PointForPosition {
9231 pub fn as_valid(&self) -> Option<DisplayPoint> {
9232 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
9233 Some(self.previous_valid)
9234 } else {
9235 None
9236 }
9237 }
9238}
9239
9240impl PositionMap {
9241 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
9242 let text_bounds = self.text_hitbox.bounds;
9243 let scroll_position = self.snapshot.scroll_position();
9244 let position = position - text_bounds.origin;
9245 let y = position.y.max(px(0.)).min(self.size.height);
9246 let x = position.x + (scroll_position.x * self.em_width);
9247 let row = ((y / self.line_height) + scroll_position.y) as u32;
9248
9249 let (column, x_overshoot_after_line_end) = if let Some(line) = self
9250 .line_layouts
9251 .get(row as usize - scroll_position.y as usize)
9252 {
9253 if let Some(ix) = line.index_for_x(x) {
9254 (ix as u32, px(0.))
9255 } else {
9256 (line.len as u32, px(0.).max(x - line.width))
9257 }
9258 } else {
9259 (0, x)
9260 };
9261
9262 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
9263 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
9264 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
9265
9266 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
9267 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
9268 PointForPosition {
9269 previous_valid,
9270 next_valid,
9271 exact_unclipped,
9272 column_overshoot_after_line_end,
9273 }
9274 }
9275}
9276
9277struct BlockLayout {
9278 id: BlockId,
9279 x_offset: Pixels,
9280 row: Option<DisplayRow>,
9281 element: AnyElement,
9282 available_space: Size<AvailableSpace>,
9283 style: BlockStyle,
9284 overlaps_gutter: bool,
9285 is_buffer_header: bool,
9286}
9287
9288pub fn layout_line(
9289 row: DisplayRow,
9290 snapshot: &EditorSnapshot,
9291 style: &EditorStyle,
9292 text_width: Pixels,
9293 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
9294 window: &mut Window,
9295 cx: &mut App,
9296) -> LineWithInvisibles {
9297 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
9298 LineWithInvisibles::from_chunks(
9299 chunks,
9300 &style,
9301 MAX_LINE_LEN,
9302 1,
9303 &snapshot.mode,
9304 text_width,
9305 is_row_soft_wrapped,
9306 window,
9307 cx,
9308 )
9309 .pop()
9310 .unwrap()
9311}
9312
9313#[derive(Debug)]
9314pub struct IndentGuideLayout {
9315 origin: gpui::Point<Pixels>,
9316 length: Pixels,
9317 single_indent_width: Pixels,
9318 depth: u32,
9319 active: bool,
9320 settings: IndentGuideSettings,
9321}
9322
9323pub struct CursorLayout {
9324 origin: gpui::Point<Pixels>,
9325 block_width: Pixels,
9326 line_height: Pixels,
9327 color: Hsla,
9328 shape: CursorShape,
9329 block_text: Option<ShapedLine>,
9330 cursor_name: Option<AnyElement>,
9331}
9332
9333#[derive(Debug)]
9334pub struct CursorName {
9335 string: SharedString,
9336 color: Hsla,
9337 is_top_row: bool,
9338}
9339
9340impl CursorLayout {
9341 pub fn new(
9342 origin: gpui::Point<Pixels>,
9343 block_width: Pixels,
9344 line_height: Pixels,
9345 color: Hsla,
9346 shape: CursorShape,
9347 block_text: Option<ShapedLine>,
9348 ) -> CursorLayout {
9349 CursorLayout {
9350 origin,
9351 block_width,
9352 line_height,
9353 color,
9354 shape,
9355 block_text,
9356 cursor_name: None,
9357 }
9358 }
9359
9360 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
9361 Bounds {
9362 origin: self.origin + origin,
9363 size: size(self.block_width, self.line_height),
9364 }
9365 }
9366
9367 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
9368 match self.shape {
9369 CursorShape::Bar => Bounds {
9370 origin: self.origin + origin,
9371 size: size(px(2.0), self.line_height),
9372 },
9373 CursorShape::Block | CursorShape::Hollow => Bounds {
9374 origin: self.origin + origin,
9375 size: size(self.block_width, self.line_height),
9376 },
9377 CursorShape::Underline => Bounds {
9378 origin: self.origin
9379 + origin
9380 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
9381 size: size(self.block_width, px(2.0)),
9382 },
9383 }
9384 }
9385
9386 pub fn layout(
9387 &mut self,
9388 origin: gpui::Point<Pixels>,
9389 cursor_name: Option<CursorName>,
9390 window: &mut Window,
9391 cx: &mut App,
9392 ) {
9393 if let Some(cursor_name) = cursor_name {
9394 let bounds = self.bounds(origin);
9395 let text_size = self.line_height / 1.5;
9396
9397 let name_origin = if cursor_name.is_top_row {
9398 point(bounds.right() - px(1.), bounds.top())
9399 } else {
9400 match self.shape {
9401 CursorShape::Bar => point(
9402 bounds.right() - px(2.),
9403 bounds.top() - text_size / 2. - px(1.),
9404 ),
9405 _ => point(
9406 bounds.right() - px(1.),
9407 bounds.top() - text_size / 2. - px(1.),
9408 ),
9409 }
9410 };
9411 let mut name_element = div()
9412 .bg(self.color)
9413 .text_size(text_size)
9414 .px_0p5()
9415 .line_height(text_size + px(2.))
9416 .text_color(cursor_name.color)
9417 .child(cursor_name.string.clone())
9418 .into_any_element();
9419
9420 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
9421
9422 self.cursor_name = Some(name_element);
9423 }
9424 }
9425
9426 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
9427 let bounds = self.bounds(origin);
9428
9429 //Draw background or border quad
9430 let cursor = if matches!(self.shape, CursorShape::Hollow) {
9431 outline(bounds, self.color, BorderStyle::Solid)
9432 } else {
9433 fill(bounds, self.color)
9434 };
9435
9436 if let Some(name) = &mut self.cursor_name {
9437 name.paint(window, cx);
9438 }
9439
9440 window.paint_quad(cursor);
9441
9442 if let Some(block_text) = &self.block_text {
9443 block_text
9444 .paint(self.origin + origin, self.line_height, window, cx)
9445 .log_err();
9446 }
9447 }
9448
9449 pub fn shape(&self) -> CursorShape {
9450 self.shape
9451 }
9452}
9453
9454#[derive(Debug)]
9455pub struct HighlightedRange {
9456 pub start_y: Pixels,
9457 pub line_height: Pixels,
9458 pub lines: Vec<HighlightedRangeLine>,
9459 pub color: Hsla,
9460 pub corner_radius: Pixels,
9461}
9462
9463#[derive(Debug)]
9464pub struct HighlightedRangeLine {
9465 pub start_x: Pixels,
9466 pub end_x: Pixels,
9467}
9468
9469impl HighlightedRange {
9470 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
9471 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
9472 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
9473 self.paint_lines(
9474 self.start_y + self.line_height,
9475 &self.lines[1..],
9476 bounds,
9477 window,
9478 );
9479 } else {
9480 self.paint_lines(self.start_y, &self.lines, bounds, window);
9481 }
9482 }
9483
9484 fn paint_lines(
9485 &self,
9486 start_y: Pixels,
9487 lines: &[HighlightedRangeLine],
9488 _bounds: Bounds<Pixels>,
9489 window: &mut Window,
9490 ) {
9491 if lines.is_empty() {
9492 return;
9493 }
9494
9495 let first_line = lines.first().unwrap();
9496 let last_line = lines.last().unwrap();
9497
9498 let first_top_left = point(first_line.start_x, start_y);
9499 let first_top_right = point(first_line.end_x, start_y);
9500
9501 let curve_height = point(Pixels::ZERO, self.corner_radius);
9502 let curve_width = |start_x: Pixels, end_x: Pixels| {
9503 let max = (end_x - start_x) / 2.;
9504 let width = if max < self.corner_radius {
9505 max
9506 } else {
9507 self.corner_radius
9508 };
9509
9510 point(width, Pixels::ZERO)
9511 };
9512
9513 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
9514 let mut builder = gpui::PathBuilder::fill();
9515 builder.move_to(first_top_right - top_curve_width);
9516 builder.curve_to(first_top_right + curve_height, first_top_right);
9517
9518 let mut iter = lines.iter().enumerate().peekable();
9519 while let Some((ix, line)) = iter.next() {
9520 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
9521
9522 if let Some((_, next_line)) = iter.peek() {
9523 let next_top_right = point(next_line.end_x, bottom_right.y);
9524
9525 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
9526 Ordering::Equal => {
9527 builder.line_to(bottom_right);
9528 }
9529 Ordering::Less => {
9530 let curve_width = curve_width(next_top_right.x, bottom_right.x);
9531 builder.line_to(bottom_right - curve_height);
9532 if self.corner_radius > Pixels::ZERO {
9533 builder.curve_to(bottom_right - curve_width, bottom_right);
9534 }
9535 builder.line_to(next_top_right + curve_width);
9536 if self.corner_radius > Pixels::ZERO {
9537 builder.curve_to(next_top_right + curve_height, next_top_right);
9538 }
9539 }
9540 Ordering::Greater => {
9541 let curve_width = curve_width(bottom_right.x, next_top_right.x);
9542 builder.line_to(bottom_right - curve_height);
9543 if self.corner_radius > Pixels::ZERO {
9544 builder.curve_to(bottom_right + curve_width, bottom_right);
9545 }
9546 builder.line_to(next_top_right - curve_width);
9547 if self.corner_radius > Pixels::ZERO {
9548 builder.curve_to(next_top_right + curve_height, next_top_right);
9549 }
9550 }
9551 }
9552 } else {
9553 let curve_width = curve_width(line.start_x, line.end_x);
9554 builder.line_to(bottom_right - curve_height);
9555 if self.corner_radius > Pixels::ZERO {
9556 builder.curve_to(bottom_right - curve_width, bottom_right);
9557 }
9558
9559 let bottom_left = point(line.start_x, bottom_right.y);
9560 builder.line_to(bottom_left + curve_width);
9561 if self.corner_radius > Pixels::ZERO {
9562 builder.curve_to(bottom_left - curve_height, bottom_left);
9563 }
9564 }
9565 }
9566
9567 if first_line.start_x > last_line.start_x {
9568 let curve_width = curve_width(last_line.start_x, first_line.start_x);
9569 let second_top_left = point(last_line.start_x, start_y + self.line_height);
9570 builder.line_to(second_top_left + curve_height);
9571 if self.corner_radius > Pixels::ZERO {
9572 builder.curve_to(second_top_left + curve_width, second_top_left);
9573 }
9574 let first_bottom_left = point(first_line.start_x, second_top_left.y);
9575 builder.line_to(first_bottom_left - curve_width);
9576 if self.corner_radius > Pixels::ZERO {
9577 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
9578 }
9579 }
9580
9581 builder.line_to(first_top_left + curve_height);
9582 if self.corner_radius > Pixels::ZERO {
9583 builder.curve_to(first_top_left + top_curve_width, first_top_left);
9584 }
9585 builder.line_to(first_top_right - top_curve_width);
9586
9587 if let Ok(path) = builder.build() {
9588 window.paint_path(path, self.color);
9589 }
9590 }
9591}
9592
9593enum CursorPopoverType {
9594 CodeContextMenu,
9595 EditPrediction,
9596}
9597
9598pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9599 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
9600}
9601
9602fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9603 (delta.pow(1.2) / 300.0).into()
9604}
9605
9606pub fn register_action<T: Action>(
9607 editor: &Entity<Editor>,
9608 window: &mut Window,
9609 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
9610) {
9611 let editor = editor.clone();
9612 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
9613 let action = action.downcast_ref().unwrap();
9614 if phase == DispatchPhase::Bubble {
9615 editor.update(cx, |editor, cx| {
9616 listener(editor, action, window, cx);
9617 })
9618 }
9619 })
9620}
9621
9622fn compute_auto_height_layout(
9623 editor: &mut Editor,
9624 max_lines: usize,
9625 max_line_number_width: Pixels,
9626 known_dimensions: Size<Option<Pixels>>,
9627 available_width: AvailableSpace,
9628 window: &mut Window,
9629 cx: &mut Context<Editor>,
9630) -> Option<Size<Pixels>> {
9631 let width = known_dimensions.width.or({
9632 if let AvailableSpace::Definite(available_width) = available_width {
9633 Some(available_width)
9634 } else {
9635 None
9636 }
9637 })?;
9638 if let Some(height) = known_dimensions.height {
9639 return Some(size(width, height));
9640 }
9641
9642 let style = editor.style.as_ref().unwrap();
9643 let font_id = window.text_system().resolve_font(&style.text.font());
9644 let font_size = style.text.font_size.to_pixels(window.rem_size());
9645 let line_height = style.text.line_height_in_pixels(window.rem_size());
9646 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
9647
9648 let mut snapshot = editor.snapshot(window, cx);
9649 let gutter_dimensions = snapshot
9650 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
9651 .or_else(|| {
9652 editor
9653 .offset_content
9654 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
9655 })
9656 .unwrap_or_default();
9657
9658 editor.gutter_dimensions = gutter_dimensions;
9659 let text_width = width - gutter_dimensions.width;
9660 let overscroll = size(em_width, px(0.));
9661
9662 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
9663 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
9664 if editor.set_wrap_width(Some(editor_width), cx) {
9665 snapshot = editor.snapshot(window, cx);
9666 }
9667 }
9668
9669 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
9670 let height = scroll_height
9671 .max(line_height)
9672 .min(line_height * max_lines as f32);
9673
9674 Some(size(width, height))
9675}
9676
9677#[cfg(test)]
9678mod tests {
9679 use super::*;
9680 use crate::{
9681 Editor, MultiBuffer,
9682 display_map::{BlockPlacement, BlockProperties},
9683 editor_tests::{init_test, update_test_language_settings},
9684 };
9685 use gpui::{TestAppContext, VisualTestContext};
9686 use language::language_settings;
9687 use log::info;
9688 use std::num::NonZeroU32;
9689 use util::test::sample_text;
9690
9691 #[gpui::test]
9692 fn test_shape_line_numbers(cx: &mut TestAppContext) {
9693 init_test(cx, |_| {});
9694 let window = cx.add_window(|window, cx| {
9695 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
9696 Editor::new(EditorMode::full(), buffer, None, window, cx)
9697 });
9698
9699 let editor = window.root(cx).unwrap();
9700 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
9701 let line_height = window
9702 .update(cx, |_, window, _| {
9703 style.text.line_height_in_pixels(window.rem_size())
9704 })
9705 .unwrap();
9706 let element = EditorElement::new(&editor, style);
9707 let snapshot = window
9708 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
9709 .unwrap();
9710
9711 let layouts = cx
9712 .update_window(*window, |_, window, cx| {
9713 element.layout_line_numbers(
9714 None,
9715 GutterDimensions {
9716 left_padding: Pixels::ZERO,
9717 right_padding: Pixels::ZERO,
9718 width: px(30.0),
9719 margin: Pixels::ZERO,
9720 git_blame_entries_width: None,
9721 },
9722 line_height,
9723 gpui::Point::default(),
9724 DisplayRow(0)..DisplayRow(6),
9725 &(0..6)
9726 .map(|row| RowInfo {
9727 buffer_row: Some(row),
9728 ..Default::default()
9729 })
9730 .collect::<Vec<_>>(),
9731 &BTreeMap::default(),
9732 Some(DisplayPoint::new(DisplayRow(0), 0)),
9733 &snapshot,
9734 window,
9735 cx,
9736 )
9737 })
9738 .unwrap();
9739 assert_eq!(layouts.len(), 6);
9740
9741 let relative_rows = window
9742 .update(cx, |editor, window, cx| {
9743 let snapshot = editor.snapshot(window, cx);
9744 element.calculate_relative_line_numbers(
9745 &snapshot,
9746 &(DisplayRow(0)..DisplayRow(6)),
9747 Some(DisplayRow(3)),
9748 )
9749 })
9750 .unwrap();
9751 assert_eq!(relative_rows[&DisplayRow(0)], 3);
9752 assert_eq!(relative_rows[&DisplayRow(1)], 2);
9753 assert_eq!(relative_rows[&DisplayRow(2)], 1);
9754 // current line has no relative number
9755 assert_eq!(relative_rows[&DisplayRow(4)], 1);
9756 assert_eq!(relative_rows[&DisplayRow(5)], 2);
9757
9758 // works if cursor is before screen
9759 let relative_rows = window
9760 .update(cx, |editor, window, cx| {
9761 let snapshot = editor.snapshot(window, cx);
9762 element.calculate_relative_line_numbers(
9763 &snapshot,
9764 &(DisplayRow(3)..DisplayRow(6)),
9765 Some(DisplayRow(1)),
9766 )
9767 })
9768 .unwrap();
9769 assert_eq!(relative_rows.len(), 3);
9770 assert_eq!(relative_rows[&DisplayRow(3)], 2);
9771 assert_eq!(relative_rows[&DisplayRow(4)], 3);
9772 assert_eq!(relative_rows[&DisplayRow(5)], 4);
9773
9774 // works if cursor is after screen
9775 let relative_rows = window
9776 .update(cx, |editor, window, cx| {
9777 let snapshot = editor.snapshot(window, cx);
9778 element.calculate_relative_line_numbers(
9779 &snapshot,
9780 &(DisplayRow(0)..DisplayRow(3)),
9781 Some(DisplayRow(6)),
9782 )
9783 })
9784 .unwrap();
9785 assert_eq!(relative_rows.len(), 3);
9786 assert_eq!(relative_rows[&DisplayRow(0)], 5);
9787 assert_eq!(relative_rows[&DisplayRow(1)], 4);
9788 assert_eq!(relative_rows[&DisplayRow(2)], 3);
9789 }
9790
9791 #[gpui::test]
9792 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
9793 init_test(cx, |_| {});
9794
9795 let window = cx.add_window(|window, cx| {
9796 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
9797 Editor::new(EditorMode::full(), buffer, None, window, cx)
9798 });
9799 let cx = &mut VisualTestContext::from_window(*window, cx);
9800 let editor = window.root(cx).unwrap();
9801 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9802
9803 window
9804 .update(cx, |editor, window, cx| {
9805 editor.cursor_shape = CursorShape::Block;
9806 editor.change_selections(None, window, cx, |s| {
9807 s.select_ranges([
9808 Point::new(0, 0)..Point::new(1, 0),
9809 Point::new(3, 2)..Point::new(3, 3),
9810 Point::new(5, 6)..Point::new(6, 0),
9811 ]);
9812 });
9813 })
9814 .unwrap();
9815
9816 let (_, state) = cx.draw(
9817 point(px(500.), px(500.)),
9818 size(px(500.), px(500.)),
9819 |_, _| EditorElement::new(&editor, style),
9820 );
9821
9822 assert_eq!(state.selections.len(), 1);
9823 let local_selections = &state.selections[0].1;
9824 assert_eq!(local_selections.len(), 3);
9825 // moves cursor back one line
9826 assert_eq!(
9827 local_selections[0].head,
9828 DisplayPoint::new(DisplayRow(0), 6)
9829 );
9830 assert_eq!(
9831 local_selections[0].range,
9832 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
9833 );
9834
9835 // moves cursor back one column
9836 assert_eq!(
9837 local_selections[1].range,
9838 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
9839 );
9840 assert_eq!(
9841 local_selections[1].head,
9842 DisplayPoint::new(DisplayRow(3), 2)
9843 );
9844
9845 // leaves cursor on the max point
9846 assert_eq!(
9847 local_selections[2].range,
9848 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
9849 );
9850 assert_eq!(
9851 local_selections[2].head,
9852 DisplayPoint::new(DisplayRow(6), 0)
9853 );
9854
9855 // active lines does not include 1 (even though the range of the selection does)
9856 assert_eq!(
9857 state.active_rows.keys().cloned().collect::<Vec<_>>(),
9858 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
9859 );
9860 }
9861
9862 #[gpui::test]
9863 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
9864 init_test(cx, |_| {});
9865
9866 let window = cx.add_window(|window, cx| {
9867 let buffer = MultiBuffer::build_simple("", cx);
9868 Editor::new(EditorMode::full(), buffer, None, window, cx)
9869 });
9870 let cx = &mut VisualTestContext::from_window(*window, cx);
9871 let editor = window.root(cx).unwrap();
9872 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9873 window
9874 .update(cx, |editor, window, cx| {
9875 editor.set_placeholder_text("hello", cx);
9876 editor.insert_blocks(
9877 [BlockProperties {
9878 style: BlockStyle::Fixed,
9879 placement: BlockPlacement::Above(Anchor::min()),
9880 height: Some(3),
9881 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
9882 priority: 0,
9883 render_in_minimap: true,
9884 }],
9885 None,
9886 cx,
9887 );
9888
9889 // Blur the editor so that it displays placeholder text.
9890 window.blur();
9891 })
9892 .unwrap();
9893
9894 let (_, state) = cx.draw(
9895 point(px(500.), px(500.)),
9896 size(px(500.), px(500.)),
9897 |_, _| EditorElement::new(&editor, style),
9898 );
9899 assert_eq!(state.position_map.line_layouts.len(), 4);
9900 assert_eq!(state.line_numbers.len(), 1);
9901 assert_eq!(
9902 state
9903 .line_numbers
9904 .get(&MultiBufferRow(0))
9905 .map(|line_number| line_number.shaped_line.text.as_ref()),
9906 Some("1")
9907 );
9908 }
9909
9910 #[gpui::test]
9911 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
9912 const TAB_SIZE: u32 = 4;
9913
9914 let input_text = "\t \t|\t| a b";
9915 let expected_invisibles = vec![
9916 Invisible::Tab {
9917 line_start_offset: 0,
9918 line_end_offset: TAB_SIZE as usize,
9919 },
9920 Invisible::Whitespace {
9921 line_offset: TAB_SIZE as usize,
9922 },
9923 Invisible::Tab {
9924 line_start_offset: TAB_SIZE as usize + 1,
9925 line_end_offset: TAB_SIZE as usize * 2,
9926 },
9927 Invisible::Tab {
9928 line_start_offset: TAB_SIZE as usize * 2 + 1,
9929 line_end_offset: TAB_SIZE as usize * 3,
9930 },
9931 Invisible::Whitespace {
9932 line_offset: TAB_SIZE as usize * 3 + 1,
9933 },
9934 Invisible::Whitespace {
9935 line_offset: TAB_SIZE as usize * 3 + 3,
9936 },
9937 ];
9938 assert_eq!(
9939 expected_invisibles.len(),
9940 input_text
9941 .chars()
9942 .filter(|initial_char| initial_char.is_whitespace())
9943 .count(),
9944 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9945 );
9946
9947 for show_line_numbers in [true, false] {
9948 init_test(cx, |s| {
9949 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9950 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
9951 });
9952
9953 let actual_invisibles = collect_invisibles_from_new_editor(
9954 cx,
9955 EditorMode::full(),
9956 input_text,
9957 px(500.0),
9958 show_line_numbers,
9959 );
9960
9961 assert_eq!(expected_invisibles, actual_invisibles);
9962 }
9963 }
9964
9965 #[gpui::test]
9966 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
9967 init_test(cx, |s| {
9968 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9969 s.defaults.tab_size = NonZeroU32::new(4);
9970 });
9971
9972 for editor_mode_without_invisibles in [
9973 EditorMode::SingleLine { auto_width: false },
9974 EditorMode::AutoHeight { max_lines: 100 },
9975 ] {
9976 for show_line_numbers in [true, false] {
9977 let invisibles = collect_invisibles_from_new_editor(
9978 cx,
9979 editor_mode_without_invisibles.clone(),
9980 "\t\t\t| | a b",
9981 px(500.0),
9982 show_line_numbers,
9983 );
9984 assert!(
9985 invisibles.is_empty(),
9986 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
9987 );
9988 }
9989 }
9990 }
9991
9992 #[gpui::test]
9993 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
9994 let tab_size = 4;
9995 let input_text = "a\tbcd ".repeat(9);
9996 let repeated_invisibles = [
9997 Invisible::Tab {
9998 line_start_offset: 1,
9999 line_end_offset: tab_size as usize,
10000 },
10001 Invisible::Whitespace {
10002 line_offset: tab_size as usize + 3,
10003 },
10004 Invisible::Whitespace {
10005 line_offset: tab_size as usize + 4,
10006 },
10007 Invisible::Whitespace {
10008 line_offset: tab_size as usize + 5,
10009 },
10010 Invisible::Whitespace {
10011 line_offset: tab_size as usize + 6,
10012 },
10013 Invisible::Whitespace {
10014 line_offset: tab_size as usize + 7,
10015 },
10016 ];
10017 let expected_invisibles = std::iter::once(repeated_invisibles)
10018 .cycle()
10019 .take(9)
10020 .flatten()
10021 .collect::<Vec<_>>();
10022 assert_eq!(
10023 expected_invisibles.len(),
10024 input_text
10025 .chars()
10026 .filter(|initial_char| initial_char.is_whitespace())
10027 .count(),
10028 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10029 );
10030 info!("Expected invisibles: {expected_invisibles:?}");
10031
10032 init_test(cx, |_| {});
10033
10034 // Put the same string with repeating whitespace pattern into editors of various size,
10035 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10036 let resize_step = 10.0;
10037 let mut editor_width = 200.0;
10038 while editor_width <= 1000.0 {
10039 for show_line_numbers in [true, false] {
10040 update_test_language_settings(cx, |s| {
10041 s.defaults.tab_size = NonZeroU32::new(tab_size);
10042 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10043 s.defaults.preferred_line_length = Some(editor_width as u32);
10044 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10045 });
10046
10047 let actual_invisibles = collect_invisibles_from_new_editor(
10048 cx,
10049 EditorMode::full(),
10050 &input_text,
10051 px(editor_width),
10052 show_line_numbers,
10053 );
10054
10055 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10056 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10057 let mut i = 0;
10058 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10059 i = actual_index;
10060 match expected_invisibles.get(i) {
10061 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10062 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10063 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10064 _ => {
10065 panic!(
10066 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10067 )
10068 }
10069 },
10070 None => {
10071 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10072 }
10073 }
10074 }
10075 let missing_expected_invisibles = &expected_invisibles[i + 1..];
10076 assert!(
10077 missing_expected_invisibles.is_empty(),
10078 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10079 );
10080
10081 editor_width += resize_step;
10082 }
10083 }
10084 }
10085
10086 fn collect_invisibles_from_new_editor(
10087 cx: &mut TestAppContext,
10088 editor_mode: EditorMode,
10089 input_text: &str,
10090 editor_width: Pixels,
10091 show_line_numbers: bool,
10092 ) -> Vec<Invisible> {
10093 info!(
10094 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10095 editor_width.0
10096 );
10097 let window = cx.add_window(|window, cx| {
10098 let buffer = MultiBuffer::build_simple(input_text, cx);
10099 Editor::new(editor_mode, buffer, None, window, cx)
10100 });
10101 let cx = &mut VisualTestContext::from_window(*window, cx);
10102 let editor = window.root(cx).unwrap();
10103
10104 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10105 window
10106 .update(cx, |editor, _, cx| {
10107 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10108 editor.set_wrap_width(Some(editor_width), cx);
10109 editor.set_show_line_numbers(show_line_numbers, cx);
10110 })
10111 .unwrap();
10112 let (_, state) = cx.draw(
10113 point(px(500.), px(500.)),
10114 size(px(500.), px(500.)),
10115 |_, _| EditorElement::new(&editor, style),
10116 );
10117 state
10118 .position_map
10119 .line_layouts
10120 .iter()
10121 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10122 .cloned()
10123 .collect()
10124 }
10125}