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