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