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