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