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