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