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