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