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