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