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