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