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