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