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