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