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