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