1use crate::{
2 ActiveDiagnostic, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext, ChunkReplacement,
3 CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker, ConflictsOuter,
4 ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape, CustomBlockId,
5 DisplayDiffHunk, DisplayPoint, DisplayRow, DocumentHighlightRead, DocumentHighlightWrite,
6 EditDisplayMode, EditPrediction, Editor, EditorMode, EditorSettings, EditorSnapshot,
7 EditorStyle, FILE_HEADER_HEIGHT, FocusedBlock, GutterDimensions, HalfPageDown, HalfPageUp,
8 HandleInput, HoveredCursor, InlayHintRefreshReason, JumpData, LineDown, LineHighlight, LineUp,
9 MAX_LINE_LEN, MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts, PageDown,
10 PageUp, PhantomBreakpointIndicator, Point, RowExt, RowRangeExt, SelectPhase,
11 SelectedTextHighlight, Selection, SelectionDragState, SelectionEffects, SizingBehavior,
12 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_line_numbers_enabled = relative.enabled();
3259 let relative_to = relative_line_numbers_enabled.then(|| newest_selection_head.row());
3260
3261 let relative_rows =
3262 self.calculate_relative_line_numbers(snapshot, &rows, relative_to, relative.wrapped());
3263 let mut line_number = String::new();
3264 let segments = buffer_rows.iter().enumerate().flat_map(|(ix, row_info)| {
3265 let display_row = DisplayRow(rows.start.0 + ix as u32);
3266 line_number.clear();
3267 let non_relative_number = if relative.wrapped() {
3268 row_info.buffer_row.or(row_info.wrapped_buffer_row)? + 1
3269 } else {
3270 row_info.buffer_row? + 1
3271 };
3272 let relative_number = relative_rows.get(&display_row);
3273 if !(relative_line_numbers_enabled && relative_number.is_some())
3274 && row_info
3275 .diff_status
3276 .is_some_and(|status| status.is_deleted())
3277 {
3278 return None;
3279 }
3280
3281 let number = relative_number.unwrap_or(&non_relative_number);
3282 write!(&mut line_number, "{number}").unwrap();
3283
3284 let color = active_rows
3285 .get(&display_row)
3286 .map(|spec| {
3287 if spec.breakpoint {
3288 cx.theme().colors().debugger_accent
3289 } else {
3290 cx.theme().colors().editor_active_line_number
3291 }
3292 })
3293 .unwrap_or_else(|| cx.theme().colors().editor_line_number);
3294 let shaped_line =
3295 self.shape_line_number(SharedString::from(&line_number), color, window);
3296 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
3297 let line_origin = gutter_hitbox.map(|hitbox| {
3298 hitbox.origin
3299 + point(
3300 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
3301 ix as f32 * line_height
3302 - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height)),
3303 )
3304 });
3305
3306 #[cfg(not(test))]
3307 let hitbox = line_origin.map(|line_origin| {
3308 window.insert_hitbox(
3309 Bounds::new(line_origin, size(shaped_line.width, line_height)),
3310 HitboxBehavior::Normal,
3311 )
3312 });
3313 #[cfg(test)]
3314 let hitbox = {
3315 let _ = line_origin;
3316 None
3317 };
3318
3319 let segment = LineNumberSegment {
3320 shaped_line,
3321 hitbox,
3322 };
3323
3324 let buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
3325 let multi_buffer_row = MultiBufferRow(buffer_row);
3326
3327 Some((multi_buffer_row, segment))
3328 });
3329
3330 let mut line_numbers: HashMap<MultiBufferRow, LineNumberLayout> = HashMap::default();
3331 for (buffer_row, segment) in segments {
3332 line_numbers
3333 .entry(buffer_row)
3334 .or_insert_with(|| LineNumberLayout {
3335 segments: Default::default(),
3336 })
3337 .segments
3338 .push(segment);
3339 }
3340 Arc::new(line_numbers)
3341 }
3342
3343 fn layout_crease_toggles(
3344 &self,
3345 rows: Range<DisplayRow>,
3346 row_infos: &[RowInfo],
3347 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3348 snapshot: &EditorSnapshot,
3349 window: &mut Window,
3350 cx: &mut App,
3351 ) -> Vec<Option<AnyElement>> {
3352 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
3353 && snapshot.mode.is_full()
3354 && self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
3355 if include_fold_statuses {
3356 row_infos
3357 .iter()
3358 .enumerate()
3359 .map(|(ix, info)| {
3360 if info.expand_info.is_some() {
3361 return None;
3362 }
3363 let row = info.multibuffer_row?;
3364 let display_row = DisplayRow(rows.start.0 + ix as u32);
3365 let active = active_rows.contains_key(&display_row);
3366
3367 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
3368 })
3369 .collect()
3370 } else {
3371 Vec::new()
3372 }
3373 }
3374
3375 fn layout_crease_trailers(
3376 &self,
3377 buffer_rows: impl IntoIterator<Item = RowInfo>,
3378 snapshot: &EditorSnapshot,
3379 window: &mut Window,
3380 cx: &mut App,
3381 ) -> Vec<Option<AnyElement>> {
3382 buffer_rows
3383 .into_iter()
3384 .map(|row_info| {
3385 if row_info.expand_info.is_some() {
3386 return None;
3387 }
3388 if let Some(row) = row_info.multibuffer_row {
3389 snapshot.render_crease_trailer(row, window, cx)
3390 } else {
3391 None
3392 }
3393 })
3394 .collect()
3395 }
3396
3397 fn bg_segments_per_row(
3398 rows: Range<DisplayRow>,
3399 selections: &[(PlayerColor, Vec<SelectionLayout>)],
3400 highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
3401 base_background: Hsla,
3402 ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
3403 if rows.start >= rows.end {
3404 return Vec::new();
3405 }
3406 if !base_background.is_opaque() {
3407 // We don't actually know what color is behind this editor.
3408 return Vec::new();
3409 }
3410 let highlight_iter = highlight_ranges.iter().cloned();
3411 let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
3412 let color = player_color.selection;
3413 layouts.iter().filter_map(move |selection_layout| {
3414 if selection_layout.range.start != selection_layout.range.end {
3415 Some((selection_layout.range.clone(), color))
3416 } else {
3417 None
3418 }
3419 })
3420 });
3421 let mut per_row_map = vec![Vec::new(); rows.len()];
3422 for (range, color) in highlight_iter.chain(selection_iter) {
3423 let covered_rows = if range.end.column() == 0 {
3424 cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
3425 } else {
3426 cmp::max(range.start.row(), rows.start)
3427 ..cmp::min(range.end.row().next_row(), rows.end)
3428 };
3429 for row in covered_rows.iter_rows() {
3430 let seg_start = if row == range.start.row() {
3431 range.start
3432 } else {
3433 DisplayPoint::new(row, 0)
3434 };
3435 let seg_end = if row == range.end.row() && range.end.column() != 0 {
3436 range.end
3437 } else {
3438 DisplayPoint::new(row, u32::MAX)
3439 };
3440 let ix = row.minus(rows.start) as usize;
3441 debug_assert!(row >= rows.start && row < rows.end);
3442 debug_assert!(ix < per_row_map.len());
3443 per_row_map[ix].push((seg_start..seg_end, color));
3444 }
3445 }
3446 for row_segments in per_row_map.iter_mut() {
3447 if row_segments.is_empty() {
3448 continue;
3449 }
3450 let segments = mem::take(row_segments);
3451 let merged = Self::merge_overlapping_ranges(segments, base_background);
3452 *row_segments = merged;
3453 }
3454 per_row_map
3455 }
3456
3457 /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
3458 /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
3459 ///
3460 /// Expects `start.row() == end.row()` for each range.
3461 fn merge_overlapping_ranges(
3462 ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3463 base_background: Hsla,
3464 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
3465 struct Boundary {
3466 pos: DisplayPoint,
3467 is_start: bool,
3468 index: usize,
3469 color: Hsla,
3470 }
3471
3472 let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
3473 for (index, (range, color)) in ranges.iter().enumerate() {
3474 debug_assert!(
3475 range.start.row() == range.end.row(),
3476 "expects single-row ranges"
3477 );
3478 if range.start < range.end {
3479 boundaries.push(Boundary {
3480 pos: range.start,
3481 is_start: true,
3482 index,
3483 color: *color,
3484 });
3485 boundaries.push(Boundary {
3486 pos: range.end,
3487 is_start: false,
3488 index,
3489 color: *color,
3490 });
3491 }
3492 }
3493
3494 if boundaries.is_empty() {
3495 return Vec::new();
3496 }
3497
3498 boundaries
3499 .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
3500
3501 let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
3502 let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
3503
3504 let mut i = 0;
3505 let mut start_pos = boundaries[0].pos;
3506
3507 let boundaries_len = boundaries.len();
3508 while i < boundaries_len {
3509 let current_boundary_pos = boundaries[i].pos;
3510 if start_pos < current_boundary_pos {
3511 if !active_ranges.is_empty() {
3512 let mut color = base_background;
3513 for &(_, c) in &active_ranges {
3514 color = Hsla::blend(color, c);
3515 }
3516 if let Some((last_range, last_color)) = processed_ranges.last_mut() {
3517 if *last_color == color && last_range.end == start_pos {
3518 last_range.end = current_boundary_pos;
3519 } else {
3520 processed_ranges.push((start_pos..current_boundary_pos, color));
3521 }
3522 } else {
3523 processed_ranges.push((start_pos..current_boundary_pos, color));
3524 }
3525 }
3526 }
3527 while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
3528 let active_range = &boundaries[i];
3529 if active_range.is_start {
3530 let idx = active_range.index;
3531 let pos = active_ranges
3532 .binary_search_by_key(&idx, |(i, _)| *i)
3533 .unwrap_or_else(|p| p);
3534 active_ranges.insert(pos, (idx, active_range.color));
3535 } else {
3536 let idx = active_range.index;
3537 if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
3538 active_ranges.remove(pos);
3539 }
3540 }
3541 i += 1;
3542 }
3543 start_pos = current_boundary_pos;
3544 }
3545
3546 processed_ranges
3547 }
3548
3549 fn layout_lines(
3550 rows: Range<DisplayRow>,
3551 snapshot: &EditorSnapshot,
3552 style: &EditorStyle,
3553 editor_width: Pixels,
3554 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3555 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
3556 window: &mut Window,
3557 cx: &mut App,
3558 ) -> Vec<LineWithInvisibles> {
3559 if rows.start >= rows.end {
3560 return Vec::new();
3561 }
3562
3563 // Show the placeholder when the editor is empty
3564 if snapshot.is_empty() {
3565 let font_size = style.text.font_size.to_pixels(window.rem_size());
3566 let placeholder_color = cx.theme().colors().text_placeholder;
3567 let placeholder_text = snapshot.placeholder_text();
3568
3569 let placeholder_lines = placeholder_text
3570 .as_ref()
3571 .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
3572
3573 let placeholder_line_count = placeholder_lines.len();
3574
3575 placeholder_lines
3576 .into_iter()
3577 .skip(rows.start.0 as usize)
3578 .chain(iter::repeat(""))
3579 .take(cmp::max(rows.len(), placeholder_line_count))
3580 .map(move |line| {
3581 let run = TextRun {
3582 len: line.len(),
3583 font: style.text.font(),
3584 color: placeholder_color,
3585 ..Default::default()
3586 };
3587 let line = window.text_system().shape_line(
3588 line.to_string().into(),
3589 font_size,
3590 &[run],
3591 None,
3592 );
3593 LineWithInvisibles {
3594 width: line.width,
3595 len: line.len,
3596 fragments: smallvec![LineFragment::Text(line)],
3597 invisibles: Vec::new(),
3598 font_size,
3599 }
3600 })
3601 .collect()
3602 } else {
3603 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
3604 LineWithInvisibles::from_chunks(
3605 chunks,
3606 style,
3607 MAX_LINE_LEN,
3608 rows.len(),
3609 &snapshot.mode,
3610 editor_width,
3611 is_row_soft_wrapped,
3612 bg_segments_per_row,
3613 window,
3614 cx,
3615 )
3616 }
3617 }
3618
3619 fn prepaint_lines(
3620 &self,
3621 start_row: DisplayRow,
3622 line_layouts: &mut [LineWithInvisibles],
3623 line_height: Pixels,
3624 scroll_position: gpui::Point<ScrollOffset>,
3625 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
3626 content_origin: gpui::Point<Pixels>,
3627 window: &mut Window,
3628 cx: &mut App,
3629 ) -> SmallVec<[AnyElement; 1]> {
3630 let mut line_elements = SmallVec::new();
3631 for (ix, line) in line_layouts.iter_mut().enumerate() {
3632 let row = start_row + DisplayRow(ix as u32);
3633 line.prepaint(
3634 line_height,
3635 scroll_position,
3636 scroll_pixel_position,
3637 row,
3638 content_origin,
3639 &mut line_elements,
3640 window,
3641 cx,
3642 );
3643 }
3644 line_elements
3645 }
3646
3647 fn render_block(
3648 &self,
3649 block: &Block,
3650 available_width: AvailableSpace,
3651 block_id: BlockId,
3652 block_row_start: DisplayRow,
3653 snapshot: &EditorSnapshot,
3654 text_x: Pixels,
3655 rows: &Range<DisplayRow>,
3656 line_layouts: &[LineWithInvisibles],
3657 editor_margins: &EditorMargins,
3658 line_height: Pixels,
3659 em_width: Pixels,
3660 text_hitbox: &Hitbox,
3661 editor_width: Pixels,
3662 scroll_width: &mut Pixels,
3663 resized_blocks: &mut HashMap<CustomBlockId, u32>,
3664 row_block_types: &mut HashMap<DisplayRow, bool>,
3665 selections: &[Selection<Point>],
3666 selected_buffer_ids: &Vec<BufferId>,
3667 selection_anchors: &[Selection<Anchor>],
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(
3744 snapshot,
3745 block_row_start,
3746 *height,
3747 first_excerpt,
3748 selection_anchors,
3749 );
3750 result
3751 .child(self.render_buffer_header(
3752 first_excerpt,
3753 true,
3754 selected,
3755 false,
3756 jump_data,
3757 window,
3758 cx,
3759 ))
3760 .into_any_element()
3761 }
3762
3763 Block::ExcerptBoundary { .. } => {
3764 let color = cx.theme().colors().clone();
3765 let mut result = v_flex().id(block_id).w_full();
3766
3767 result = result.child(
3768 h_flex().relative().child(
3769 div()
3770 .top(line_height / 2.)
3771 .absolute()
3772 .w_full()
3773 .h_px()
3774 .bg(color.border_variant),
3775 ),
3776 );
3777
3778 result.into_any()
3779 }
3780
3781 Block::BufferHeader { excerpt, height } => {
3782 let mut result = v_flex().id(block_id).w_full();
3783
3784 let jump_data = header_jump_data(
3785 snapshot,
3786 block_row_start,
3787 *height,
3788 excerpt,
3789 selection_anchors,
3790 );
3791
3792 if sticky_header_excerpt_id != Some(excerpt.id) {
3793 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3794
3795 result = result.child(div().pr(editor_margins.right).child(
3796 self.render_buffer_header(
3797 excerpt, false, selected, false, jump_data, window, cx,
3798 ),
3799 ));
3800 } else {
3801 result =
3802 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3803 }
3804
3805 result.into_any()
3806 }
3807 };
3808
3809 // Discover the element's content height, then round up to the nearest multiple of line height.
3810 let preliminary_size = element.layout_as_root(
3811 size(available_width, AvailableSpace::MinContent),
3812 window,
3813 cx,
3814 );
3815 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
3816 let final_size = if preliminary_size.height == quantized_height {
3817 preliminary_size
3818 } else {
3819 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
3820 };
3821 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
3822
3823 let mut row = block_row_start;
3824 let mut x_offset = px(0.);
3825 let mut is_block = true;
3826
3827 if let BlockId::Custom(custom_block_id) = block_id
3828 && block.has_height()
3829 {
3830 if block.place_near()
3831 && let Some((x_target, line_width)) = x_position
3832 {
3833 let margin = em_width * 2;
3834 if line_width + final_size.width + margin
3835 < editor_width + editor_margins.gutter.full_width()
3836 && !row_block_types.contains_key(&(row - 1))
3837 && element_height_in_lines == 1
3838 {
3839 x_offset = line_width + margin;
3840 row = row - 1;
3841 is_block = false;
3842 element_height_in_lines = 0;
3843 row_block_types.insert(row, is_block);
3844 } else {
3845 let max_offset =
3846 editor_width + editor_margins.gutter.full_width() - final_size.width;
3847 let min_offset = (x_target + em_width - final_size.width)
3848 .max(editor_margins.gutter.full_width());
3849 x_offset = x_target.min(max_offset).max(min_offset);
3850 }
3851 };
3852 if element_height_in_lines != block.height() {
3853 resized_blocks.insert(custom_block_id, element_height_in_lines);
3854 }
3855 }
3856 for i in 0..element_height_in_lines {
3857 row_block_types.insert(row + i, is_block);
3858 }
3859
3860 Some((element, final_size, row, x_offset))
3861 }
3862
3863 fn render_buffer_header(
3864 &self,
3865 for_excerpt: &ExcerptInfo,
3866 is_folded: bool,
3867 is_selected: bool,
3868 is_sticky: bool,
3869 jump_data: JumpData,
3870 window: &mut Window,
3871 cx: &mut App,
3872 ) -> impl IntoElement {
3873 let editor = self.editor.read(cx);
3874 let multi_buffer = editor.buffer.read(cx);
3875 let file_status = multi_buffer
3876 .all_diff_hunks_expanded()
3877 .then(|| editor.status_for_buffer_id(for_excerpt.buffer_id, cx))
3878 .flatten();
3879 let indicator = multi_buffer
3880 .buffer(for_excerpt.buffer_id)
3881 .and_then(|buffer| {
3882 let buffer = buffer.read(cx);
3883 let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
3884 (true, _) => Some(Color::Warning),
3885 (_, true) => Some(Color::Accent),
3886 (false, false) => None,
3887 };
3888 indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
3889 });
3890
3891 let include_root = editor
3892 .project
3893 .as_ref()
3894 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
3895 .unwrap_or_default();
3896 let file = for_excerpt.buffer.file();
3897 let can_open_excerpts = Editor::can_open_excerpts_in_file(file);
3898 let path_style = file.map(|file| file.path_style(cx));
3899 let relative_path = for_excerpt.buffer.resolve_file_path(include_root, cx);
3900 let (parent_path, filename) = if let Some(path) = &relative_path {
3901 if let Some(path_style) = path_style {
3902 let (dir, file_name) = path_style.split(path);
3903 (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
3904 } else {
3905 (None, Some(path.clone()))
3906 }
3907 } else {
3908 (None, None)
3909 };
3910 let focus_handle = editor.focus_handle(cx);
3911 let colors = cx.theme().colors();
3912
3913 let header = div()
3914 .p_1()
3915 .w_full()
3916 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3917 .child(
3918 h_flex()
3919 .size_full()
3920 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3921 .pl_1()
3922 .pr_2()
3923 .rounded_sm()
3924 .gap_1p5()
3925 .when(is_sticky, |el| el.shadow_md())
3926 .border_1()
3927 .map(|div| {
3928 let border_color = if is_selected
3929 && is_folded
3930 && focus_handle.contains_focused(window, cx)
3931 {
3932 colors.border_focused
3933 } else {
3934 colors.border
3935 };
3936 div.border_color(border_color)
3937 })
3938 .bg(colors.editor_subheader_background)
3939 .hover(|style| style.bg(colors.element_hover))
3940 .map(|header| {
3941 let editor = self.editor.clone();
3942 let buffer_id = for_excerpt.buffer_id;
3943 let toggle_chevron_icon =
3944 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3945 let button_size = rems_from_px(28.);
3946
3947 header.child(
3948 div()
3949 .hover(|style| style.bg(colors.element_selected))
3950 .rounded_xs()
3951 .child(
3952 ButtonLike::new("toggle-buffer-fold")
3953 .style(ButtonStyle::Transparent)
3954 .height(button_size.into())
3955 .width(button_size)
3956 .children(toggle_chevron_icon)
3957 .tooltip({
3958 let focus_handle = focus_handle.clone();
3959 move |_window, cx| {
3960 Tooltip::with_meta_in(
3961 "Toggle Excerpt Fold",
3962 Some(&ToggleFold),
3963 format!(
3964 "{} to toggle all",
3965 text_for_keystroke(
3966 &Modifiers::alt(),
3967 "click",
3968 cx
3969 )
3970 ),
3971 &focus_handle,
3972 cx,
3973 )
3974 }
3975 })
3976 .on_click(move |event, window, cx| {
3977 if event.modifiers().alt {
3978 // Alt+click toggles all buffers
3979 editor.update(cx, |editor, cx| {
3980 editor.toggle_fold_all(
3981 &ToggleFoldAll,
3982 window,
3983 cx,
3984 );
3985 });
3986 } else {
3987 // Regular click toggles single buffer
3988 if is_folded {
3989 editor.update(cx, |editor, cx| {
3990 editor.unfold_buffer(buffer_id, cx);
3991 });
3992 } else {
3993 editor.update(cx, |editor, cx| {
3994 editor.fold_buffer(buffer_id, cx);
3995 });
3996 }
3997 }
3998 }),
3999 ),
4000 )
4001 })
4002 .children(
4003 editor
4004 .addons
4005 .values()
4006 .filter_map(|addon| {
4007 addon.render_buffer_header_controls(for_excerpt, window, cx)
4008 })
4009 .take(1),
4010 )
4011 .child(
4012 h_flex()
4013 .size(rems_from_px(12.0))
4014 .justify_center()
4015 .flex_shrink_0()
4016 .children(indicator),
4017 )
4018 .child(
4019 h_flex()
4020 .cursor_pointer()
4021 .id("path header block")
4022 .size_full()
4023 .justify_between()
4024 .overflow_hidden()
4025 .child(h_flex().gap_0p5().map(|path_header| {
4026 let filename = filename
4027 .map(SharedString::from)
4028 .unwrap_or_else(|| "untitled".into());
4029
4030 path_header
4031 .when(ItemSettings::get_global(cx).file_icons, |el| {
4032 let path = path::Path::new(filename.as_str());
4033 let icon =
4034 FileIcons::get_icon(path, cx).unwrap_or_default();
4035 let icon = Icon::from_path(icon).color(Color::Muted);
4036 el.child(icon)
4037 })
4038 .child(
4039 ButtonLike::new("filename-button")
4040 .style(ButtonStyle::Subtle)
4041 .child(
4042 div()
4043 .child(
4044 Label::new(filename)
4045 .single_line()
4046 .color(file_status_label_color(
4047 file_status,
4048 ))
4049 .when(
4050 file_status.is_some_and(|s| {
4051 s.is_deleted()
4052 }),
4053 |label| label.strikethrough(),
4054 ),
4055 )
4056 .group_hover("", |div| div.underline()),
4057 )
4058 .on_click(window.listener_for(&self.editor, {
4059 let jump_data = jump_data.clone();
4060
4061 move |editor, e: &ClickEvent, window, cx| {
4062 editor.open_excerpts_common(
4063 Some(jump_data.clone()),
4064 e.modifiers().secondary(),
4065 window,
4066 cx,
4067 );
4068 }
4069 })),
4070 )
4071 .when_some(parent_path, |then, path| {
4072 then.child(div().child(path).text_color(
4073 if file_status.is_some_and(FileStatus::is_deleted) {
4074 colors.text_disabled
4075 } else {
4076 colors.text_muted
4077 },
4078 ))
4079 })
4080 }))
4081 .when(
4082 can_open_excerpts && is_selected && relative_path.is_some(),
4083 |el| {
4084 el.child(
4085 ButtonLike::new("open-file-button")
4086 .style(ButtonStyle::OutlinedGhost)
4087 .child(
4088 h_flex()
4089 .gap_2p5()
4090 .child(Label::new("Open file"))
4091 .child(KeyBinding::for_action_in(
4092 &OpenExcerpts,
4093 &focus_handle,
4094 cx,
4095 )),
4096 )
4097 .on_click(window.listener_for(&self.editor, {
4098 let jump_data = jump_data.clone();
4099
4100 move |editor, e: &ClickEvent, window, cx| {
4101 editor.open_excerpts_common(
4102 Some(jump_data.clone()),
4103 e.modifiers().secondary(),
4104 window,
4105 cx,
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 selection_anchors: &[Selection<Anchor>],
4255 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4256 sticky_header_excerpt_id: Option<ExcerptId>,
4257 window: &mut Window,
4258 cx: &mut App,
4259 ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
4260 let (fixed_blocks, non_fixed_blocks) = snapshot
4261 .blocks_in_range(rows.clone())
4262 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
4263
4264 let mut focused_block = self
4265 .editor
4266 .update(cx, |editor, _| editor.take_focused_block());
4267 let mut fixed_block_max_width = Pixels::ZERO;
4268 let mut blocks = Vec::new();
4269 let mut resized_blocks = HashMap::default();
4270 let mut row_block_types = HashMap::default();
4271
4272 for (row, block) in fixed_blocks {
4273 let block_id = block.id();
4274
4275 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4276 focused_block = None;
4277 }
4278
4279 if let Some((element, element_size, row, x_offset)) = self.render_block(
4280 block,
4281 AvailableSpace::MinContent,
4282 block_id,
4283 row,
4284 snapshot,
4285 text_x,
4286 &rows,
4287 line_layouts,
4288 editor_margins,
4289 line_height,
4290 em_width,
4291 text_hitbox,
4292 editor_width,
4293 scroll_width,
4294 &mut resized_blocks,
4295 &mut row_block_types,
4296 selections,
4297 selected_buffer_ids,
4298 selection_anchors,
4299 is_row_soft_wrapped,
4300 sticky_header_excerpt_id,
4301 window,
4302 cx,
4303 ) {
4304 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
4305 blocks.push(BlockLayout {
4306 id: block_id,
4307 x_offset,
4308 row: Some(row),
4309 element,
4310 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
4311 style: BlockStyle::Fixed,
4312 overlaps_gutter: true,
4313 is_buffer_header: block.is_buffer_header(),
4314 });
4315 }
4316 }
4317
4318 for (row, block) in non_fixed_blocks {
4319 let style = block.style();
4320 let width = match (style, block.place_near()) {
4321 (_, true) => AvailableSpace::MinContent,
4322 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
4323 (BlockStyle::Flex, _) => hitbox
4324 .size
4325 .width
4326 .max(fixed_block_max_width)
4327 .max(editor_margins.gutter.width + *scroll_width)
4328 .into(),
4329 (BlockStyle::Fixed, _) => unreachable!(),
4330 };
4331 let block_id = block.id();
4332
4333 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4334 focused_block = None;
4335 }
4336
4337 if let Some((element, element_size, row, x_offset)) = self.render_block(
4338 block,
4339 width,
4340 block_id,
4341 row,
4342 snapshot,
4343 text_x,
4344 &rows,
4345 line_layouts,
4346 editor_margins,
4347 line_height,
4348 em_width,
4349 text_hitbox,
4350 editor_width,
4351 scroll_width,
4352 &mut resized_blocks,
4353 &mut row_block_types,
4354 selections,
4355 selected_buffer_ids,
4356 selection_anchors,
4357 is_row_soft_wrapped,
4358 sticky_header_excerpt_id,
4359 window,
4360 cx,
4361 ) {
4362 blocks.push(BlockLayout {
4363 id: block_id,
4364 x_offset,
4365 row: Some(row),
4366 element,
4367 available_space: size(width, element_size.height.into()),
4368 style,
4369 overlaps_gutter: !block.place_near(),
4370 is_buffer_header: block.is_buffer_header(),
4371 });
4372 }
4373 }
4374
4375 if let Some(focused_block) = focused_block
4376 && let Some(focus_handle) = focused_block.focus_handle.upgrade()
4377 && focus_handle.is_focused(window)
4378 && let Some(block) = snapshot.block_for_id(focused_block.id)
4379 {
4380 let style = block.style();
4381 let width = match style {
4382 BlockStyle::Fixed => AvailableSpace::MinContent,
4383 BlockStyle::Flex => AvailableSpace::Definite(
4384 hitbox
4385 .size
4386 .width
4387 .max(fixed_block_max_width)
4388 .max(editor_margins.gutter.width + *scroll_width),
4389 ),
4390 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
4391 };
4392
4393 if let Some((element, element_size, _, x_offset)) = self.render_block(
4394 &block,
4395 width,
4396 focused_block.id,
4397 rows.end,
4398 snapshot,
4399 text_x,
4400 &rows,
4401 line_layouts,
4402 editor_margins,
4403 line_height,
4404 em_width,
4405 text_hitbox,
4406 editor_width,
4407 scroll_width,
4408 &mut resized_blocks,
4409 &mut row_block_types,
4410 selections,
4411 selected_buffer_ids,
4412 selection_anchors,
4413 is_row_soft_wrapped,
4414 sticky_header_excerpt_id,
4415 window,
4416 cx,
4417 ) {
4418 blocks.push(BlockLayout {
4419 id: block.id(),
4420 x_offset,
4421 row: None,
4422 element,
4423 available_space: size(width, element_size.height.into()),
4424 style,
4425 overlaps_gutter: true,
4426 is_buffer_header: block.is_buffer_header(),
4427 });
4428 }
4429 }
4430
4431 if resized_blocks.is_empty() {
4432 *scroll_width =
4433 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
4434 Ok((blocks, row_block_types))
4435 } else {
4436 Err(resized_blocks)
4437 }
4438 }
4439
4440 fn layout_blocks(
4441 &self,
4442 blocks: &mut Vec<BlockLayout>,
4443 hitbox: &Hitbox,
4444 line_height: Pixels,
4445 scroll_position: gpui::Point<ScrollOffset>,
4446 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4447 window: &mut Window,
4448 cx: &mut App,
4449 ) {
4450 for block in blocks {
4451 let mut origin = if let Some(row) = block.row {
4452 hitbox.origin
4453 + point(
4454 block.x_offset,
4455 Pixels::from(
4456 (row.as_f64() - scroll_position.y)
4457 * ScrollPixelOffset::from(line_height),
4458 ),
4459 )
4460 } else {
4461 // Position the block outside the visible area
4462 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
4463 };
4464
4465 if !matches!(block.style, BlockStyle::Sticky) {
4466 origin += point(Pixels::from(-scroll_pixel_position.x), Pixels::ZERO);
4467 }
4468
4469 let focus_handle =
4470 block
4471 .element
4472 .prepaint_as_root(origin, block.available_space, window, cx);
4473
4474 if let Some(focus_handle) = focus_handle {
4475 self.editor.update(cx, |editor, _cx| {
4476 editor.set_focused_block(FocusedBlock {
4477 id: block.id,
4478 focus_handle: focus_handle.downgrade(),
4479 });
4480 });
4481 }
4482 }
4483 }
4484
4485 fn layout_sticky_buffer_header(
4486 &self,
4487 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
4488 scroll_position: gpui::Point<ScrollOffset>,
4489 line_height: Pixels,
4490 right_margin: Pixels,
4491 snapshot: &EditorSnapshot,
4492 hitbox: &Hitbox,
4493 selected_buffer_ids: &Vec<BufferId>,
4494 blocks: &[BlockLayout],
4495 selection_anchors: &[Selection<Anchor>],
4496 window: &mut Window,
4497 cx: &mut App,
4498 ) -> AnyElement {
4499 let jump_data = header_jump_data(
4500 snapshot,
4501 DisplayRow(scroll_position.y as u32),
4502 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4503 excerpt,
4504 selection_anchors,
4505 );
4506
4507 let editor_bg_color = cx.theme().colors().editor_background;
4508
4509 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4510
4511 let available_width = hitbox.bounds.size.width - right_margin;
4512
4513 let mut header = v_flex()
4514 .w_full()
4515 .relative()
4516 .child(
4517 div()
4518 .w(available_width)
4519 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4520 .bg(linear_gradient(
4521 0.,
4522 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4523 linear_color_stop(editor_bg_color, 0.6),
4524 ))
4525 .absolute()
4526 .top_0(),
4527 )
4528 .child(
4529 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4530 .into_any_element(),
4531 )
4532 .into_any_element();
4533
4534 let mut origin = hitbox.origin;
4535 // Move floating header up to avoid colliding with the next buffer header.
4536 for block in blocks.iter() {
4537 if !block.is_buffer_header {
4538 continue;
4539 }
4540
4541 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position.y as u32) else {
4542 continue;
4543 };
4544
4545 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4546 let offset = scroll_position.y - max_row as f64;
4547
4548 if offset > 0.0 {
4549 origin.y -= Pixels::from(offset * ScrollPixelOffset::from(line_height));
4550 }
4551 break;
4552 }
4553
4554 let size = size(
4555 AvailableSpace::Definite(available_width),
4556 AvailableSpace::MinContent,
4557 );
4558
4559 header.prepaint_as_root(origin, size, window, cx);
4560
4561 header
4562 }
4563
4564 fn layout_sticky_headers(
4565 &self,
4566 snapshot: &EditorSnapshot,
4567 editor_width: Pixels,
4568 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4569 line_height: Pixels,
4570 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4571 content_origin: gpui::Point<Pixels>,
4572 gutter_dimensions: &GutterDimensions,
4573 gutter_hitbox: &Hitbox,
4574 text_hitbox: &Hitbox,
4575 window: &mut Window,
4576 cx: &mut App,
4577 ) -> Option<StickyHeaders> {
4578 let show_line_numbers = snapshot
4579 .show_line_numbers
4580 .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
4581
4582 let rows = Self::sticky_headers(self.editor.read(cx), snapshot, cx);
4583
4584 let mut lines = Vec::<StickyHeaderLine>::new();
4585
4586 for StickyHeader {
4587 item,
4588 sticky_row,
4589 start_point,
4590 offset,
4591 } in rows.into_iter().rev()
4592 {
4593 let line = layout_line(
4594 sticky_row,
4595 snapshot,
4596 &self.style,
4597 editor_width,
4598 is_row_soft_wrapped,
4599 window,
4600 cx,
4601 );
4602
4603 let line_number = show_line_numbers.then(|| {
4604 let number = (start_point.row + 1).to_string();
4605 let color = cx.theme().colors().editor_line_number;
4606 self.shape_line_number(SharedString::from(number), color, window)
4607 });
4608
4609 lines.push(StickyHeaderLine::new(
4610 sticky_row,
4611 line_height * offset as f32,
4612 line,
4613 line_number,
4614 item.range.start,
4615 line_height,
4616 scroll_pixel_position,
4617 content_origin,
4618 gutter_hitbox,
4619 text_hitbox,
4620 window,
4621 cx,
4622 ));
4623 }
4624
4625 lines.reverse();
4626 if lines.is_empty() {
4627 return None;
4628 }
4629
4630 Some(StickyHeaders {
4631 lines,
4632 gutter_background: cx.theme().colors().editor_gutter_background,
4633 content_background: self.style.background,
4634 gutter_right_padding: gutter_dimensions.right_padding,
4635 })
4636 }
4637
4638 pub(crate) fn sticky_headers(
4639 editor: &Editor,
4640 snapshot: &EditorSnapshot,
4641 cx: &App,
4642 ) -> Vec<StickyHeader> {
4643 let scroll_top = snapshot.scroll_position().y;
4644
4645 let mut end_rows = Vec::<DisplayRow>::new();
4646 let mut rows = Vec::<StickyHeader>::new();
4647
4648 let items = editor.sticky_headers(cx).unwrap_or_default();
4649
4650 for item in items {
4651 let start_point = item.range.start.to_point(snapshot.buffer_snapshot());
4652 let end_point = item.range.end.to_point(snapshot.buffer_snapshot());
4653
4654 let sticky_row = snapshot
4655 .display_snapshot
4656 .point_to_display_point(start_point, Bias::Left)
4657 .row();
4658 let end_row = snapshot
4659 .display_snapshot
4660 .point_to_display_point(end_point, Bias::Left)
4661 .row();
4662 let max_sticky_row = end_row.previous_row();
4663 if max_sticky_row <= sticky_row {
4664 continue;
4665 }
4666
4667 while end_rows
4668 .last()
4669 .is_some_and(|&last_end| last_end < sticky_row)
4670 {
4671 end_rows.pop();
4672 }
4673 let depth = end_rows.len();
4674 let adjusted_scroll_top = scroll_top + depth as f64;
4675
4676 if sticky_row.as_f64() >= adjusted_scroll_top || end_row.as_f64() <= adjusted_scroll_top
4677 {
4678 continue;
4679 }
4680
4681 let max_scroll_offset = max_sticky_row.as_f64() - scroll_top;
4682 let offset = (depth as f64).min(max_scroll_offset);
4683
4684 end_rows.push(end_row);
4685 rows.push(StickyHeader {
4686 item,
4687 sticky_row,
4688 start_point,
4689 offset,
4690 });
4691 }
4692
4693 rows
4694 }
4695
4696 fn layout_cursor_popovers(
4697 &self,
4698 line_height: Pixels,
4699 text_hitbox: &Hitbox,
4700 content_origin: gpui::Point<Pixels>,
4701 right_margin: Pixels,
4702 start_row: DisplayRow,
4703 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4704 line_layouts: &[LineWithInvisibles],
4705 cursor: DisplayPoint,
4706 cursor_point: Point,
4707 style: &EditorStyle,
4708 window: &mut Window,
4709 cx: &mut App,
4710 ) -> Option<ContextMenuLayout> {
4711 let mut min_menu_height = Pixels::ZERO;
4712 let mut max_menu_height = Pixels::ZERO;
4713 let mut height_above_menu = Pixels::ZERO;
4714 let height_below_menu = Pixels::ZERO;
4715 let mut edit_prediction_popover_visible = false;
4716 let mut context_menu_visible = false;
4717 let context_menu_placement;
4718
4719 {
4720 let editor = self.editor.read(cx);
4721 if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
4722 {
4723 height_above_menu +=
4724 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4725 edit_prediction_popover_visible = true;
4726 }
4727
4728 if editor.context_menu_visible()
4729 && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
4730 {
4731 let (min_height_in_lines, max_height_in_lines) = editor
4732 .context_menu_options
4733 .as_ref()
4734 .map_or((3, 12), |options| {
4735 (options.min_entries_visible, options.max_entries_visible)
4736 });
4737
4738 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4739 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4740 context_menu_visible = true;
4741 }
4742 context_menu_placement = editor
4743 .context_menu_options
4744 .as_ref()
4745 .and_then(|options| options.placement.clone());
4746 }
4747
4748 let visible = edit_prediction_popover_visible || context_menu_visible;
4749 if !visible {
4750 return None;
4751 }
4752
4753 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4754 let target_position = content_origin
4755 + gpui::Point {
4756 x: cmp::max(
4757 px(0.),
4758 Pixels::from(
4759 ScrollPixelOffset::from(
4760 cursor_row_layout.x_for_index(cursor.column() as usize),
4761 ) - scroll_pixel_position.x,
4762 ),
4763 ),
4764 y: cmp::max(
4765 px(0.),
4766 Pixels::from(
4767 cursor.row().next_row().as_f64() * ScrollPixelOffset::from(line_height)
4768 - scroll_pixel_position.y,
4769 ),
4770 ),
4771 };
4772
4773 let viewport_bounds =
4774 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4775 right: -right_margin - MENU_GAP,
4776 ..Default::default()
4777 });
4778
4779 let min_height = height_above_menu + min_menu_height + height_below_menu;
4780 let max_height = height_above_menu + max_menu_height + height_below_menu;
4781 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4782 target_position,
4783 line_height,
4784 min_height,
4785 max_height,
4786 context_menu_placement,
4787 text_hitbox,
4788 viewport_bounds,
4789 window,
4790 cx,
4791 |height, max_width_for_stable_x, y_flipped, window, cx| {
4792 // First layout the menu to get its size - others can be at least this wide.
4793 let context_menu = if context_menu_visible {
4794 let menu_height = if y_flipped {
4795 height - height_below_menu
4796 } else {
4797 height - height_above_menu
4798 };
4799 let mut element = self
4800 .render_context_menu(line_height, menu_height, window, cx)
4801 .expect("Visible context menu should always render.");
4802 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4803 Some((CursorPopoverType::CodeContextMenu, element, size))
4804 } else {
4805 None
4806 };
4807 let min_width = context_menu
4808 .as_ref()
4809 .map_or(px(0.), |(_, _, size)| size.width);
4810 let max_width = max_width_for_stable_x.max(
4811 context_menu
4812 .as_ref()
4813 .map_or(px(0.), |(_, _, size)| size.width),
4814 );
4815
4816 let edit_prediction = if edit_prediction_popover_visible {
4817 self.editor.update(cx, move |editor, cx| {
4818 let accept_binding =
4819 editor.accept_edit_prediction_keybind(false, window, cx);
4820 let mut element = editor.render_edit_prediction_cursor_popover(
4821 min_width,
4822 max_width,
4823 cursor_point,
4824 style,
4825 accept_binding.keystroke(),
4826 window,
4827 cx,
4828 )?;
4829 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4830 Some((CursorPopoverType::EditPrediction, element, size))
4831 })
4832 } else {
4833 None
4834 };
4835 vec![edit_prediction, context_menu]
4836 .into_iter()
4837 .flatten()
4838 .collect::<Vec<_>>()
4839 },
4840 )?;
4841
4842 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4843 .iter()
4844 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4845 let last_ix = laid_out_popovers.len() - 1;
4846 let menu_is_last = menu_ix == last_ix;
4847 let first_popover_bounds = laid_out_popovers[0].1;
4848 let last_popover_bounds = laid_out_popovers[last_ix].1;
4849
4850 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4851 // right, and otherwise it goes below or to the right.
4852 let mut target_bounds = Bounds::from_corners(
4853 first_popover_bounds.origin,
4854 last_popover_bounds.bottom_right(),
4855 );
4856 target_bounds.size.width = menu_bounds.size.width;
4857
4858 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4859 // based on this is preferred for layout stability.
4860 let mut max_target_bounds = target_bounds;
4861 max_target_bounds.size.height = max_height;
4862 if y_flipped {
4863 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4864 }
4865
4866 // Add spacing around `target_bounds` and `max_target_bounds`.
4867 let mut extend_amount = Edges::all(MENU_GAP);
4868 if y_flipped {
4869 extend_amount.bottom = line_height;
4870 } else {
4871 extend_amount.top = line_height;
4872 }
4873 let target_bounds = target_bounds.extend(extend_amount);
4874 let max_target_bounds = max_target_bounds.extend(extend_amount);
4875
4876 let must_place_above_or_below =
4877 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4878 laid_out_popovers[menu_ix + 1..]
4879 .iter()
4880 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4881 } else {
4882 false
4883 };
4884
4885 let aside_bounds = self.layout_context_menu_aside(
4886 y_flipped,
4887 *menu_bounds,
4888 target_bounds,
4889 max_target_bounds,
4890 max_menu_height,
4891 must_place_above_or_below,
4892 text_hitbox,
4893 viewport_bounds,
4894 window,
4895 cx,
4896 );
4897
4898 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4899 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4900 Some(*bounds)
4901 } else {
4902 None
4903 }
4904 }) {
4905 let bounds = if let Some(aside_bounds) = aside_bounds {
4906 menu_bounds.union(&aside_bounds)
4907 } else {
4908 menu_bounds
4909 };
4910 return Some(ContextMenuLayout { y_flipped, bounds });
4911 }
4912
4913 None
4914 }
4915
4916 fn layout_gutter_menu(
4917 &self,
4918 line_height: Pixels,
4919 text_hitbox: &Hitbox,
4920 content_origin: gpui::Point<Pixels>,
4921 right_margin: Pixels,
4922 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4923 gutter_overshoot: Pixels,
4924 window: &mut Window,
4925 cx: &mut App,
4926 ) {
4927 let editor = self.editor.read(cx);
4928 if !editor.context_menu_visible() {
4929 return;
4930 }
4931 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4932 editor.context_menu_origin()
4933 else {
4934 return;
4935 };
4936 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4937 // indicator than just a plain first column of the text field.
4938 let target_position = content_origin
4939 + gpui::Point {
4940 x: -gutter_overshoot,
4941 y: Pixels::from(
4942 gutter_row.next_row().as_f64() * ScrollPixelOffset::from(line_height)
4943 - scroll_pixel_position.y,
4944 ),
4945 };
4946
4947 let (min_height_in_lines, max_height_in_lines) = editor
4948 .context_menu_options
4949 .as_ref()
4950 .map_or((3, 12), |options| {
4951 (options.min_entries_visible, options.max_entries_visible)
4952 });
4953
4954 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4955 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4956 let viewport_bounds =
4957 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4958 right: -right_margin - MENU_GAP,
4959 ..Default::default()
4960 });
4961 self.layout_popovers_above_or_below_line(
4962 target_position,
4963 line_height,
4964 min_height,
4965 max_height,
4966 editor
4967 .context_menu_options
4968 .as_ref()
4969 .and_then(|options| options.placement.clone()),
4970 text_hitbox,
4971 viewport_bounds,
4972 window,
4973 cx,
4974 move |height, _max_width_for_stable_x, _, window, cx| {
4975 let mut element = self
4976 .render_context_menu(line_height, height, window, cx)
4977 .expect("Visible context menu should always render.");
4978 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4979 vec![(CursorPopoverType::CodeContextMenu, element, size)]
4980 },
4981 );
4982 }
4983
4984 fn layout_popovers_above_or_below_line(
4985 &self,
4986 target_position: gpui::Point<Pixels>,
4987 line_height: Pixels,
4988 min_height: Pixels,
4989 max_height: Pixels,
4990 placement: Option<ContextMenuPlacement>,
4991 text_hitbox: &Hitbox,
4992 viewport_bounds: Bounds<Pixels>,
4993 window: &mut Window,
4994 cx: &mut App,
4995 make_sized_popovers: impl FnOnce(
4996 Pixels,
4997 Pixels,
4998 bool,
4999 &mut Window,
5000 &mut App,
5001 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
5002 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
5003 let text_style = TextStyleRefinement {
5004 line_height: Some(DefiniteLength::Fraction(
5005 BufferLineHeight::Comfortable.value(),
5006 )),
5007 ..Default::default()
5008 };
5009 window.with_text_style(Some(text_style), |window| {
5010 // If the max height won't fit below and there is more space above, put it above the line.
5011 let bottom_y_when_flipped = target_position.y - line_height;
5012 let available_above = bottom_y_when_flipped - text_hitbox.top();
5013 let available_below = text_hitbox.bottom() - target_position.y;
5014 let y_overflows_below = max_height > available_below;
5015 let mut y_flipped = match placement {
5016 Some(ContextMenuPlacement::Above) => true,
5017 Some(ContextMenuPlacement::Below) => false,
5018 None => y_overflows_below && available_above > available_below,
5019 };
5020 let mut height = cmp::min(
5021 max_height,
5022 if y_flipped {
5023 available_above
5024 } else {
5025 available_below
5026 },
5027 );
5028
5029 // If the min height doesn't fit within text bounds, instead fit within the window.
5030 if height < min_height {
5031 let available_above = bottom_y_when_flipped;
5032 let available_below = viewport_bounds.bottom() - target_position.y;
5033 let (y_flipped_override, height_override) = match placement {
5034 Some(ContextMenuPlacement::Above) => {
5035 (true, cmp::min(available_above, min_height))
5036 }
5037 Some(ContextMenuPlacement::Below) => {
5038 (false, cmp::min(available_below, min_height))
5039 }
5040 None => {
5041 if available_below > min_height {
5042 (false, min_height)
5043 } else if available_above > min_height {
5044 (true, min_height)
5045 } else if available_above > available_below {
5046 (true, available_above)
5047 } else {
5048 (false, available_below)
5049 }
5050 }
5051 };
5052 y_flipped = y_flipped_override;
5053 height = height_override;
5054 }
5055
5056 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
5057
5058 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
5059 // for very narrow windows.
5060 let popovers =
5061 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
5062 if popovers.is_empty() {
5063 return None;
5064 }
5065
5066 let max_width = popovers
5067 .iter()
5068 .map(|(_, _, size)| size.width)
5069 .max()
5070 .unwrap_or_default();
5071
5072 let mut current_position = gpui::Point {
5073 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
5074 // overflow. Include space for the scrollbar.
5075 x: target_position
5076 .x
5077 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
5078 y: if y_flipped {
5079 bottom_y_when_flipped
5080 } else {
5081 target_position.y
5082 },
5083 };
5084
5085 let mut laid_out_popovers = popovers
5086 .into_iter()
5087 .map(|(popover_type, element, size)| {
5088 if y_flipped {
5089 current_position.y -= size.height;
5090 }
5091 let position = current_position;
5092 window.defer_draw(element, current_position, 1);
5093 if !y_flipped {
5094 current_position.y += size.height + MENU_GAP;
5095 } else {
5096 current_position.y -= MENU_GAP;
5097 }
5098 (popover_type, Bounds::new(position, size))
5099 })
5100 .collect::<Vec<_>>();
5101
5102 if y_flipped {
5103 laid_out_popovers.reverse();
5104 }
5105
5106 Some((laid_out_popovers, y_flipped))
5107 })
5108 }
5109
5110 fn layout_context_menu_aside(
5111 &self,
5112 y_flipped: bool,
5113 menu_bounds: Bounds<Pixels>,
5114 target_bounds: Bounds<Pixels>,
5115 max_target_bounds: Bounds<Pixels>,
5116 max_height: Pixels,
5117 must_place_above_or_below: bool,
5118 text_hitbox: &Hitbox,
5119 viewport_bounds: Bounds<Pixels>,
5120 window: &mut Window,
5121 cx: &mut App,
5122 ) -> Option<Bounds<Pixels>> {
5123 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
5124 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
5125 && !must_place_above_or_below
5126 {
5127 let max_width = cmp::min(
5128 available_within_viewport.right - px(1.),
5129 MENU_ASIDE_MAX_WIDTH,
5130 );
5131 let mut aside = self.render_context_menu_aside(
5132 size(max_width, max_height - POPOVER_Y_PADDING),
5133 window,
5134 cx,
5135 )?;
5136 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5137 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
5138 Some((aside, right_position, size))
5139 } else {
5140 let max_size = size(
5141 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
5142 // won't be needed here.
5143 cmp::min(
5144 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
5145 viewport_bounds.right(),
5146 ),
5147 cmp::min(
5148 max_height,
5149 cmp::max(
5150 available_within_viewport.top,
5151 available_within_viewport.bottom,
5152 ),
5153 ) - POPOVER_Y_PADDING,
5154 );
5155 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
5156 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5157
5158 let top_position = point(
5159 menu_bounds.origin.x,
5160 target_bounds.top() - actual_size.height,
5161 );
5162 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
5163
5164 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
5165 // Prefer to fit on the same side of the line as the menu, then on the other side of
5166 // the line.
5167 if !y_flipped && wanted.height < available.bottom {
5168 Some(bottom_position)
5169 } else if !y_flipped && wanted.height < available.top {
5170 Some(top_position)
5171 } else if y_flipped && wanted.height < available.top {
5172 Some(top_position)
5173 } else if y_flipped && wanted.height < available.bottom {
5174 Some(bottom_position)
5175 } else {
5176 None
5177 }
5178 };
5179
5180 // Prefer choosing a direction using max sizes rather than actual size for stability.
5181 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
5182 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
5183 let aside_position = fit_within(available_within_text, wanted)
5184 // Fallback: fit max size in window.
5185 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
5186 // Fallback: fit actual size in window.
5187 .or_else(|| fit_within(available_within_viewport, actual_size));
5188
5189 aside_position.map(|position| (aside, position, actual_size))
5190 };
5191
5192 // Skip drawing if it doesn't fit anywhere.
5193 if let Some((aside, position, size)) = positioned_aside {
5194 let aside_bounds = Bounds::new(position, size);
5195 window.defer_draw(aside, position, 2);
5196 return Some(aside_bounds);
5197 }
5198
5199 None
5200 }
5201
5202 fn render_context_menu(
5203 &self,
5204 line_height: Pixels,
5205 height: Pixels,
5206 window: &mut Window,
5207 cx: &mut App,
5208 ) -> Option<AnyElement> {
5209 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
5210 self.editor.update(cx, |editor, cx| {
5211 editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
5212 })
5213 }
5214
5215 fn render_context_menu_aside(
5216 &self,
5217 max_size: Size<Pixels>,
5218 window: &mut Window,
5219 cx: &mut App,
5220 ) -> Option<AnyElement> {
5221 if max_size.width < px(100.) || max_size.height < px(12.) {
5222 None
5223 } else {
5224 self.editor.update(cx, |editor, cx| {
5225 editor.render_context_menu_aside(max_size, window, cx)
5226 })
5227 }
5228 }
5229
5230 fn layout_mouse_context_menu(
5231 &self,
5232 editor_snapshot: &EditorSnapshot,
5233 visible_range: Range<DisplayRow>,
5234 content_origin: gpui::Point<Pixels>,
5235 window: &mut Window,
5236 cx: &mut App,
5237 ) -> Option<AnyElement> {
5238 let position = self.editor.update(cx, |editor, _cx| {
5239 let visible_start_point = editor.display_to_pixel_point(
5240 DisplayPoint::new(visible_range.start, 0),
5241 editor_snapshot,
5242 window,
5243 )?;
5244 let visible_end_point = editor.display_to_pixel_point(
5245 DisplayPoint::new(visible_range.end, 0),
5246 editor_snapshot,
5247 window,
5248 )?;
5249
5250 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5251 let (source_display_point, position) = match mouse_context_menu.position {
5252 MenuPosition::PinnedToScreen(point) => (None, point),
5253 MenuPosition::PinnedToEditor { source, offset } => {
5254 let source_display_point = source.to_display_point(editor_snapshot);
5255 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
5256 let position = content_origin + source_point + offset;
5257 (Some(source_display_point), position)
5258 }
5259 };
5260
5261 let source_included = source_display_point.is_none_or(|source_display_point| {
5262 visible_range
5263 .to_inclusive()
5264 .contains(&source_display_point.row())
5265 });
5266 let position_included =
5267 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
5268 if !source_included && !position_included {
5269 None
5270 } else {
5271 Some(position)
5272 }
5273 })?;
5274
5275 let text_style = TextStyleRefinement {
5276 line_height: Some(DefiniteLength::Fraction(
5277 BufferLineHeight::Comfortable.value(),
5278 )),
5279 ..Default::default()
5280 };
5281 window.with_text_style(Some(text_style), |window| {
5282 let mut element = self.editor.read_with(cx, |editor, _| {
5283 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5284 let context_menu = mouse_context_menu.context_menu.clone();
5285
5286 Some(
5287 deferred(
5288 anchored()
5289 .position(position)
5290 .child(context_menu)
5291 .anchor(Corner::TopLeft)
5292 .snap_to_window_with_margin(px(8.)),
5293 )
5294 .with_priority(1)
5295 .into_any(),
5296 )
5297 })?;
5298
5299 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
5300 Some(element)
5301 })
5302 }
5303
5304 fn layout_hover_popovers(
5305 &self,
5306 snapshot: &EditorSnapshot,
5307 hitbox: &Hitbox,
5308 visible_display_row_range: Range<DisplayRow>,
5309 content_origin: gpui::Point<Pixels>,
5310 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5311 line_layouts: &[LineWithInvisibles],
5312 line_height: Pixels,
5313 em_width: Pixels,
5314 context_menu_layout: Option<ContextMenuLayout>,
5315 window: &mut Window,
5316 cx: &mut App,
5317 ) {
5318 struct MeasuredHoverPopover {
5319 element: AnyElement,
5320 size: Size<Pixels>,
5321 horizontal_offset: Pixels,
5322 }
5323
5324 let max_size = size(
5325 (120. * em_width) // Default size
5326 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5327 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5328 (16. * line_height) // Default size
5329 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5330 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5331 );
5332
5333 let hover_popovers = self.editor.update(cx, |editor, cx| {
5334 editor.hover_state.render(
5335 snapshot,
5336 visible_display_row_range.clone(),
5337 max_size,
5338 &editor.text_layout_details(window),
5339 window,
5340 cx,
5341 )
5342 });
5343 let Some((popover_position, hover_popovers)) = hover_popovers else {
5344 return;
5345 };
5346
5347 // This is safe because we check on layout whether the required row is available
5348 let hovered_row_layout = &line_layouts[popover_position
5349 .row()
5350 .minus(visible_display_row_range.start)
5351 as usize];
5352
5353 // Compute Hovered Point
5354 let x = hovered_row_layout.x_for_index(popover_position.column() as usize)
5355 - Pixels::from(scroll_pixel_position.x);
5356 let y = Pixels::from(
5357 popover_position.row().as_f64() * ScrollPixelOffset::from(line_height)
5358 - scroll_pixel_position.y,
5359 );
5360 let hovered_point = content_origin + point(x, y);
5361
5362 let mut overall_height = Pixels::ZERO;
5363 let mut measured_hover_popovers = Vec::new();
5364 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
5365 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
5366 let horizontal_offset =
5367 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
5368 .min(Pixels::ZERO);
5369 match position {
5370 itertools::Position::Middle | itertools::Position::Last => {
5371 overall_height += HOVER_POPOVER_GAP
5372 }
5373 _ => {}
5374 }
5375 overall_height += size.height;
5376 measured_hover_popovers.push(MeasuredHoverPopover {
5377 element: hover_popover,
5378 size,
5379 horizontal_offset,
5380 });
5381 }
5382
5383 fn draw_occluder(
5384 width: Pixels,
5385 origin: gpui::Point<Pixels>,
5386 window: &mut Window,
5387 cx: &mut App,
5388 ) {
5389 let mut occlusion = div()
5390 .size_full()
5391 .occlude()
5392 .on_mouse_move(|_, _, cx| cx.stop_propagation())
5393 .into_any_element();
5394 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
5395 window.defer_draw(occlusion, origin, 2);
5396 }
5397
5398 fn place_popovers_above(
5399 hovered_point: gpui::Point<Pixels>,
5400 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5401 window: &mut Window,
5402 cx: &mut App,
5403 ) {
5404 let mut current_y = hovered_point.y;
5405 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5406 let size = popover.size;
5407 let popover_origin = point(
5408 hovered_point.x + popover.horizontal_offset,
5409 current_y - size.height,
5410 );
5411
5412 window.defer_draw(popover.element, popover_origin, 2);
5413 if position != itertools::Position::Last {
5414 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
5415 draw_occluder(size.width, origin, window, cx);
5416 }
5417
5418 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5419 }
5420 }
5421
5422 fn place_popovers_below(
5423 hovered_point: gpui::Point<Pixels>,
5424 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5425 line_height: Pixels,
5426 window: &mut Window,
5427 cx: &mut App,
5428 ) {
5429 let mut current_y = hovered_point.y + line_height;
5430 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5431 let size = popover.size;
5432 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5433
5434 window.defer_draw(popover.element, popover_origin, 2);
5435 if position != itertools::Position::Last {
5436 let origin = point(popover_origin.x, popover_origin.y + size.height);
5437 draw_occluder(size.width, origin, window, cx);
5438 }
5439
5440 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5441 }
5442 }
5443
5444 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5445 context_menu_layout
5446 .as_ref()
5447 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5448 };
5449
5450 let can_place_above = {
5451 let mut bounds_above = Vec::new();
5452 let mut current_y = hovered_point.y;
5453 for popover in &measured_hover_popovers {
5454 let size = popover.size;
5455 let popover_origin = point(
5456 hovered_point.x + popover.horizontal_offset,
5457 current_y - size.height,
5458 );
5459 bounds_above.push(Bounds::new(popover_origin, size));
5460 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5461 }
5462 bounds_above
5463 .iter()
5464 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5465 };
5466
5467 let can_place_below = || {
5468 let mut bounds_below = Vec::new();
5469 let mut current_y = hovered_point.y + line_height;
5470 for popover in &measured_hover_popovers {
5471 let size = popover.size;
5472 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5473 bounds_below.push(Bounds::new(popover_origin, size));
5474 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5475 }
5476 bounds_below
5477 .iter()
5478 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5479 };
5480
5481 if can_place_above {
5482 // try placing above hovered point
5483 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5484 } else if can_place_below() {
5485 // try placing below hovered point
5486 place_popovers_below(
5487 hovered_point,
5488 measured_hover_popovers,
5489 line_height,
5490 window,
5491 cx,
5492 );
5493 } else {
5494 // try to place popovers around the context menu
5495 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5496 let total_width = measured_hover_popovers
5497 .iter()
5498 .map(|p| p.size.width)
5499 .max()
5500 .unwrap_or(Pixels::ZERO);
5501 let y_for_horizontal_positioning = if menu.y_flipped {
5502 menu.bounds.bottom() - overall_height
5503 } else {
5504 menu.bounds.top()
5505 };
5506 let possible_origins = vec![
5507 // left of context menu
5508 point(
5509 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
5510 y_for_horizontal_positioning,
5511 ),
5512 // right of context menu
5513 point(
5514 menu.bounds.right() + HOVER_POPOVER_GAP,
5515 y_for_horizontal_positioning,
5516 ),
5517 // top of context menu
5518 point(
5519 menu.bounds.left(),
5520 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
5521 ),
5522 // bottom of context menu
5523 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5524 ];
5525 possible_origins.into_iter().find(|&origin| {
5526 Bounds::new(origin, size(total_width, overall_height))
5527 .is_contained_within(hitbox)
5528 })
5529 });
5530 if let Some(origin) = origin_surrounding_menu {
5531 let mut current_y = origin.y;
5532 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5533 let size = popover.size;
5534 let popover_origin = point(origin.x, current_y);
5535
5536 window.defer_draw(popover.element, popover_origin, 2);
5537 if position != itertools::Position::Last {
5538 let origin = point(popover_origin.x, popover_origin.y + size.height);
5539 draw_occluder(size.width, origin, window, cx);
5540 }
5541
5542 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5543 }
5544 } else {
5545 // fallback to existing above/below cursor logic
5546 // this might overlap menu or overflow in rare case
5547 if can_place_above {
5548 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5549 } else {
5550 place_popovers_below(
5551 hovered_point,
5552 measured_hover_popovers,
5553 line_height,
5554 window,
5555 cx,
5556 );
5557 }
5558 }
5559 }
5560 }
5561
5562 fn layout_diff_hunk_controls(
5563 &self,
5564 row_range: Range<DisplayRow>,
5565 row_infos: &[RowInfo],
5566 text_hitbox: &Hitbox,
5567 newest_cursor_position: Option<DisplayPoint>,
5568 line_height: Pixels,
5569 right_margin: Pixels,
5570 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5571 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5572 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
5573 editor: Entity<Editor>,
5574 window: &mut Window,
5575 cx: &mut App,
5576 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
5577 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
5578 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
5579
5580 let mut controls = vec![];
5581 let mut control_bounds = vec![];
5582
5583 let active_positions = [
5584 hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
5585 newest_cursor_position,
5586 ];
5587
5588 for (hunk, _) in display_hunks {
5589 if let DisplayDiffHunk::Unfolded {
5590 display_row_range,
5591 multi_buffer_range,
5592 status,
5593 is_created_file,
5594 ..
5595 } = &hunk
5596 {
5597 if display_row_range.start < row_range.start
5598 || display_row_range.start >= row_range.end
5599 {
5600 continue;
5601 }
5602 if highlighted_rows
5603 .get(&display_row_range.start)
5604 .and_then(|highlight| highlight.type_id)
5605 .is_some_and(|type_id| {
5606 [
5607 TypeId::of::<ConflictsOuter>(),
5608 TypeId::of::<ConflictsOursMarker>(),
5609 TypeId::of::<ConflictsOurs>(),
5610 TypeId::of::<ConflictsTheirs>(),
5611 TypeId::of::<ConflictsTheirsMarker>(),
5612 ]
5613 .contains(&type_id)
5614 })
5615 {
5616 continue;
5617 }
5618 let row_ix = (display_row_range.start - row_range.start).0 as usize;
5619 if row_infos[row_ix].diff_status.is_none() {
5620 continue;
5621 }
5622 if row_infos[row_ix]
5623 .diff_status
5624 .is_some_and(|status| status.is_added())
5625 && !status.is_added()
5626 {
5627 continue;
5628 }
5629
5630 if active_positions
5631 .iter()
5632 .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
5633 {
5634 let y = (display_row_range.start.as_f64()
5635 * ScrollPixelOffset::from(line_height)
5636 + ScrollPixelOffset::from(text_hitbox.bounds.top())
5637 - scroll_pixel_position.y)
5638 .into();
5639
5640 let mut element = render_diff_hunk_controls(
5641 display_row_range.start.0,
5642 status,
5643 multi_buffer_range.clone(),
5644 *is_created_file,
5645 line_height,
5646 &editor,
5647 window,
5648 cx,
5649 );
5650 let size =
5651 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5652
5653 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5654
5655 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5656 control_bounds.push((display_row_range.start, bounds));
5657
5658 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5659 element.prepaint(window, cx)
5660 });
5661 controls.push(element);
5662 }
5663 }
5664 }
5665
5666 (controls, control_bounds)
5667 }
5668
5669 fn layout_signature_help(
5670 &self,
5671 hitbox: &Hitbox,
5672 content_origin: gpui::Point<Pixels>,
5673 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5674 newest_selection_head: Option<DisplayPoint>,
5675 start_row: DisplayRow,
5676 line_layouts: &[LineWithInvisibles],
5677 line_height: Pixels,
5678 em_width: Pixels,
5679 context_menu_layout: Option<ContextMenuLayout>,
5680 window: &mut Window,
5681 cx: &mut App,
5682 ) {
5683 if !self.editor.focus_handle(cx).is_focused(window) {
5684 return;
5685 }
5686 let Some(newest_selection_head) = newest_selection_head else {
5687 return;
5688 };
5689
5690 let max_size = size(
5691 (120. * em_width) // Default size
5692 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5693 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5694 (16. * line_height) // Default size
5695 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5696 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5697 );
5698
5699 let maybe_element = self.editor.update(cx, |editor, cx| {
5700 if let Some(popover) = editor.signature_help_state.popover_mut() {
5701 let element = popover.render(max_size, window, cx);
5702 Some(element)
5703 } else {
5704 None
5705 }
5706 });
5707 let Some(mut element) = maybe_element else {
5708 return;
5709 };
5710
5711 let selection_row = newest_selection_head.row();
5712 let Some(cursor_row_layout) = (selection_row >= start_row)
5713 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5714 .flatten()
5715 else {
5716 return;
5717 };
5718
5719 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5720 - Pixels::from(scroll_pixel_position.x);
5721 let target_y = Pixels::from(
5722 selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
5723 );
5724 let target_point = content_origin + point(target_x, target_y);
5725
5726 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5727
5728 let (popover_bounds_above, popover_bounds_below) = {
5729 let horizontal_offset = (hitbox.top_right().x
5730 - POPOVER_RIGHT_OFFSET
5731 - (target_point.x + actual_size.width))
5732 .min(Pixels::ZERO);
5733 let initial_x = target_point.x + horizontal_offset;
5734 (
5735 Bounds::new(
5736 point(initial_x, target_point.y - actual_size.height),
5737 actual_size,
5738 ),
5739 Bounds::new(
5740 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5741 actual_size,
5742 ),
5743 )
5744 };
5745
5746 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5747 context_menu_layout
5748 .as_ref()
5749 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5750 };
5751
5752 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5753 && !intersects_menu(popover_bounds_above)
5754 {
5755 // try placing above cursor
5756 popover_bounds_above.origin
5757 } else if popover_bounds_below.is_contained_within(hitbox)
5758 && !intersects_menu(popover_bounds_below)
5759 {
5760 // try placing below cursor
5761 popover_bounds_below.origin
5762 } else {
5763 // try surrounding context menu if exists
5764 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5765 let y_for_horizontal_positioning = if menu.y_flipped {
5766 menu.bounds.bottom() - actual_size.height
5767 } else {
5768 menu.bounds.top()
5769 };
5770 let possible_origins = vec![
5771 // left of context menu
5772 point(
5773 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5774 y_for_horizontal_positioning,
5775 ),
5776 // right of context menu
5777 point(
5778 menu.bounds.right() + HOVER_POPOVER_GAP,
5779 y_for_horizontal_positioning,
5780 ),
5781 // top of context menu
5782 point(
5783 menu.bounds.left(),
5784 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5785 ),
5786 // bottom of context menu
5787 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5788 ];
5789 possible_origins
5790 .into_iter()
5791 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5792 });
5793 origin_surrounding_menu.unwrap_or_else(|| {
5794 // fallback to existing above/below cursor logic
5795 // this might overlap menu or overflow in rare case
5796 if popover_bounds_above.is_contained_within(hitbox) {
5797 popover_bounds_above.origin
5798 } else {
5799 popover_bounds_below.origin
5800 }
5801 })
5802 };
5803
5804 window.defer_draw(element, final_origin, 2);
5805 }
5806
5807 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5808 window.paint_layer(layout.hitbox.bounds, |window| {
5809 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5810 let gutter_bg = cx.theme().colors().editor_gutter_background;
5811 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5812 window.paint_quad(fill(
5813 layout.position_map.text_hitbox.bounds,
5814 self.style.background,
5815 ));
5816
5817 if matches!(
5818 layout.mode,
5819 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5820 ) {
5821 let show_active_line_background = match layout.mode {
5822 EditorMode::Full {
5823 show_active_line_background,
5824 ..
5825 } => show_active_line_background,
5826 EditorMode::Minimap { .. } => true,
5827 _ => false,
5828 };
5829 let mut active_rows = layout.active_rows.iter().peekable();
5830 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5831 let mut end_row = start_row.0;
5832 while active_rows
5833 .peek()
5834 .is_some_and(|(active_row, has_selection)| {
5835 active_row.0 == end_row + 1
5836 && has_selection.selection == contains_non_empty_selection.selection
5837 })
5838 {
5839 active_rows.next().unwrap();
5840 end_row += 1;
5841 }
5842
5843 if show_active_line_background && !contains_non_empty_selection.selection {
5844 let highlight_h_range =
5845 match layout.position_map.snapshot.current_line_highlight {
5846 CurrentLineHighlight::Gutter => Some(Range {
5847 start: layout.hitbox.left(),
5848 end: layout.gutter_hitbox.right(),
5849 }),
5850 CurrentLineHighlight::Line => Some(Range {
5851 start: layout.position_map.text_hitbox.bounds.left(),
5852 end: layout.position_map.text_hitbox.bounds.right(),
5853 }),
5854 CurrentLineHighlight::All => Some(Range {
5855 start: layout.hitbox.left(),
5856 end: layout.hitbox.right(),
5857 }),
5858 CurrentLineHighlight::None => None,
5859 };
5860 if let Some(range) = highlight_h_range {
5861 let active_line_bg = cx.theme().colors().editor_active_line_background;
5862 let bounds = Bounds {
5863 origin: point(
5864 range.start,
5865 layout.hitbox.origin.y
5866 + Pixels::from(
5867 (start_row.as_f64() - scroll_top)
5868 * ScrollPixelOffset::from(
5869 layout.position_map.line_height,
5870 ),
5871 ),
5872 ),
5873 size: size(
5874 range.end - range.start,
5875 layout.position_map.line_height
5876 * (end_row - start_row.0 + 1) as f32,
5877 ),
5878 };
5879 window.paint_quad(fill(bounds, active_line_bg));
5880 }
5881 }
5882 }
5883
5884 let mut paint_highlight = |highlight_row_start: DisplayRow,
5885 highlight_row_end: DisplayRow,
5886 highlight: crate::LineHighlight,
5887 edges| {
5888 let mut origin_x = layout.hitbox.left();
5889 let mut width = layout.hitbox.size.width;
5890 if !highlight.include_gutter {
5891 origin_x += layout.gutter_hitbox.size.width;
5892 width -= layout.gutter_hitbox.size.width;
5893 }
5894
5895 let origin = point(
5896 origin_x,
5897 layout.hitbox.origin.y
5898 + Pixels::from(
5899 (highlight_row_start.as_f64() - scroll_top)
5900 * ScrollPixelOffset::from(layout.position_map.line_height),
5901 ),
5902 );
5903 let size = size(
5904 width,
5905 layout.position_map.line_height
5906 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5907 );
5908 let mut quad = fill(Bounds { origin, size }, highlight.background);
5909 if let Some(border_color) = highlight.border {
5910 quad.border_color = border_color;
5911 quad.border_widths = edges
5912 }
5913 window.paint_quad(quad);
5914 };
5915
5916 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5917 None;
5918 for (&new_row, &new_background) in &layout.highlighted_rows {
5919 match &mut current_paint {
5920 &mut Some((current_background, ref mut current_range, mut edges)) => {
5921 let new_range_started = current_background != new_background
5922 || current_range.end.next_row() != new_row;
5923 if new_range_started {
5924 if current_range.end.next_row() == new_row {
5925 edges.bottom = px(0.);
5926 };
5927 paint_highlight(
5928 current_range.start,
5929 current_range.end,
5930 current_background,
5931 edges,
5932 );
5933 let edges = Edges {
5934 top: if current_range.end.next_row() != new_row {
5935 px(1.)
5936 } else {
5937 px(0.)
5938 },
5939 bottom: px(1.),
5940 ..Default::default()
5941 };
5942 current_paint = Some((new_background, new_row..new_row, edges));
5943 continue;
5944 } else {
5945 current_range.end = current_range.end.next_row();
5946 }
5947 }
5948 None => {
5949 let edges = Edges {
5950 top: px(1.),
5951 bottom: px(1.),
5952 ..Default::default()
5953 };
5954 current_paint = Some((new_background, new_row..new_row, edges))
5955 }
5956 };
5957 }
5958 if let Some((color, range, edges)) = current_paint {
5959 paint_highlight(range.start, range.end, color, edges);
5960 }
5961
5962 for (guide_x, active) in layout.wrap_guides.iter() {
5963 let color = if *active {
5964 cx.theme().colors().editor_active_wrap_guide
5965 } else {
5966 cx.theme().colors().editor_wrap_guide
5967 };
5968 window.paint_quad(fill(
5969 Bounds {
5970 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5971 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5972 },
5973 color,
5974 ));
5975 }
5976 }
5977 })
5978 }
5979
5980 fn paint_indent_guides(
5981 &mut self,
5982 layout: &mut EditorLayout,
5983 window: &mut Window,
5984 cx: &mut App,
5985 ) {
5986 let Some(indent_guides) = &layout.indent_guides else {
5987 return;
5988 };
5989
5990 let faded_color = |color: Hsla, alpha: f32| {
5991 let mut faded = color;
5992 faded.a = alpha;
5993 faded
5994 };
5995
5996 for indent_guide in indent_guides {
5997 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
5998 let settings = &indent_guide.settings;
5999
6000 // TODO fixed for now, expose them through themes later
6001 const INDENT_AWARE_ALPHA: f32 = 0.2;
6002 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
6003 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
6004 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
6005
6006 let line_color = match (settings.coloring, indent_guide.active) {
6007 (IndentGuideColoring::Disabled, _) => None,
6008 (IndentGuideColoring::Fixed, false) => {
6009 Some(cx.theme().colors().editor_indent_guide)
6010 }
6011 (IndentGuideColoring::Fixed, true) => {
6012 Some(cx.theme().colors().editor_indent_guide_active)
6013 }
6014 (IndentGuideColoring::IndentAware, false) => {
6015 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
6016 }
6017 (IndentGuideColoring::IndentAware, true) => {
6018 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
6019 }
6020 };
6021
6022 let background_color = match (settings.background_coloring, indent_guide.active) {
6023 (IndentGuideBackgroundColoring::Disabled, _) => None,
6024 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
6025 indent_accent_colors,
6026 INDENT_AWARE_BACKGROUND_ALPHA,
6027 )),
6028 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
6029 indent_accent_colors,
6030 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
6031 )),
6032 };
6033
6034 let requested_line_width = if indent_guide.active {
6035 settings.active_line_width
6036 } else {
6037 settings.line_width
6038 }
6039 .clamp(1, 10);
6040 let mut line_indicator_width = 0.;
6041 if let Some(color) = line_color {
6042 window.paint_quad(fill(
6043 Bounds {
6044 origin: indent_guide.origin,
6045 size: size(px(requested_line_width as f32), indent_guide.length),
6046 },
6047 color,
6048 ));
6049 line_indicator_width = requested_line_width as f32;
6050 }
6051
6052 if let Some(color) = background_color {
6053 let width = indent_guide.single_indent_width - px(line_indicator_width);
6054 window.paint_quad(fill(
6055 Bounds {
6056 origin: point(
6057 indent_guide.origin.x + px(line_indicator_width),
6058 indent_guide.origin.y,
6059 ),
6060 size: size(width, indent_guide.length),
6061 },
6062 color,
6063 ));
6064 }
6065 }
6066 }
6067
6068 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6069 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
6070
6071 let line_height = layout.position_map.line_height;
6072 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
6073
6074 for line_layout in layout.line_numbers.values() {
6075 for LineNumberSegment {
6076 shaped_line,
6077 hitbox,
6078 } in &line_layout.segments
6079 {
6080 let Some(hitbox) = hitbox else {
6081 continue;
6082 };
6083
6084 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
6085 let color = cx.theme().colors().editor_hover_line_number;
6086
6087 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
6088 line.paint(hitbox.origin, line_height, window, cx).log_err()
6089 } else {
6090 shaped_line
6091 .paint(hitbox.origin, line_height, window, cx)
6092 .log_err()
6093 }) else {
6094 continue;
6095 };
6096
6097 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
6098 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
6099 if is_singleton {
6100 window.set_cursor_style(CursorStyle::IBeam, hitbox);
6101 } else {
6102 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
6103 }
6104 }
6105 }
6106 }
6107
6108 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6109 if layout.display_hunks.is_empty() {
6110 return;
6111 }
6112
6113 let line_height = layout.position_map.line_height;
6114 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6115 for (hunk, hitbox) in &layout.display_hunks {
6116 let hunk_to_paint = match hunk {
6117 DisplayDiffHunk::Folded { .. } => {
6118 let hunk_bounds = Self::diff_hunk_bounds(
6119 &layout.position_map.snapshot,
6120 line_height,
6121 layout.gutter_hitbox.bounds,
6122 hunk,
6123 );
6124 Some((
6125 hunk_bounds,
6126 cx.theme().colors().version_control_modified,
6127 Corners::all(px(0.)),
6128 DiffHunkStatus::modified_none(),
6129 ))
6130 }
6131 DisplayDiffHunk::Unfolded {
6132 status,
6133 display_row_range,
6134 ..
6135 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
6136 DiffHunkStatusKind::Added => (
6137 hunk_hitbox.bounds,
6138 cx.theme().colors().version_control_added,
6139 Corners::all(px(0.)),
6140 *status,
6141 ),
6142 DiffHunkStatusKind::Modified => (
6143 hunk_hitbox.bounds,
6144 cx.theme().colors().version_control_modified,
6145 Corners::all(px(0.)),
6146 *status,
6147 ),
6148 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
6149 hunk_hitbox.bounds,
6150 cx.theme().colors().version_control_deleted,
6151 Corners::all(px(0.)),
6152 *status,
6153 ),
6154 DiffHunkStatusKind::Deleted => (
6155 Bounds::new(
6156 point(
6157 hunk_hitbox.origin.x - hunk_hitbox.size.width,
6158 hunk_hitbox.origin.y,
6159 ),
6160 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
6161 ),
6162 cx.theme().colors().version_control_deleted,
6163 Corners::all(1. * line_height),
6164 *status,
6165 ),
6166 }),
6167 };
6168
6169 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
6170 // Flatten the background color with the editor color to prevent
6171 // elements below transparent hunks from showing through
6172 let flattened_background_color = cx
6173 .theme()
6174 .colors()
6175 .editor_background
6176 .blend(background_color);
6177
6178 if !Self::diff_hunk_hollow(status, cx) {
6179 window.paint_quad(quad(
6180 hunk_bounds,
6181 corner_radii,
6182 flattened_background_color,
6183 Edges::default(),
6184 transparent_black(),
6185 BorderStyle::default(),
6186 ));
6187 } else {
6188 let flattened_unstaged_background_color = cx
6189 .theme()
6190 .colors()
6191 .editor_background
6192 .blend(background_color.opacity(0.3));
6193
6194 window.paint_quad(quad(
6195 hunk_bounds,
6196 corner_radii,
6197 flattened_unstaged_background_color,
6198 Edges::all(px(1.0)),
6199 flattened_background_color,
6200 BorderStyle::Solid,
6201 ));
6202 }
6203 }
6204 }
6205 });
6206 }
6207
6208 fn gutter_strip_width(line_height: Pixels) -> Pixels {
6209 (0.275 * line_height).floor()
6210 }
6211
6212 fn diff_hunk_bounds(
6213 snapshot: &EditorSnapshot,
6214 line_height: Pixels,
6215 gutter_bounds: Bounds<Pixels>,
6216 hunk: &DisplayDiffHunk,
6217 ) -> Bounds<Pixels> {
6218 let scroll_position = snapshot.scroll_position();
6219 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
6220 let gutter_strip_width = Self::gutter_strip_width(line_height);
6221
6222 match hunk {
6223 DisplayDiffHunk::Folded { display_row, .. } => {
6224 let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
6225 - scroll_top)
6226 .into();
6227 let end_y = start_y + line_height;
6228 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6229 let highlight_size = size(gutter_strip_width, end_y - start_y);
6230 Bounds::new(highlight_origin, highlight_size)
6231 }
6232 DisplayDiffHunk::Unfolded {
6233 display_row_range,
6234 status,
6235 ..
6236 } => {
6237 if status.is_deleted() && display_row_range.is_empty() {
6238 let row = display_row_range.start;
6239
6240 let offset = ScrollPixelOffset::from(line_height / 2.);
6241 let start_y =
6242 (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
6243 .into();
6244 let end_y = start_y + line_height;
6245
6246 let width = (0.35 * line_height).floor();
6247 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6248 let highlight_size = size(width, end_y - start_y);
6249 Bounds::new(highlight_origin, highlight_size)
6250 } else {
6251 let start_row = display_row_range.start;
6252 let end_row = display_row_range.end;
6253 // If we're in a multibuffer, row range span might include an
6254 // excerpt header, so if we were to draw the marker straight away,
6255 // the hunk might include the rows of that header.
6256 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
6257 // Instead, we simply check whether the range we're dealing with includes
6258 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
6259 let end_row_in_current_excerpt = snapshot
6260 .blocks_in_range(start_row..end_row)
6261 .find_map(|(start_row, block)| {
6262 if matches!(
6263 block,
6264 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
6265 ) {
6266 Some(start_row)
6267 } else {
6268 None
6269 }
6270 })
6271 .unwrap_or(end_row);
6272
6273 let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
6274 - scroll_top)
6275 .into();
6276 let end_y = Pixels::from(
6277 end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
6278 - scroll_top,
6279 );
6280
6281 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6282 let highlight_size = size(gutter_strip_width, end_y - start_y);
6283 Bounds::new(highlight_origin, highlight_size)
6284 }
6285 }
6286 }
6287 }
6288
6289 fn paint_gutter_indicators(
6290 &self,
6291 layout: &mut EditorLayout,
6292 window: &mut Window,
6293 cx: &mut App,
6294 ) {
6295 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6296 window.with_element_namespace("crease_toggles", |window| {
6297 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
6298 crease_toggle.paint(window, cx);
6299 }
6300 });
6301
6302 window.with_element_namespace("expand_toggles", |window| {
6303 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
6304 expand_toggle.paint(window, cx);
6305 }
6306 });
6307
6308 for breakpoint in layout.breakpoints.iter_mut() {
6309 breakpoint.paint(window, cx);
6310 }
6311
6312 for test_indicator in layout.test_indicators.iter_mut() {
6313 test_indicator.paint(window, cx);
6314 }
6315 });
6316 }
6317
6318 fn paint_gutter_highlights(
6319 &self,
6320 layout: &mut EditorLayout,
6321 window: &mut Window,
6322 cx: &mut App,
6323 ) {
6324 for (_, hunk_hitbox) in &layout.display_hunks {
6325 if let Some(hunk_hitbox) = hunk_hitbox
6326 && !self
6327 .editor
6328 .read(cx)
6329 .buffer()
6330 .read(cx)
6331 .all_diff_hunks_expanded()
6332 {
6333 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
6334 }
6335 }
6336
6337 let show_git_gutter = layout
6338 .position_map
6339 .snapshot
6340 .show_git_diff_gutter
6341 .unwrap_or_else(|| {
6342 matches!(
6343 ProjectSettings::get_global(cx).git.git_gutter,
6344 GitGutterSetting::TrackedFiles
6345 )
6346 });
6347 if show_git_gutter {
6348 Self::paint_gutter_diff_hunks(layout, window, cx)
6349 }
6350
6351 let highlight_width = 0.275 * layout.position_map.line_height;
6352 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
6353 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6354 for (range, color) in &layout.highlighted_gutter_ranges {
6355 let start_row = if range.start.row() < layout.visible_display_row_range.start {
6356 layout.visible_display_row_range.start - DisplayRow(1)
6357 } else {
6358 range.start.row()
6359 };
6360 let end_row = if range.end.row() > layout.visible_display_row_range.end {
6361 layout.visible_display_row_range.end + DisplayRow(1)
6362 } else {
6363 range.end.row()
6364 };
6365
6366 let start_y = layout.gutter_hitbox.top()
6367 + Pixels::from(
6368 start_row.0 as f64
6369 * ScrollPixelOffset::from(layout.position_map.line_height)
6370 - layout.position_map.scroll_pixel_position.y,
6371 );
6372 let end_y = layout.gutter_hitbox.top()
6373 + Pixels::from(
6374 (end_row.0 + 1) as f64
6375 * ScrollPixelOffset::from(layout.position_map.line_height)
6376 - layout.position_map.scroll_pixel_position.y,
6377 );
6378 let bounds = Bounds::from_corners(
6379 point(layout.gutter_hitbox.left(), start_y),
6380 point(layout.gutter_hitbox.left() + highlight_width, end_y),
6381 );
6382 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
6383 }
6384 });
6385 }
6386
6387 fn paint_blamed_display_rows(
6388 &self,
6389 layout: &mut EditorLayout,
6390 window: &mut Window,
6391 cx: &mut App,
6392 ) {
6393 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
6394 return;
6395 };
6396
6397 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6398 for mut blame_element in blamed_display_rows.into_iter() {
6399 blame_element.paint(window, cx);
6400 }
6401 })
6402 }
6403
6404 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6405 window.with_content_mask(
6406 Some(ContentMask {
6407 bounds: layout.position_map.text_hitbox.bounds,
6408 }),
6409 |window| {
6410 let editor = self.editor.read(cx);
6411 if editor.mouse_cursor_hidden {
6412 window.set_window_cursor_style(CursorStyle::None);
6413 } else if let SelectionDragState::ReadyToDrag {
6414 mouse_down_time, ..
6415 } = &editor.selection_drag_state
6416 {
6417 let drag_and_drop_delay = Duration::from_millis(
6418 EditorSettings::get_global(cx)
6419 .drag_and_drop_selection
6420 .delay
6421 .0,
6422 );
6423 if mouse_down_time.elapsed() >= drag_and_drop_delay {
6424 window.set_cursor_style(
6425 CursorStyle::DragCopy,
6426 &layout.position_map.text_hitbox,
6427 );
6428 }
6429 } else if matches!(
6430 editor.selection_drag_state,
6431 SelectionDragState::Dragging { .. }
6432 ) {
6433 window
6434 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
6435 } else if editor
6436 .hovered_link_state
6437 .as_ref()
6438 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
6439 {
6440 window.set_cursor_style(
6441 CursorStyle::PointingHand,
6442 &layout.position_map.text_hitbox,
6443 );
6444 } else {
6445 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
6446 };
6447
6448 self.paint_lines_background(layout, window, cx);
6449 let invisible_display_ranges = self.paint_highlights(layout, window, cx);
6450 self.paint_document_colors(layout, window);
6451 self.paint_lines(&invisible_display_ranges, layout, window, cx);
6452 self.paint_redactions(layout, window);
6453 self.paint_cursors(layout, window, cx);
6454 self.paint_inline_diagnostics(layout, window, cx);
6455 self.paint_inline_blame(layout, window, cx);
6456 self.paint_inline_code_actions(layout, window, cx);
6457 self.paint_diff_hunk_controls(layout, window, cx);
6458 window.with_element_namespace("crease_trailers", |window| {
6459 for trailer in layout.crease_trailers.iter_mut().flatten() {
6460 trailer.element.paint(window, cx);
6461 }
6462 });
6463 },
6464 )
6465 }
6466
6467 fn paint_highlights(
6468 &mut self,
6469 layout: &mut EditorLayout,
6470 window: &mut Window,
6471 cx: &mut App,
6472 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6473 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6474 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6475 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6476 for (range, color) in &layout.highlighted_ranges {
6477 self.paint_highlighted_range(
6478 range.clone(),
6479 true,
6480 *color,
6481 Pixels::ZERO,
6482 line_end_overshoot,
6483 layout,
6484 window,
6485 );
6486 }
6487
6488 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
6489 0.15 * layout.position_map.line_height
6490 } else {
6491 Pixels::ZERO
6492 };
6493
6494 for (player_color, selections) in &layout.selections {
6495 for selection in selections.iter() {
6496 self.paint_highlighted_range(
6497 selection.range.clone(),
6498 true,
6499 player_color.selection,
6500 corner_radius,
6501 corner_radius * 2.,
6502 layout,
6503 window,
6504 );
6505
6506 if selection.is_local && !selection.range.is_empty() {
6507 invisible_display_ranges.push(selection.range.clone());
6508 }
6509 }
6510 }
6511 invisible_display_ranges
6512 })
6513 }
6514
6515 fn paint_lines(
6516 &mut self,
6517 invisible_display_ranges: &[Range<DisplayPoint>],
6518 layout: &mut EditorLayout,
6519 window: &mut Window,
6520 cx: &mut App,
6521 ) {
6522 let whitespace_setting = self
6523 .editor
6524 .read(cx)
6525 .buffer
6526 .read(cx)
6527 .language_settings(cx)
6528 .show_whitespaces;
6529
6530 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6531 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6532 line_with_invisibles.draw(
6533 layout,
6534 row,
6535 layout.content_origin,
6536 whitespace_setting,
6537 invisible_display_ranges,
6538 window,
6539 cx,
6540 )
6541 }
6542
6543 for line_element in &mut layout.line_elements {
6544 line_element.paint(window, cx);
6545 }
6546 }
6547
6548 fn paint_sticky_headers(
6549 &mut self,
6550 layout: &mut EditorLayout,
6551 window: &mut Window,
6552 cx: &mut App,
6553 ) {
6554 let Some(mut sticky_headers) = layout.sticky_headers.take() else {
6555 return;
6556 };
6557
6558 if sticky_headers.lines.is_empty() {
6559 layout.sticky_headers = Some(sticky_headers);
6560 return;
6561 }
6562
6563 let whitespace_setting = self
6564 .editor
6565 .read(cx)
6566 .buffer
6567 .read(cx)
6568 .language_settings(cx)
6569 .show_whitespaces;
6570 sticky_headers.paint(layout, whitespace_setting, window, cx);
6571
6572 let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
6573 .lines
6574 .iter()
6575 .map(|line| line.hitbox.clone())
6576 .collect();
6577 let hovered_hitbox = sticky_header_hitboxes
6578 .iter()
6579 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6580
6581 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
6582 if !phase.bubble() {
6583 return;
6584 }
6585
6586 let current_hover = sticky_header_hitboxes
6587 .iter()
6588 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6589 if hovered_hitbox != current_hover {
6590 window.refresh();
6591 }
6592 });
6593
6594 for (line_index, line) in sticky_headers.lines.iter().enumerate() {
6595 let editor = self.editor.clone();
6596 let hitbox = line.hitbox.clone();
6597 let target_anchor = line.target_anchor;
6598 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
6599 if !phase.bubble() {
6600 return;
6601 }
6602
6603 if event.button == MouseButton::Left && hitbox.is_hovered(window) {
6604 editor.update(cx, |editor, cx| {
6605 editor.change_selections(
6606 SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
6607 window,
6608 cx,
6609 |selections| selections.select_ranges([target_anchor..target_anchor]),
6610 );
6611 cx.stop_propagation();
6612 });
6613 }
6614 });
6615 }
6616
6617 let text_bounds = layout.position_map.text_hitbox.bounds;
6618 let border_top = text_bounds.top()
6619 + sticky_headers.lines.last().unwrap().offset
6620 + layout.position_map.line_height;
6621 let separator_height = px(1.);
6622 let border_bounds = Bounds::from_corners(
6623 point(layout.gutter_hitbox.bounds.left(), border_top),
6624 point(text_bounds.right(), border_top + separator_height),
6625 );
6626 window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
6627
6628 layout.sticky_headers = Some(sticky_headers);
6629 }
6630
6631 fn paint_lines_background(
6632 &mut self,
6633 layout: &mut EditorLayout,
6634 window: &mut Window,
6635 cx: &mut App,
6636 ) {
6637 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6638 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6639 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6640 }
6641 }
6642
6643 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6644 if layout.redacted_ranges.is_empty() {
6645 return;
6646 }
6647
6648 let line_end_overshoot = layout.line_end_overshoot();
6649
6650 // A softer than perfect black
6651 let redaction_color = gpui::rgb(0x0e1111);
6652
6653 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6654 for range in layout.redacted_ranges.iter() {
6655 self.paint_highlighted_range(
6656 range.clone(),
6657 true,
6658 redaction_color.into(),
6659 Pixels::ZERO,
6660 line_end_overshoot,
6661 layout,
6662 window,
6663 );
6664 }
6665 });
6666 }
6667
6668 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6669 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6670 return;
6671 };
6672 if image_colors.is_empty()
6673 || colors_render_mode == &DocumentColorsRenderMode::None
6674 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6675 {
6676 return;
6677 }
6678
6679 let line_end_overshoot = layout.line_end_overshoot();
6680
6681 for (range, color) in image_colors {
6682 match colors_render_mode {
6683 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6684 DocumentColorsRenderMode::Background => {
6685 self.paint_highlighted_range(
6686 range.clone(),
6687 true,
6688 *color,
6689 Pixels::ZERO,
6690 line_end_overshoot,
6691 layout,
6692 window,
6693 );
6694 }
6695 DocumentColorsRenderMode::Border => {
6696 self.paint_highlighted_range(
6697 range.clone(),
6698 false,
6699 *color,
6700 Pixels::ZERO,
6701 line_end_overshoot,
6702 layout,
6703 window,
6704 );
6705 }
6706 }
6707 }
6708 }
6709
6710 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6711 for cursor in &mut layout.visible_cursors {
6712 cursor.paint(layout.content_origin, window, cx);
6713 }
6714 }
6715
6716 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6717 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6718 return;
6719 };
6720 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6721
6722 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6723 let hitbox = &scrollbar_layout.hitbox;
6724 if scrollbars_layout.visible {
6725 let scrollbar_edges = match axis {
6726 ScrollbarAxis::Horizontal => Edges {
6727 top: Pixels::ZERO,
6728 right: Pixels::ZERO,
6729 bottom: Pixels::ZERO,
6730 left: Pixels::ZERO,
6731 },
6732 ScrollbarAxis::Vertical => Edges {
6733 top: Pixels::ZERO,
6734 right: Pixels::ZERO,
6735 bottom: Pixels::ZERO,
6736 left: ScrollbarLayout::BORDER_WIDTH,
6737 },
6738 };
6739
6740 window.paint_layer(hitbox.bounds, |window| {
6741 window.paint_quad(quad(
6742 hitbox.bounds,
6743 Corners::default(),
6744 cx.theme().colors().scrollbar_track_background,
6745 scrollbar_edges,
6746 cx.theme().colors().scrollbar_track_border,
6747 BorderStyle::Solid,
6748 ));
6749
6750 if axis == ScrollbarAxis::Vertical {
6751 let fast_markers =
6752 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6753 // Refresh slow scrollbar markers in the background. Below, we
6754 // paint whatever markers have already been computed.
6755 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6756
6757 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6758 for marker in markers.iter().chain(&fast_markers) {
6759 let mut marker = marker.clone();
6760 marker.bounds.origin += hitbox.origin;
6761 window.paint_quad(marker);
6762 }
6763 }
6764
6765 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6766 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6767 ScrollbarThumbState::Dragging => {
6768 cx.theme().colors().scrollbar_thumb_active_background
6769 }
6770 ScrollbarThumbState::Hovered => {
6771 cx.theme().colors().scrollbar_thumb_hover_background
6772 }
6773 ScrollbarThumbState::Idle => {
6774 cx.theme().colors().scrollbar_thumb_background
6775 }
6776 };
6777 window.paint_quad(quad(
6778 thumb_bounds,
6779 Corners::default(),
6780 scrollbar_thumb_color,
6781 scrollbar_edges,
6782 cx.theme().colors().scrollbar_thumb_border,
6783 BorderStyle::Solid,
6784 ));
6785
6786 if any_scrollbar_dragged {
6787 window.set_window_cursor_style(CursorStyle::Arrow);
6788 } else {
6789 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6790 }
6791 }
6792 })
6793 }
6794 }
6795
6796 window.on_mouse_event({
6797 let editor = self.editor.clone();
6798 let scrollbars_layout = scrollbars_layout.clone();
6799
6800 let mut mouse_position = window.mouse_position();
6801 move |event: &MouseMoveEvent, phase, window, cx| {
6802 if phase == DispatchPhase::Capture {
6803 return;
6804 }
6805
6806 editor.update(cx, |editor, cx| {
6807 if let Some((scrollbar_layout, axis)) = event
6808 .pressed_button
6809 .filter(|button| *button == MouseButton::Left)
6810 .and(editor.scroll_manager.dragging_scrollbar_axis())
6811 .and_then(|axis| {
6812 scrollbars_layout
6813 .iter_scrollbars()
6814 .find(|(_, a)| *a == axis)
6815 })
6816 {
6817 let ScrollbarLayout {
6818 hitbox,
6819 text_unit_size,
6820 ..
6821 } = scrollbar_layout;
6822
6823 let old_position = mouse_position.along(axis);
6824 let new_position = event.position.along(axis);
6825 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6826 .contains(&old_position)
6827 {
6828 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6829 (p + ScrollOffset::from(
6830 (new_position - old_position) / *text_unit_size,
6831 ))
6832 .max(0.)
6833 });
6834 editor.set_scroll_position(position, window, cx);
6835 }
6836
6837 editor.scroll_manager.show_scrollbars(window, cx);
6838 cx.stop_propagation();
6839 } else if let Some((layout, axis)) = scrollbars_layout
6840 .get_hovered_axis(window)
6841 .filter(|_| !event.dragging())
6842 {
6843 if layout.thumb_hovered(&event.position) {
6844 editor
6845 .scroll_manager
6846 .set_hovered_scroll_thumb_axis(axis, cx);
6847 } else {
6848 editor.scroll_manager.reset_scrollbar_state(cx);
6849 }
6850
6851 editor.scroll_manager.show_scrollbars(window, cx);
6852 } else {
6853 editor.scroll_manager.reset_scrollbar_state(cx);
6854 }
6855
6856 mouse_position = event.position;
6857 })
6858 }
6859 });
6860
6861 if any_scrollbar_dragged {
6862 window.on_mouse_event({
6863 let editor = self.editor.clone();
6864 move |_: &MouseUpEvent, phase, window, cx| {
6865 if phase == DispatchPhase::Capture {
6866 return;
6867 }
6868
6869 editor.update(cx, |editor, cx| {
6870 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6871 editor
6872 .scroll_manager
6873 .set_hovered_scroll_thumb_axis(axis, cx);
6874 } else {
6875 editor.scroll_manager.reset_scrollbar_state(cx);
6876 }
6877 cx.stop_propagation();
6878 });
6879 }
6880 });
6881 } else {
6882 window.on_mouse_event({
6883 let editor = self.editor.clone();
6884
6885 move |event: &MouseDownEvent, phase, window, cx| {
6886 if phase == DispatchPhase::Capture {
6887 return;
6888 }
6889 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6890 else {
6891 return;
6892 };
6893
6894 let ScrollbarLayout {
6895 hitbox,
6896 visible_range,
6897 text_unit_size,
6898 thumb_bounds,
6899 ..
6900 } = scrollbar_layout;
6901
6902 let Some(thumb_bounds) = thumb_bounds else {
6903 return;
6904 };
6905
6906 editor.update(cx, |editor, cx| {
6907 editor
6908 .scroll_manager
6909 .set_dragged_scroll_thumb_axis(axis, cx);
6910
6911 let event_position = event.position.along(axis);
6912
6913 if event_position < thumb_bounds.origin.along(axis)
6914 || thumb_bounds.bottom_right().along(axis) < event_position
6915 {
6916 let center_position = ((event_position - hitbox.origin.along(axis))
6917 / *text_unit_size)
6918 .round() as u32;
6919 let start_position = center_position.saturating_sub(
6920 (visible_range.end - visible_range.start) as u32 / 2,
6921 );
6922
6923 let position = editor
6924 .scroll_position(cx)
6925 .apply_along(axis, |_| start_position as ScrollOffset);
6926
6927 editor.set_scroll_position(position, window, cx);
6928 } else {
6929 editor.scroll_manager.show_scrollbars(window, cx);
6930 }
6931
6932 cx.stop_propagation();
6933 });
6934 }
6935 });
6936 }
6937 }
6938
6939 fn collect_fast_scrollbar_markers(
6940 &self,
6941 layout: &EditorLayout,
6942 scrollbar_layout: &ScrollbarLayout,
6943 cx: &mut App,
6944 ) -> Vec<PaintQuad> {
6945 const LIMIT: usize = 100;
6946 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6947 return vec![];
6948 }
6949 let cursor_ranges = layout
6950 .cursors
6951 .iter()
6952 .map(|(point, color)| ColoredRange {
6953 start: point.row(),
6954 end: point.row(),
6955 color: *color,
6956 })
6957 .collect_vec();
6958 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6959 }
6960
6961 fn refresh_slow_scrollbar_markers(
6962 &self,
6963 layout: &EditorLayout,
6964 scrollbar_layout: &ScrollbarLayout,
6965 window: &mut Window,
6966 cx: &mut App,
6967 ) {
6968 self.editor.update(cx, |editor, cx| {
6969 if editor.buffer_kind(cx) != ItemBufferKind::Singleton
6970 || !editor
6971 .scrollbar_marker_state
6972 .should_refresh(scrollbar_layout.hitbox.size)
6973 {
6974 return;
6975 }
6976
6977 let scrollbar_layout = scrollbar_layout.clone();
6978 let background_highlights = editor.background_highlights.clone();
6979 let snapshot = layout.position_map.snapshot.clone();
6980 let theme = cx.theme().clone();
6981 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6982
6983 editor.scrollbar_marker_state.dirty = false;
6984 editor.scrollbar_marker_state.pending_refresh =
6985 Some(cx.spawn_in(window, async move |editor, cx| {
6986 let scrollbar_size = scrollbar_layout.hitbox.size;
6987 let scrollbar_markers = cx
6988 .background_spawn(async move {
6989 let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
6990 let mut marker_quads = Vec::new();
6991 if scrollbar_settings.git_diff {
6992 let marker_row_ranges =
6993 snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
6994 let start_display_row =
6995 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6996 .to_display_point(&snapshot.display_snapshot)
6997 .row();
6998 let mut end_display_row =
6999 MultiBufferPoint::new(hunk.row_range.end.0, 0)
7000 .to_display_point(&snapshot.display_snapshot)
7001 .row();
7002 if end_display_row != start_display_row {
7003 end_display_row.0 -= 1;
7004 }
7005 let color = match &hunk.status().kind {
7006 DiffHunkStatusKind::Added => {
7007 theme.colors().version_control_added
7008 }
7009 DiffHunkStatusKind::Modified => {
7010 theme.colors().version_control_modified
7011 }
7012 DiffHunkStatusKind::Deleted => {
7013 theme.colors().version_control_deleted
7014 }
7015 };
7016 ColoredRange {
7017 start: start_display_row,
7018 end: end_display_row,
7019 color,
7020 }
7021 });
7022
7023 marker_quads.extend(
7024 scrollbar_layout
7025 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
7026 );
7027 }
7028
7029 for (background_highlight_id, (_, background_ranges)) in
7030 background_highlights.iter()
7031 {
7032 let is_search_highlights = *background_highlight_id
7033 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
7034 let is_text_highlights = *background_highlight_id
7035 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
7036 let is_symbol_occurrences = *background_highlight_id
7037 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
7038 || *background_highlight_id
7039 == HighlightKey::Type(
7040 TypeId::of::<DocumentHighlightWrite>(),
7041 );
7042 if (is_search_highlights && scrollbar_settings.search_results)
7043 || (is_text_highlights && scrollbar_settings.selected_text)
7044 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
7045 {
7046 let mut color = theme.status().info;
7047 if is_symbol_occurrences {
7048 color.fade_out(0.5);
7049 }
7050 let marker_row_ranges = background_ranges.iter().map(|range| {
7051 let display_start = range
7052 .start
7053 .to_display_point(&snapshot.display_snapshot);
7054 let display_end =
7055 range.end.to_display_point(&snapshot.display_snapshot);
7056 ColoredRange {
7057 start: display_start.row(),
7058 end: display_end.row(),
7059 color,
7060 }
7061 });
7062 marker_quads.extend(
7063 scrollbar_layout
7064 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
7065 );
7066 }
7067 }
7068
7069 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
7070 let diagnostics = snapshot
7071 .buffer_snapshot()
7072 .diagnostics_in_range::<Point>(Point::zero()..max_point)
7073 // Don't show diagnostics the user doesn't care about
7074 .filter(|diagnostic| {
7075 match (
7076 scrollbar_settings.diagnostics,
7077 diagnostic.diagnostic.severity,
7078 ) {
7079 (ScrollbarDiagnostics::All, _) => true,
7080 (
7081 ScrollbarDiagnostics::Error,
7082 lsp::DiagnosticSeverity::ERROR,
7083 ) => true,
7084 (
7085 ScrollbarDiagnostics::Warning,
7086 lsp::DiagnosticSeverity::ERROR
7087 | lsp::DiagnosticSeverity::WARNING,
7088 ) => true,
7089 (
7090 ScrollbarDiagnostics::Information,
7091 lsp::DiagnosticSeverity::ERROR
7092 | lsp::DiagnosticSeverity::WARNING
7093 | lsp::DiagnosticSeverity::INFORMATION,
7094 ) => true,
7095 (_, _) => false,
7096 }
7097 })
7098 // We want to sort by severity, in order to paint the most severe diagnostics last.
7099 .sorted_by_key(|diagnostic| {
7100 std::cmp::Reverse(diagnostic.diagnostic.severity)
7101 });
7102
7103 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
7104 let start_display = diagnostic
7105 .range
7106 .start
7107 .to_display_point(&snapshot.display_snapshot);
7108 let end_display = diagnostic
7109 .range
7110 .end
7111 .to_display_point(&snapshot.display_snapshot);
7112 let color = match diagnostic.diagnostic.severity {
7113 lsp::DiagnosticSeverity::ERROR => theme.status().error,
7114 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
7115 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
7116 _ => theme.status().hint,
7117 };
7118 ColoredRange {
7119 start: start_display.row(),
7120 end: end_display.row(),
7121 color,
7122 }
7123 });
7124 marker_quads.extend(
7125 scrollbar_layout
7126 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
7127 );
7128 }
7129
7130 Arc::from(marker_quads)
7131 })
7132 .await;
7133
7134 editor.update(cx, |editor, cx| {
7135 editor.scrollbar_marker_state.markers = scrollbar_markers;
7136 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
7137 editor.scrollbar_marker_state.pending_refresh = None;
7138 cx.notify();
7139 })?;
7140
7141 Ok(())
7142 }));
7143 });
7144 }
7145
7146 fn paint_highlighted_range(
7147 &self,
7148 range: Range<DisplayPoint>,
7149 fill: bool,
7150 color: Hsla,
7151 corner_radius: Pixels,
7152 line_end_overshoot: Pixels,
7153 layout: &EditorLayout,
7154 window: &mut Window,
7155 ) {
7156 let start_row = layout.visible_display_row_range.start;
7157 let end_row = layout.visible_display_row_range.end;
7158 if range.start != range.end {
7159 let row_range = if range.end.column() == 0 {
7160 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
7161 } else {
7162 cmp::max(range.start.row(), start_row)
7163 ..cmp::min(range.end.row().next_row(), end_row)
7164 };
7165
7166 let highlighted_range = HighlightedRange {
7167 color,
7168 line_height: layout.position_map.line_height,
7169 corner_radius,
7170 start_y: layout.content_origin.y
7171 + Pixels::from(
7172 (row_range.start.as_f64() - layout.position_map.scroll_position.y)
7173 * ScrollOffset::from(layout.position_map.line_height),
7174 ),
7175 lines: row_range
7176 .iter_rows()
7177 .map(|row| {
7178 let line_layout =
7179 &layout.position_map.line_layouts[row.minus(start_row) as usize];
7180 HighlightedRangeLine {
7181 start_x: if row == range.start.row() {
7182 layout.content_origin.x
7183 + Pixels::from(
7184 ScrollPixelOffset::from(
7185 line_layout.x_for_index(range.start.column() as usize),
7186 ) - layout.position_map.scroll_pixel_position.x,
7187 )
7188 } else {
7189 layout.content_origin.x
7190 - Pixels::from(layout.position_map.scroll_pixel_position.x)
7191 },
7192 end_x: if row == range.end.row() {
7193 layout.content_origin.x
7194 + Pixels::from(
7195 ScrollPixelOffset::from(
7196 line_layout.x_for_index(range.end.column() as usize),
7197 ) - layout.position_map.scroll_pixel_position.x,
7198 )
7199 } else {
7200 Pixels::from(
7201 ScrollPixelOffset::from(
7202 layout.content_origin.x
7203 + line_layout.width
7204 + line_end_overshoot,
7205 ) - layout.position_map.scroll_pixel_position.x,
7206 )
7207 },
7208 }
7209 })
7210 .collect(),
7211 };
7212
7213 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
7214 }
7215 }
7216
7217 fn paint_inline_diagnostics(
7218 &mut self,
7219 layout: &mut EditorLayout,
7220 window: &mut Window,
7221 cx: &mut App,
7222 ) {
7223 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
7224 inline_diagnostic.1.paint(window, cx);
7225 }
7226 }
7227
7228 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7229 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
7230 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
7231 blame_layout.element.paint(window, cx);
7232 })
7233 }
7234 }
7235
7236 fn paint_inline_code_actions(
7237 &mut self,
7238 layout: &mut EditorLayout,
7239 window: &mut Window,
7240 cx: &mut App,
7241 ) {
7242 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
7243 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
7244 inline_code_actions.paint(window, cx);
7245 })
7246 }
7247 }
7248
7249 fn paint_diff_hunk_controls(
7250 &mut self,
7251 layout: &mut EditorLayout,
7252 window: &mut Window,
7253 cx: &mut App,
7254 ) {
7255 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
7256 diff_hunk_control.paint(window, cx);
7257 }
7258 }
7259
7260 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7261 if let Some(mut layout) = layout.minimap.take() {
7262 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
7263 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
7264
7265 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
7266 window.with_element_namespace("minimap", |window| {
7267 layout.minimap.paint(window, cx);
7268 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
7269 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
7270 ScrollbarThumbState::Idle => {
7271 cx.theme().colors().minimap_thumb_background
7272 }
7273 ScrollbarThumbState::Hovered => {
7274 cx.theme().colors().minimap_thumb_hover_background
7275 }
7276 ScrollbarThumbState::Dragging => {
7277 cx.theme().colors().minimap_thumb_active_background
7278 }
7279 };
7280 let minimap_thumb_border = match layout.thumb_border_style {
7281 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
7282 MinimapThumbBorder::LeftOnly => Edges {
7283 left: ScrollbarLayout::BORDER_WIDTH,
7284 ..Default::default()
7285 },
7286 MinimapThumbBorder::LeftOpen => Edges {
7287 right: ScrollbarLayout::BORDER_WIDTH,
7288 top: ScrollbarLayout::BORDER_WIDTH,
7289 bottom: ScrollbarLayout::BORDER_WIDTH,
7290 ..Default::default()
7291 },
7292 MinimapThumbBorder::RightOpen => Edges {
7293 left: ScrollbarLayout::BORDER_WIDTH,
7294 top: ScrollbarLayout::BORDER_WIDTH,
7295 bottom: ScrollbarLayout::BORDER_WIDTH,
7296 ..Default::default()
7297 },
7298 MinimapThumbBorder::None => Default::default(),
7299 };
7300
7301 window.paint_layer(minimap_hitbox.bounds, |window| {
7302 window.paint_quad(quad(
7303 thumb_bounds,
7304 Corners::default(),
7305 minimap_thumb_color,
7306 minimap_thumb_border,
7307 cx.theme().colors().minimap_thumb_border,
7308 BorderStyle::Solid,
7309 ));
7310 });
7311 }
7312 });
7313 });
7314
7315 if dragging_minimap {
7316 window.set_window_cursor_style(CursorStyle::Arrow);
7317 } else {
7318 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
7319 }
7320
7321 let minimap_axis = ScrollbarAxis::Vertical;
7322 let pixels_per_line = Pixels::from(
7323 ScrollPixelOffset::from(minimap_hitbox.size.height) / layout.max_scroll_top,
7324 )
7325 .min(layout.minimap_line_height);
7326
7327 let mut mouse_position = window.mouse_position();
7328
7329 window.on_mouse_event({
7330 let editor = self.editor.clone();
7331
7332 let minimap_hitbox = minimap_hitbox.clone();
7333
7334 move |event: &MouseMoveEvent, phase, window, cx| {
7335 if phase == DispatchPhase::Capture {
7336 return;
7337 }
7338
7339 editor.update(cx, |editor, cx| {
7340 if event.pressed_button == Some(MouseButton::Left)
7341 && editor.scroll_manager.is_dragging_minimap()
7342 {
7343 let old_position = mouse_position.along(minimap_axis);
7344 let new_position = event.position.along(minimap_axis);
7345 if (minimap_hitbox.origin.along(minimap_axis)
7346 ..minimap_hitbox.bottom_right().along(minimap_axis))
7347 .contains(&old_position)
7348 {
7349 let position =
7350 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
7351 (p + ScrollPixelOffset::from(
7352 (new_position - old_position) / pixels_per_line,
7353 ))
7354 .max(0.)
7355 });
7356
7357 editor.set_scroll_position(position, window, cx);
7358 }
7359 cx.stop_propagation();
7360 } else if minimap_hitbox.is_hovered(window) {
7361 editor.scroll_manager.set_is_hovering_minimap_thumb(
7362 !event.dragging()
7363 && layout
7364 .thumb_layout
7365 .thumb_bounds
7366 .is_some_and(|bounds| bounds.contains(&event.position)),
7367 cx,
7368 );
7369
7370 // Stop hover events from propagating to the
7371 // underlying editor if the minimap hitbox is hovered
7372 if !event.dragging() {
7373 cx.stop_propagation();
7374 }
7375 } else {
7376 editor.scroll_manager.hide_minimap_thumb(cx);
7377 }
7378 mouse_position = event.position;
7379 });
7380 }
7381 });
7382
7383 if dragging_minimap {
7384 window.on_mouse_event({
7385 let editor = self.editor.clone();
7386 move |event: &MouseUpEvent, phase, window, cx| {
7387 if phase == DispatchPhase::Capture {
7388 return;
7389 }
7390
7391 editor.update(cx, |editor, cx| {
7392 if minimap_hitbox.is_hovered(window) {
7393 editor.scroll_manager.set_is_hovering_minimap_thumb(
7394 layout
7395 .thumb_layout
7396 .thumb_bounds
7397 .is_some_and(|bounds| bounds.contains(&event.position)),
7398 cx,
7399 );
7400 } else {
7401 editor.scroll_manager.hide_minimap_thumb(cx);
7402 }
7403 cx.stop_propagation();
7404 });
7405 }
7406 });
7407 } else {
7408 window.on_mouse_event({
7409 let editor = self.editor.clone();
7410
7411 move |event: &MouseDownEvent, phase, window, cx| {
7412 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
7413 return;
7414 }
7415
7416 let event_position = event.position;
7417
7418 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
7419 return;
7420 };
7421
7422 editor.update(cx, |editor, cx| {
7423 if !thumb_bounds.contains(&event_position) {
7424 let click_position =
7425 event_position.relative_to(&minimap_hitbox.origin).y;
7426
7427 let top_position = (click_position
7428 - thumb_bounds.size.along(minimap_axis) / 2.0)
7429 .max(Pixels::ZERO);
7430
7431 let scroll_offset = (layout.minimap_scroll_top
7432 + ScrollPixelOffset::from(
7433 top_position / layout.minimap_line_height,
7434 ))
7435 .min(layout.max_scroll_top);
7436
7437 let scroll_position = editor
7438 .scroll_position(cx)
7439 .apply_along(minimap_axis, |_| scroll_offset);
7440 editor.set_scroll_position(scroll_position, window, cx);
7441 }
7442
7443 editor.scroll_manager.set_is_dragging_minimap(cx);
7444 cx.stop_propagation();
7445 });
7446 }
7447 });
7448 }
7449 }
7450 }
7451
7452 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7453 for mut block in layout.blocks.drain(..) {
7454 if block.overlaps_gutter {
7455 block.element.paint(window, cx);
7456 } else {
7457 let mut bounds = layout.hitbox.bounds;
7458 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
7459 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7460 block.element.paint(window, cx);
7461 })
7462 }
7463 }
7464 }
7465
7466 fn paint_edit_prediction_popover(
7467 &mut self,
7468 layout: &mut EditorLayout,
7469 window: &mut Window,
7470 cx: &mut App,
7471 ) {
7472 if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
7473 edit_prediction_popover.paint(window, cx);
7474 }
7475 }
7476
7477 fn paint_mouse_context_menu(
7478 &mut self,
7479 layout: &mut EditorLayout,
7480 window: &mut Window,
7481 cx: &mut App,
7482 ) {
7483 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
7484 mouse_context_menu.paint(window, cx);
7485 }
7486 }
7487
7488 fn paint_scroll_wheel_listener(
7489 &mut self,
7490 layout: &EditorLayout,
7491 window: &mut Window,
7492 cx: &mut App,
7493 ) {
7494 window.on_mouse_event({
7495 let position_map = layout.position_map.clone();
7496 let editor = self.editor.clone();
7497 let hitbox = layout.hitbox.clone();
7498 let mut delta = ScrollDelta::default();
7499
7500 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
7501 // accidentally turn off their scrolling.
7502 let base_scroll_sensitivity =
7503 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
7504
7505 // Use a minimum fast_scroll_sensitivity for same reason above
7506 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
7507 .fast_scroll_sensitivity
7508 .max(0.01);
7509
7510 move |event: &ScrollWheelEvent, phase, window, cx| {
7511 let scroll_sensitivity = {
7512 if event.modifiers.alt {
7513 fast_scroll_sensitivity
7514 } else {
7515 base_scroll_sensitivity
7516 }
7517 };
7518
7519 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
7520 delta = delta.coalesce(event.delta);
7521 editor.update(cx, |editor, cx| {
7522 let position_map: &PositionMap = &position_map;
7523
7524 let line_height = position_map.line_height;
7525 let max_glyph_advance = position_map.em_advance;
7526 let (delta, axis) = match delta {
7527 gpui::ScrollDelta::Pixels(mut pixels) => {
7528 //Trackpad
7529 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7530 (pixels, axis)
7531 }
7532
7533 gpui::ScrollDelta::Lines(lines) => {
7534 //Not trackpad
7535 let pixels =
7536 point(lines.x * max_glyph_advance, lines.y * line_height);
7537 (pixels, None)
7538 }
7539 };
7540
7541 let current_scroll_position = position_map.snapshot.scroll_position();
7542 let x = (current_scroll_position.x
7543 * ScrollPixelOffset::from(max_glyph_advance)
7544 - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
7545 / ScrollPixelOffset::from(max_glyph_advance);
7546 let y = (current_scroll_position.y * ScrollPixelOffset::from(line_height)
7547 - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
7548 / ScrollPixelOffset::from(line_height);
7549 let mut scroll_position =
7550 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7551 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
7552 if forbid_vertical_scroll {
7553 scroll_position.y = current_scroll_position.y;
7554 }
7555
7556 if scroll_position != current_scroll_position {
7557 editor.scroll(scroll_position, axis, window, cx);
7558 cx.stop_propagation();
7559 } else if y < 0. {
7560 // Due to clamping, we may fail to detect cases of overscroll to the top;
7561 // We want the scroll manager to get an update in such cases and detect the change of direction
7562 // on the next frame.
7563 cx.notify();
7564 }
7565 });
7566 }
7567 }
7568 });
7569 }
7570
7571 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7572 if layout.mode.is_minimap() {
7573 return;
7574 }
7575
7576 self.paint_scroll_wheel_listener(layout, window, cx);
7577
7578 window.on_mouse_event({
7579 let position_map = layout.position_map.clone();
7580 let editor = self.editor.clone();
7581 let line_numbers = layout.line_numbers.clone();
7582
7583 move |event: &MouseDownEvent, phase, window, cx| {
7584 if phase == DispatchPhase::Bubble {
7585 match event.button {
7586 MouseButton::Left => editor.update(cx, |editor, cx| {
7587 let pending_mouse_down = editor
7588 .pending_mouse_down
7589 .get_or_insert_with(Default::default)
7590 .clone();
7591
7592 *pending_mouse_down.borrow_mut() = Some(event.clone());
7593
7594 Self::mouse_left_down(
7595 editor,
7596 event,
7597 &position_map,
7598 line_numbers.as_ref(),
7599 window,
7600 cx,
7601 );
7602 }),
7603 MouseButton::Right => editor.update(cx, |editor, cx| {
7604 Self::mouse_right_down(editor, event, &position_map, window, cx);
7605 }),
7606 MouseButton::Middle => editor.update(cx, |editor, cx| {
7607 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7608 }),
7609 _ => {}
7610 };
7611 }
7612 }
7613 });
7614
7615 window.on_mouse_event({
7616 let editor = self.editor.clone();
7617 let position_map = layout.position_map.clone();
7618
7619 move |event: &MouseUpEvent, phase, window, cx| {
7620 if phase == DispatchPhase::Bubble {
7621 editor.update(cx, |editor, cx| {
7622 Self::mouse_up(editor, event, &position_map, window, cx)
7623 });
7624 }
7625 }
7626 });
7627
7628 window.on_mouse_event({
7629 let editor = self.editor.clone();
7630 let position_map = layout.position_map.clone();
7631 let mut captured_mouse_down = None;
7632
7633 move |event: &MouseUpEvent, phase, window, cx| match phase {
7634 // Clear the pending mouse down during the capture phase,
7635 // so that it happens even if another event handler stops
7636 // propagation.
7637 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7638 let pending_mouse_down = editor
7639 .pending_mouse_down
7640 .get_or_insert_with(Default::default)
7641 .clone();
7642
7643 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7644 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7645 captured_mouse_down = pending_mouse_down.take();
7646 window.refresh();
7647 }
7648 }),
7649 // Fire click handlers during the bubble phase.
7650 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7651 if let Some(mouse_down) = captured_mouse_down.take() {
7652 let event = ClickEvent::Mouse(MouseClickEvent {
7653 down: mouse_down,
7654 up: event.clone(),
7655 });
7656 Self::click(editor, &event, &position_map, window, cx);
7657 }
7658 }),
7659 }
7660 });
7661
7662 window.on_mouse_event({
7663 let position_map = layout.position_map.clone();
7664 let editor = self.editor.clone();
7665
7666 move |event: &MouseMoveEvent, phase, window, cx| {
7667 if phase == DispatchPhase::Bubble {
7668 editor.update(cx, |editor, cx| {
7669 if editor.hover_state.focused(window, cx) {
7670 return;
7671 }
7672 if event.pressed_button == Some(MouseButton::Left)
7673 || event.pressed_button == Some(MouseButton::Middle)
7674 {
7675 Self::mouse_dragged(editor, event, &position_map, window, cx)
7676 }
7677
7678 Self::mouse_moved(editor, event, &position_map, window, cx)
7679 });
7680 }
7681 }
7682 });
7683 }
7684
7685 fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
7686 let style = &self.style;
7687 let font_size = style.text.font_size.to_pixels(window.rem_size());
7688 let layout = window.text_system().shape_line(
7689 SharedString::from(" ".repeat(column)),
7690 font_size,
7691 &[TextRun {
7692 len: column,
7693 font: style.text.font(),
7694 color: Hsla::default(),
7695 ..Default::default()
7696 }],
7697 None,
7698 );
7699
7700 layout.width
7701 }
7702
7703 fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
7704 let digit_count = snapshot.widest_line_number().ilog10() + 1;
7705 self.column_pixels(digit_count as usize, window)
7706 }
7707
7708 fn shape_line_number(
7709 &self,
7710 text: SharedString,
7711 color: Hsla,
7712 window: &mut Window,
7713 ) -> ShapedLine {
7714 let run = TextRun {
7715 len: text.len(),
7716 font: self.style.text.font(),
7717 color,
7718 ..Default::default()
7719 };
7720 window.text_system().shape_line(
7721 text,
7722 self.style.text.font_size.to_pixels(window.rem_size()),
7723 &[run],
7724 None,
7725 )
7726 }
7727
7728 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7729 let unstaged = status.has_secondary_hunk();
7730 let unstaged_hollow = matches!(
7731 ProjectSettings::get_global(cx).git.hunk_style,
7732 GitHunkStyleSetting::UnstagedHollow
7733 );
7734
7735 unstaged == unstaged_hollow
7736 }
7737
7738 #[cfg(debug_assertions)]
7739 fn layout_debug_ranges(
7740 selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
7741 anchor_range: Range<Anchor>,
7742 display_snapshot: &DisplaySnapshot,
7743 cx: &App,
7744 ) {
7745 let theme = cx.theme();
7746 text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
7747 if debug_ranges.ranges.is_empty() {
7748 return;
7749 }
7750 let buffer_snapshot = &display_snapshot.buffer_snapshot();
7751 for (buffer, buffer_range, excerpt_id) in
7752 buffer_snapshot.range_to_buffer_ranges(anchor_range)
7753 {
7754 let buffer_range =
7755 buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
7756 selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
7757 let player_color = theme
7758 .players()
7759 .color_for_participant(debug_range.occurrence_index as u32 + 1);
7760 debug_range.ranges.iter().filter_map(move |range| {
7761 if range.start.buffer_id != Some(buffer.remote_id()) {
7762 return None;
7763 }
7764 let clipped_start = range.start.max(&buffer_range.start, buffer);
7765 let clipped_end = range.end.min(&buffer_range.end, buffer);
7766 let range = buffer_snapshot
7767 .anchor_range_in_excerpt(excerpt_id, *clipped_start..*clipped_end)?;
7768 let start = range.start.to_display_point(display_snapshot);
7769 let end = range.end.to_display_point(display_snapshot);
7770 let selection_layout = SelectionLayout {
7771 head: start,
7772 range: start..end,
7773 cursor_shape: CursorShape::Bar,
7774 is_newest: false,
7775 is_local: false,
7776 active_rows: start.row()..end.row(),
7777 user_name: Some(SharedString::new(debug_range.value.clone())),
7778 };
7779 Some((player_color, vec![selection_layout]))
7780 })
7781 }));
7782 }
7783 });
7784 }
7785}
7786
7787fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
7788 file_status.map_or(Color::Default, |status| {
7789 if status.is_conflicted() {
7790 Color::Conflict
7791 } else if status.is_modified() {
7792 Color::Modified
7793 } else if status.is_deleted() {
7794 Color::Disabled
7795 } else if status.is_created() {
7796 Color::Created
7797 } else {
7798 Color::Default
7799 }
7800 })
7801}
7802
7803fn header_jump_data(
7804 snapshot: &EditorSnapshot,
7805 block_row_start: DisplayRow,
7806 height: u32,
7807 for_excerpt: &ExcerptInfo,
7808 selection_anchors: &[Selection<Anchor>],
7809) -> JumpData {
7810 if let Some(cursor_anchor) = latest_anchor_for_buffer(selection_anchors, for_excerpt.buffer_id)
7811 {
7812 let buffer_point =
7813 language::ToPoint::to_point(&cursor_anchor.text_anchor, &for_excerpt.buffer);
7814 let multibuffer_point = snapshot
7815 .buffer_snapshot()
7816 .summary_for_anchor::<Point>(&cursor_anchor);
7817 let display_row = snapshot
7818 .display_snapshot
7819 .point_to_display_point(multibuffer_point, Bias::Left)
7820 .row()
7821 .0;
7822 let scroll_row = snapshot
7823 .scroll_anchor
7824 .scroll_position(&snapshot.display_snapshot)
7825 .y as u32;
7826 let line_offset_from_top = display_row.saturating_sub(scroll_row);
7827
7828 return JumpData::MultiBufferPoint {
7829 excerpt_id: cursor_anchor.excerpt_id,
7830 anchor: cursor_anchor.text_anchor,
7831 position: buffer_point,
7832 line_offset_from_top,
7833 };
7834 }
7835
7836 let range = &for_excerpt.range;
7837 let buffer = &for_excerpt.buffer;
7838 let jump_anchor = range.primary.start;
7839
7840 let excerpt_start = range.context.start;
7841 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
7842 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
7843 0
7844 } else {
7845 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
7846 jump_position.row.saturating_sub(excerpt_start_point.row)
7847 };
7848
7849 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
7850 .saturating_sub(
7851 snapshot
7852 .scroll_anchor
7853 .scroll_position(&snapshot.display_snapshot)
7854 .y as u32,
7855 );
7856
7857 JumpData::MultiBufferPoint {
7858 excerpt_id: for_excerpt.id,
7859 anchor: jump_anchor,
7860 position: jump_position,
7861 line_offset_from_top,
7862 }
7863}
7864
7865fn latest_anchor_for_buffer(
7866 selection_anchors: &[Selection<Anchor>],
7867 buffer_id: BufferId,
7868) -> Option<Anchor> {
7869 selection_anchors
7870 .iter()
7871 .filter_map(|selection| {
7872 let head = selection.head();
7873 (head.buffer_id == Some(buffer_id)).then_some((selection.id, head))
7874 })
7875 .max_by_key(|(id, _)| *id)
7876 .map(|(_, anchor)| anchor)
7877}
7878
7879pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
7880
7881impl AcceptEditPredictionBinding {
7882 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
7883 if let Some(binding) = self.0.as_ref() {
7884 match &binding.keystrokes() {
7885 [keystroke, ..] => Some(keystroke),
7886 _ => None,
7887 }
7888 } else {
7889 None
7890 }
7891 }
7892}
7893
7894fn prepaint_gutter_button(
7895 button: IconButton,
7896 row: DisplayRow,
7897 line_height: Pixels,
7898 gutter_dimensions: &GutterDimensions,
7899 scroll_position: gpui::Point<ScrollOffset>,
7900 gutter_hitbox: &Hitbox,
7901 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
7902 window: &mut Window,
7903 cx: &mut App,
7904) -> AnyElement {
7905 let mut button = button.into_any_element();
7906
7907 let available_space = size(
7908 AvailableSpace::MinContent,
7909 AvailableSpace::Definite(line_height),
7910 );
7911 let indicator_size = button.layout_as_root(available_space, window, cx);
7912
7913 let blame_width = gutter_dimensions.git_blame_entries_width;
7914 let gutter_width = display_hunks
7915 .binary_search_by(|(hunk, _)| match hunk {
7916 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
7917 DisplayDiffHunk::Unfolded {
7918 display_row_range, ..
7919 } => {
7920 if display_row_range.end <= row {
7921 Ordering::Less
7922 } else if display_row_range.start > row {
7923 Ordering::Greater
7924 } else {
7925 Ordering::Equal
7926 }
7927 }
7928 })
7929 .ok()
7930 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
7931 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
7932
7933 let mut x = left_offset;
7934 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
7935 - indicator_size.width
7936 - left_offset;
7937 x += available_width / 2.;
7938
7939 let mut y =
7940 Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
7941 y += (line_height - indicator_size.height) / 2.;
7942
7943 button.prepaint_as_root(
7944 gutter_hitbox.origin + point(x, y),
7945 available_space,
7946 window,
7947 cx,
7948 );
7949 button
7950}
7951
7952fn render_inline_blame_entry(
7953 blame_entry: BlameEntry,
7954 style: &EditorStyle,
7955 cx: &mut App,
7956) -> Option<AnyElement> {
7957 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7958 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
7959}
7960
7961fn render_blame_entry_popover(
7962 blame_entry: BlameEntry,
7963 scroll_handle: ScrollHandle,
7964 commit_message: Option<ParsedCommitMessage>,
7965 markdown: Entity<Markdown>,
7966 workspace: WeakEntity<Workspace>,
7967 blame: &Entity<GitBlame>,
7968 buffer: BufferId,
7969 window: &mut Window,
7970 cx: &mut App,
7971) -> Option<AnyElement> {
7972 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7973 let blame = blame.read(cx);
7974 let repository = blame.repository(cx, buffer)?;
7975 renderer.render_blame_entry_popover(
7976 blame_entry,
7977 scroll_handle,
7978 commit_message,
7979 markdown,
7980 repository,
7981 workspace,
7982 window,
7983 cx,
7984 )
7985}
7986
7987fn render_blame_entry(
7988 ix: usize,
7989 blame: &Entity<GitBlame>,
7990 blame_entry: BlameEntry,
7991 style: &EditorStyle,
7992 last_used_color: &mut Option<(Hsla, Oid)>,
7993 editor: Entity<Editor>,
7994 workspace: Entity<Workspace>,
7995 buffer: BufferId,
7996 renderer: &dyn BlameRenderer,
7997 window: &mut Window,
7998 cx: &mut App,
7999) -> Option<AnyElement> {
8000 let index: u32 = blame_entry.sha.into();
8001 let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
8002
8003 // If the last color we used is the same as the one we get for this line, but
8004 // the commit SHAs are different, then we try again to get a different color.
8005 if let Some((color, sha)) = *last_used_color
8006 && sha != blame_entry.sha
8007 && color == sha_color
8008 {
8009 sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
8010 }
8011 last_used_color.replace((sha_color, blame_entry.sha));
8012
8013 let blame = blame.read(cx);
8014 let details = blame.details_for_entry(buffer, &blame_entry);
8015 let repository = blame.repository(cx, buffer)?;
8016 renderer.render_blame_entry(
8017 &style.text,
8018 blame_entry,
8019 details,
8020 repository,
8021 workspace.downgrade(),
8022 editor,
8023 ix,
8024 sha_color,
8025 window,
8026 cx,
8027 )
8028}
8029
8030#[derive(Debug)]
8031pub(crate) struct LineWithInvisibles {
8032 fragments: SmallVec<[LineFragment; 1]>,
8033 invisibles: Vec<Invisible>,
8034 len: usize,
8035 pub(crate) width: Pixels,
8036 font_size: Pixels,
8037}
8038
8039enum LineFragment {
8040 Text(ShapedLine),
8041 Element {
8042 id: ChunkRendererId,
8043 element: Option<AnyElement>,
8044 size: Size<Pixels>,
8045 len: usize,
8046 },
8047}
8048
8049impl fmt::Debug for LineFragment {
8050 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8051 match self {
8052 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
8053 LineFragment::Element { size, len, .. } => f
8054 .debug_struct("Element")
8055 .field("size", size)
8056 .field("len", len)
8057 .finish(),
8058 }
8059 }
8060}
8061
8062impl LineWithInvisibles {
8063 fn from_chunks<'a>(
8064 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
8065 editor_style: &EditorStyle,
8066 max_line_len: usize,
8067 max_line_count: usize,
8068 editor_mode: &EditorMode,
8069 text_width: Pixels,
8070 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8071 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
8072 window: &mut Window,
8073 cx: &mut App,
8074 ) -> Vec<Self> {
8075 let text_style = &editor_style.text;
8076 let mut layouts = Vec::with_capacity(max_line_count);
8077 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
8078 let mut line = String::new();
8079 let mut invisibles = Vec::new();
8080 let mut width = Pixels::ZERO;
8081 let mut len = 0;
8082 let mut styles = Vec::new();
8083 let mut non_whitespace_added = false;
8084 let mut row = 0;
8085 let mut line_exceeded_max_len = false;
8086 let font_size = text_style.font_size.to_pixels(window.rem_size());
8087 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
8088
8089 let ellipsis = SharedString::from("β―");
8090
8091 for highlighted_chunk in chunks.chain([HighlightedChunk {
8092 text: "\n",
8093 style: None,
8094 is_tab: false,
8095 is_inlay: false,
8096 replacement: None,
8097 }]) {
8098 if let Some(replacement) = highlighted_chunk.replacement {
8099 if !line.is_empty() {
8100 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8101 let text_runs: &[TextRun] = if segments.is_empty() {
8102 &styles
8103 } else {
8104 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8105 };
8106 let shaped_line = window.text_system().shape_line(
8107 line.clone().into(),
8108 font_size,
8109 text_runs,
8110 None,
8111 );
8112 width += shaped_line.width;
8113 len += shaped_line.len;
8114 fragments.push(LineFragment::Text(shaped_line));
8115 line.clear();
8116 styles.clear();
8117 }
8118
8119 match replacement {
8120 ChunkReplacement::Renderer(renderer) => {
8121 let available_width = if renderer.constrain_width {
8122 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
8123 ellipsis.clone()
8124 } else {
8125 SharedString::from(Arc::from(highlighted_chunk.text))
8126 };
8127 let shaped_line = window.text_system().shape_line(
8128 chunk,
8129 font_size,
8130 &[text_style.to_run(highlighted_chunk.text.len())],
8131 None,
8132 );
8133 AvailableSpace::Definite(shaped_line.width)
8134 } else {
8135 AvailableSpace::MinContent
8136 };
8137
8138 let mut element = (renderer.render)(&mut ChunkRendererContext {
8139 context: cx,
8140 window,
8141 max_width: text_width,
8142 });
8143 let line_height = text_style.line_height_in_pixels(window.rem_size());
8144 let size = element.layout_as_root(
8145 size(available_width, AvailableSpace::Definite(line_height)),
8146 window,
8147 cx,
8148 );
8149
8150 width += size.width;
8151 len += highlighted_chunk.text.len();
8152 fragments.push(LineFragment::Element {
8153 id: renderer.id,
8154 element: Some(element),
8155 size,
8156 len: highlighted_chunk.text.len(),
8157 });
8158 }
8159 ChunkReplacement::Str(x) => {
8160 let text_style = if let Some(style) = highlighted_chunk.style {
8161 Cow::Owned(text_style.clone().highlight(style))
8162 } else {
8163 Cow::Borrowed(text_style)
8164 };
8165
8166 let run = TextRun {
8167 len: x.len(),
8168 font: text_style.font(),
8169 color: text_style.color,
8170 background_color: text_style.background_color,
8171 underline: text_style.underline,
8172 strikethrough: text_style.strikethrough,
8173 };
8174 let line_layout = window
8175 .text_system()
8176 .shape_line(x, font_size, &[run], None)
8177 .with_len(highlighted_chunk.text.len());
8178
8179 width += line_layout.width;
8180 len += highlighted_chunk.text.len();
8181 fragments.push(LineFragment::Text(line_layout))
8182 }
8183 }
8184 } else {
8185 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
8186 if ix > 0 {
8187 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8188 let text_runs = if segments.is_empty() {
8189 &styles
8190 } else {
8191 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8192 };
8193 let shaped_line = window.text_system().shape_line(
8194 line.clone().into(),
8195 font_size,
8196 text_runs,
8197 None,
8198 );
8199 width += shaped_line.width;
8200 len += shaped_line.len;
8201 fragments.push(LineFragment::Text(shaped_line));
8202 layouts.push(Self {
8203 width: mem::take(&mut width),
8204 len: mem::take(&mut len),
8205 fragments: mem::take(&mut fragments),
8206 invisibles: std::mem::take(&mut invisibles),
8207 font_size,
8208 });
8209
8210 line.clear();
8211 styles.clear();
8212 row += 1;
8213 line_exceeded_max_len = false;
8214 non_whitespace_added = false;
8215 if row == max_line_count {
8216 return layouts;
8217 }
8218 }
8219
8220 if !line_chunk.is_empty() && !line_exceeded_max_len {
8221 let text_style = if let Some(style) = highlighted_chunk.style {
8222 Cow::Owned(text_style.clone().highlight(style))
8223 } else {
8224 Cow::Borrowed(text_style)
8225 };
8226
8227 if line.len() + line_chunk.len() > max_line_len {
8228 let mut chunk_len = max_line_len - line.len();
8229 while !line_chunk.is_char_boundary(chunk_len) {
8230 chunk_len -= 1;
8231 }
8232 line_chunk = &line_chunk[..chunk_len];
8233 line_exceeded_max_len = true;
8234 }
8235
8236 styles.push(TextRun {
8237 len: line_chunk.len(),
8238 font: text_style.font(),
8239 color: text_style.color,
8240 background_color: text_style.background_color,
8241 underline: text_style.underline,
8242 strikethrough: text_style.strikethrough,
8243 });
8244
8245 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
8246 // Line wrap pads its contents with fake whitespaces,
8247 // avoid printing them
8248 let is_soft_wrapped = is_row_soft_wrapped(row);
8249 if highlighted_chunk.is_tab {
8250 if non_whitespace_added || !is_soft_wrapped {
8251 invisibles.push(Invisible::Tab {
8252 line_start_offset: line.len(),
8253 line_end_offset: line.len() + line_chunk.len(),
8254 });
8255 }
8256 } else {
8257 invisibles.extend(line_chunk.char_indices().filter_map(
8258 |(index, c)| {
8259 let is_whitespace = c.is_whitespace();
8260 non_whitespace_added |= !is_whitespace;
8261 if is_whitespace
8262 && (non_whitespace_added || !is_soft_wrapped)
8263 {
8264 Some(Invisible::Whitespace {
8265 line_offset: line.len() + index,
8266 })
8267 } else {
8268 None
8269 }
8270 },
8271 ))
8272 }
8273 }
8274
8275 line.push_str(line_chunk);
8276 }
8277 }
8278 }
8279 }
8280
8281 layouts
8282 }
8283
8284 /// Takes text runs and non-overlapping left-to-right background ranges with color.
8285 /// Returns new text runs with adjusted contrast as per background ranges.
8286 fn split_runs_by_bg_segments(
8287 text_runs: &[TextRun],
8288 bg_segments: &[(Range<DisplayPoint>, Hsla)],
8289 min_contrast: f32,
8290 start_col_offset: usize,
8291 ) -> Vec<TextRun> {
8292 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
8293 let mut line_col = start_col_offset;
8294 let mut segment_ix = 0usize;
8295
8296 for text_run in text_runs.iter() {
8297 let run_start_col = line_col;
8298 let run_end_col = run_start_col + text_run.len;
8299 while segment_ix < bg_segments.len()
8300 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
8301 {
8302 segment_ix += 1;
8303 }
8304 let mut cursor_col = run_start_col;
8305 let mut local_segment_ix = segment_ix;
8306 while local_segment_ix < bg_segments.len() {
8307 let (range, segment_color) = &bg_segments[local_segment_ix];
8308 let segment_start_col = range.start.column() as usize;
8309 let segment_end_col = range.end.column() as usize;
8310 if segment_start_col >= run_end_col {
8311 break;
8312 }
8313 if segment_start_col > cursor_col {
8314 let span_len = segment_start_col - cursor_col;
8315 output_runs.push(TextRun {
8316 len: span_len,
8317 font: text_run.font.clone(),
8318 color: text_run.color,
8319 background_color: text_run.background_color,
8320 underline: text_run.underline,
8321 strikethrough: text_run.strikethrough,
8322 });
8323 cursor_col = segment_start_col;
8324 }
8325 let segment_slice_end_col = segment_end_col.min(run_end_col);
8326 if segment_slice_end_col > cursor_col {
8327 let new_text_color =
8328 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
8329 output_runs.push(TextRun {
8330 len: segment_slice_end_col - cursor_col,
8331 font: text_run.font.clone(),
8332 color: new_text_color,
8333 background_color: text_run.background_color,
8334 underline: text_run.underline,
8335 strikethrough: text_run.strikethrough,
8336 });
8337 cursor_col = segment_slice_end_col;
8338 }
8339 if segment_end_col >= run_end_col {
8340 break;
8341 }
8342 local_segment_ix += 1;
8343 }
8344 if cursor_col < run_end_col {
8345 output_runs.push(TextRun {
8346 len: run_end_col - cursor_col,
8347 font: text_run.font.clone(),
8348 color: text_run.color,
8349 background_color: text_run.background_color,
8350 underline: text_run.underline,
8351 strikethrough: text_run.strikethrough,
8352 });
8353 }
8354 line_col = run_end_col;
8355 segment_ix = local_segment_ix;
8356 }
8357 output_runs
8358 }
8359
8360 fn prepaint(
8361 &mut self,
8362 line_height: Pixels,
8363 scroll_position: gpui::Point<ScrollOffset>,
8364 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8365 row: DisplayRow,
8366 content_origin: gpui::Point<Pixels>,
8367 line_elements: &mut SmallVec<[AnyElement; 1]>,
8368 window: &mut Window,
8369 cx: &mut App,
8370 ) {
8371 let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
8372 self.prepaint_with_custom_offset(
8373 line_height,
8374 scroll_pixel_position,
8375 content_origin,
8376 line_y,
8377 line_elements,
8378 window,
8379 cx,
8380 );
8381 }
8382
8383 fn prepaint_with_custom_offset(
8384 &mut self,
8385 line_height: Pixels,
8386 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8387 content_origin: gpui::Point<Pixels>,
8388 line_y: Pixels,
8389 line_elements: &mut SmallVec<[AnyElement; 1]>,
8390 window: &mut Window,
8391 cx: &mut App,
8392 ) {
8393 let mut fragment_origin =
8394 content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
8395 for fragment in &mut self.fragments {
8396 match fragment {
8397 LineFragment::Text(line) => {
8398 fragment_origin.x += line.width;
8399 }
8400 LineFragment::Element { element, size, .. } => {
8401 let mut element = element
8402 .take()
8403 .expect("you can't prepaint LineWithInvisibles twice");
8404
8405 // Center the element vertically within the line.
8406 let mut element_origin = fragment_origin;
8407 element_origin.y += (line_height - size.height) / 2.;
8408 element.prepaint_at(element_origin, window, cx);
8409 line_elements.push(element);
8410
8411 fragment_origin.x += size.width;
8412 }
8413 }
8414 }
8415 }
8416
8417 fn draw(
8418 &self,
8419 layout: &EditorLayout,
8420 row: DisplayRow,
8421 content_origin: gpui::Point<Pixels>,
8422 whitespace_setting: ShowWhitespaceSetting,
8423 selection_ranges: &[Range<DisplayPoint>],
8424 window: &mut Window,
8425 cx: &mut App,
8426 ) {
8427 self.draw_with_custom_offset(
8428 layout,
8429 row,
8430 content_origin,
8431 layout.position_map.line_height
8432 * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
8433 whitespace_setting,
8434 selection_ranges,
8435 window,
8436 cx,
8437 );
8438 }
8439
8440 fn draw_with_custom_offset(
8441 &self,
8442 layout: &EditorLayout,
8443 row: DisplayRow,
8444 content_origin: gpui::Point<Pixels>,
8445 line_y: Pixels,
8446 whitespace_setting: ShowWhitespaceSetting,
8447 selection_ranges: &[Range<DisplayPoint>],
8448 window: &mut Window,
8449 cx: &mut App,
8450 ) {
8451 let line_height = layout.position_map.line_height;
8452 let mut fragment_origin = content_origin
8453 + gpui::point(
8454 Pixels::from(-layout.position_map.scroll_pixel_position.x),
8455 line_y,
8456 );
8457
8458 for fragment in &self.fragments {
8459 match fragment {
8460 LineFragment::Text(line) => {
8461 line.paint(fragment_origin, line_height, window, cx)
8462 .log_err();
8463 fragment_origin.x += line.width;
8464 }
8465 LineFragment::Element { size, .. } => {
8466 fragment_origin.x += size.width;
8467 }
8468 }
8469 }
8470
8471 self.draw_invisibles(
8472 selection_ranges,
8473 layout,
8474 content_origin,
8475 line_y,
8476 row,
8477 line_height,
8478 whitespace_setting,
8479 window,
8480 cx,
8481 );
8482 }
8483
8484 fn draw_background(
8485 &self,
8486 layout: &EditorLayout,
8487 row: DisplayRow,
8488 content_origin: gpui::Point<Pixels>,
8489 window: &mut Window,
8490 cx: &mut App,
8491 ) {
8492 let line_height = layout.position_map.line_height;
8493 let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
8494
8495 let mut fragment_origin = content_origin
8496 + gpui::point(
8497 Pixels::from(-layout.position_map.scroll_pixel_position.x),
8498 line_y,
8499 );
8500
8501 for fragment in &self.fragments {
8502 match fragment {
8503 LineFragment::Text(line) => {
8504 line.paint_background(fragment_origin, line_height, window, cx)
8505 .log_err();
8506 fragment_origin.x += line.width;
8507 }
8508 LineFragment::Element { size, .. } => {
8509 fragment_origin.x += size.width;
8510 }
8511 }
8512 }
8513 }
8514
8515 fn draw_invisibles(
8516 &self,
8517 selection_ranges: &[Range<DisplayPoint>],
8518 layout: &EditorLayout,
8519 content_origin: gpui::Point<Pixels>,
8520 line_y: Pixels,
8521 row: DisplayRow,
8522 line_height: Pixels,
8523 whitespace_setting: ShowWhitespaceSetting,
8524 window: &mut Window,
8525 cx: &mut App,
8526 ) {
8527 let extract_whitespace_info = |invisible: &Invisible| {
8528 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
8529 Invisible::Tab {
8530 line_start_offset,
8531 line_end_offset,
8532 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
8533 Invisible::Whitespace { line_offset } => {
8534 (*line_offset, line_offset + 1, &layout.space_invisible)
8535 }
8536 };
8537
8538 let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
8539 let invisible_offset: ScrollPixelOffset =
8540 ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
8541 .into();
8542 let origin = content_origin
8543 + gpui::point(
8544 Pixels::from(
8545 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
8546 ),
8547 line_y,
8548 );
8549
8550 (
8551 [token_offset, token_end_offset],
8552 Box::new(move |window: &mut Window, cx: &mut App| {
8553 invisible_symbol
8554 .paint(origin, line_height, window, cx)
8555 .log_err();
8556 }),
8557 )
8558 };
8559
8560 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
8561 match whitespace_setting {
8562 ShowWhitespaceSetting::None => (),
8563 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
8564 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
8565 let invisible_point = DisplayPoint::new(row, start as u32);
8566 if !selection_ranges
8567 .iter()
8568 .any(|region| region.start <= invisible_point && invisible_point < region.end)
8569 {
8570 return;
8571 }
8572
8573 paint(window, cx);
8574 }),
8575
8576 ShowWhitespaceSetting::Trailing => {
8577 let mut previous_start = self.len;
8578 for ([start, end], paint) in invisible_iter.rev() {
8579 if previous_start != end {
8580 break;
8581 }
8582 previous_start = start;
8583 paint(window, cx);
8584 }
8585 }
8586
8587 // For a whitespace to be on a boundary, any of the following conditions need to be met:
8588 // - It is a tab
8589 // - It is adjacent to an edge (start or end)
8590 // - It is adjacent to a whitespace (left or right)
8591 ShowWhitespaceSetting::Boundary => {
8592 // 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
8593 // the above cases.
8594 // Note: We zip in the original `invisibles` to check for tab equality
8595 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
8596 for (([start, end], paint), invisible) in
8597 invisible_iter.zip_eq(self.invisibles.iter())
8598 {
8599 let should_render = match (&last_seen, invisible) {
8600 (_, Invisible::Tab { .. }) => true,
8601 (Some((_, last_end, _)), _) => *last_end == start,
8602 _ => false,
8603 };
8604
8605 if should_render || start == 0 || end == self.len {
8606 paint(window, cx);
8607
8608 // Since we are scanning from the left, we will skip over the first available whitespace that is part
8609 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
8610 if let Some((should_render_last, last_end, paint_last)) = last_seen {
8611 // Note that we need to make sure that the last one is actually adjacent
8612 if !should_render_last && last_end == start {
8613 paint_last(window, cx);
8614 }
8615 }
8616 }
8617
8618 // Manually render anything within a selection
8619 let invisible_point = DisplayPoint::new(row, start as u32);
8620 if selection_ranges.iter().any(|region| {
8621 region.start <= invisible_point && invisible_point < region.end
8622 }) {
8623 paint(window, cx);
8624 }
8625
8626 last_seen = Some((should_render, end, paint));
8627 }
8628 }
8629 }
8630 }
8631
8632 pub fn x_for_index(&self, index: usize) -> Pixels {
8633 let mut fragment_start_x = Pixels::ZERO;
8634 let mut fragment_start_index = 0;
8635
8636 for fragment in &self.fragments {
8637 match fragment {
8638 LineFragment::Text(shaped_line) => {
8639 let fragment_end_index = fragment_start_index + shaped_line.len;
8640 if index < fragment_end_index {
8641 return fragment_start_x
8642 + shaped_line.x_for_index(index - fragment_start_index);
8643 }
8644 fragment_start_x += shaped_line.width;
8645 fragment_start_index = fragment_end_index;
8646 }
8647 LineFragment::Element { len, size, .. } => {
8648 let fragment_end_index = fragment_start_index + len;
8649 if index < fragment_end_index {
8650 return fragment_start_x;
8651 }
8652 fragment_start_x += size.width;
8653 fragment_start_index = fragment_end_index;
8654 }
8655 }
8656 }
8657
8658 fragment_start_x
8659 }
8660
8661 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
8662 let mut fragment_start_x = Pixels::ZERO;
8663 let mut fragment_start_index = 0;
8664
8665 for fragment in &self.fragments {
8666 match fragment {
8667 LineFragment::Text(shaped_line) => {
8668 let fragment_end_x = fragment_start_x + shaped_line.width;
8669 if x < fragment_end_x {
8670 return Some(
8671 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x),
8672 );
8673 }
8674 fragment_start_x = fragment_end_x;
8675 fragment_start_index += shaped_line.len;
8676 }
8677 LineFragment::Element { len, size, .. } => {
8678 let fragment_end_x = fragment_start_x + size.width;
8679 if x < fragment_end_x {
8680 return Some(fragment_start_index);
8681 }
8682 fragment_start_index += len;
8683 fragment_start_x = fragment_end_x;
8684 }
8685 }
8686 }
8687
8688 None
8689 }
8690
8691 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
8692 let mut fragment_start_index = 0;
8693
8694 for fragment in &self.fragments {
8695 match fragment {
8696 LineFragment::Text(shaped_line) => {
8697 let fragment_end_index = fragment_start_index + shaped_line.len;
8698 if index < fragment_end_index {
8699 return shaped_line.font_id_for_index(index - fragment_start_index);
8700 }
8701 fragment_start_index = fragment_end_index;
8702 }
8703 LineFragment::Element { len, .. } => {
8704 let fragment_end_index = fragment_start_index + len;
8705 if index < fragment_end_index {
8706 return None;
8707 }
8708 fragment_start_index = fragment_end_index;
8709 }
8710 }
8711 }
8712
8713 None
8714 }
8715}
8716
8717#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8718enum Invisible {
8719 /// A tab character
8720 ///
8721 /// A tab character is internally represented by spaces (configured by the user's tab width)
8722 /// aligned to the nearest column, so it's necessary to store the start and end offset for
8723 /// adjacency checks.
8724 Tab {
8725 line_start_offset: usize,
8726 line_end_offset: usize,
8727 },
8728 Whitespace {
8729 line_offset: usize,
8730 },
8731}
8732
8733impl EditorElement {
8734 /// Returns the rem size to use when rendering the [`EditorElement`].
8735 ///
8736 /// This allows UI elements to scale based on the `buffer_font_size`.
8737 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
8738 match self.editor.read(cx).mode {
8739 EditorMode::Full {
8740 scale_ui_elements_with_buffer_font_size: true,
8741 ..
8742 }
8743 | EditorMode::Minimap { .. } => {
8744 let buffer_font_size = self.style.text.font_size;
8745 match buffer_font_size {
8746 AbsoluteLength::Pixels(pixels) => {
8747 let rem_size_scale = {
8748 // Our default UI font size is 14px on a 16px base scale.
8749 // This means the default UI font size is 0.875rems.
8750 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
8751
8752 // We then determine the delta between a single rem and the default font
8753 // size scale.
8754 let default_font_size_delta = 1. - default_font_size_scale;
8755
8756 // Finally, we add this delta to 1rem to get the scale factor that
8757 // should be used to scale up the UI.
8758 1. + default_font_size_delta
8759 };
8760
8761 Some(pixels * rem_size_scale)
8762 }
8763 AbsoluteLength::Rems(rems) => {
8764 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
8765 }
8766 }
8767 }
8768 // We currently use single-line and auto-height editors in UI contexts,
8769 // so we don't want to scale everything with the buffer font size, as it
8770 // ends up looking off.
8771 _ => None,
8772 }
8773 }
8774
8775 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
8776 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
8777 parent.upgrade()
8778 } else {
8779 Some(self.editor.clone())
8780 }
8781 }
8782}
8783
8784impl Element for EditorElement {
8785 type RequestLayoutState = ();
8786 type PrepaintState = EditorLayout;
8787
8788 fn id(&self) -> Option<ElementId> {
8789 None
8790 }
8791
8792 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
8793 None
8794 }
8795
8796 fn request_layout(
8797 &mut self,
8798 _: Option<&GlobalElementId>,
8799 _inspector_id: Option<&gpui::InspectorElementId>,
8800 window: &mut Window,
8801 cx: &mut App,
8802 ) -> (gpui::LayoutId, ()) {
8803 let rem_size = self.rem_size(cx);
8804 window.with_rem_size(rem_size, |window| {
8805 self.editor.update(cx, |editor, cx| {
8806 editor.set_style(self.style.clone(), window, cx);
8807
8808 let layout_id = match editor.mode {
8809 EditorMode::SingleLine => {
8810 let rem_size = window.rem_size();
8811 let height = self.style.text.line_height_in_pixels(rem_size);
8812 let mut style = Style::default();
8813 style.size.height = height.into();
8814 style.size.width = relative(1.).into();
8815 window.request_layout(style, None, cx)
8816 }
8817 EditorMode::AutoHeight {
8818 min_lines,
8819 max_lines,
8820 } => {
8821 let editor_handle = cx.entity();
8822 let max_line_number_width =
8823 self.max_line_number_width(&editor.snapshot(window, cx), window);
8824 window.request_measured_layout(
8825 Style::default(),
8826 move |known_dimensions, available_space, window, cx| {
8827 editor_handle
8828 .update(cx, |editor, cx| {
8829 compute_auto_height_layout(
8830 editor,
8831 min_lines,
8832 max_lines,
8833 max_line_number_width,
8834 known_dimensions,
8835 available_space.width,
8836 window,
8837 cx,
8838 )
8839 })
8840 .unwrap_or_default()
8841 },
8842 )
8843 }
8844 EditorMode::Minimap { .. } => {
8845 let mut style = Style::default();
8846 style.size.width = relative(1.).into();
8847 style.size.height = relative(1.).into();
8848 window.request_layout(style, None, cx)
8849 }
8850 EditorMode::Full {
8851 sizing_behavior, ..
8852 } => {
8853 let mut style = Style::default();
8854 style.size.width = relative(1.).into();
8855 if sizing_behavior == SizingBehavior::SizeByContent {
8856 let snapshot = editor.snapshot(window, cx);
8857 let line_height =
8858 self.style.text.line_height_in_pixels(window.rem_size());
8859 let scroll_height =
8860 (snapshot.max_point().row().next_row().0 as f32) * line_height;
8861 style.size.height = scroll_height.into();
8862 } else {
8863 style.size.height = relative(1.).into();
8864 }
8865 window.request_layout(style, None, cx)
8866 }
8867 };
8868
8869 (layout_id, ())
8870 })
8871 })
8872 }
8873
8874 fn prepaint(
8875 &mut self,
8876 _: Option<&GlobalElementId>,
8877 _inspector_id: Option<&gpui::InspectorElementId>,
8878 bounds: Bounds<Pixels>,
8879 _: &mut Self::RequestLayoutState,
8880 window: &mut Window,
8881 cx: &mut App,
8882 ) -> Self::PrepaintState {
8883 let text_style = TextStyleRefinement {
8884 font_size: Some(self.style.text.font_size),
8885 line_height: Some(self.style.text.line_height),
8886 ..Default::default()
8887 };
8888
8889 let is_minimap = self.editor.read(cx).mode.is_minimap();
8890 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
8891
8892 if !is_minimap {
8893 let focus_handle = self.editor.focus_handle(cx);
8894 window.set_view_id(self.editor.entity_id());
8895 window.set_focus_handle(&focus_handle, cx);
8896 }
8897
8898 let rem_size = self.rem_size(cx);
8899 window.with_rem_size(rem_size, |window| {
8900 window.with_text_style(Some(text_style), |window| {
8901 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8902 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
8903 (editor.snapshot(window, cx), editor.read_only(cx))
8904 });
8905 let style = &self.style;
8906
8907 let rem_size = window.rem_size();
8908 let font_id = window.text_system().resolve_font(&style.text.font());
8909 let font_size = style.text.font_size.to_pixels(rem_size);
8910 let line_height = style.text.line_height_in_pixels(rem_size);
8911 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8912 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
8913 let glyph_grid_cell = size(em_advance, line_height);
8914
8915 let gutter_dimensions = snapshot
8916 .gutter_dimensions(
8917 font_id,
8918 font_size,
8919 self.max_line_number_width(&snapshot, window),
8920 cx,
8921 )
8922 .or_else(|| {
8923 self.editor.read(cx).offset_content.then(|| {
8924 GutterDimensions::default_with_margin(font_id, font_size, cx)
8925 })
8926 })
8927 .unwrap_or_default();
8928 let text_width = bounds.size.width - gutter_dimensions.width;
8929
8930 let settings = EditorSettings::get_global(cx);
8931 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
8932 let vertical_scrollbar_width = (scrollbars_shown
8933 && settings.scrollbar.axes.vertical
8934 && self.editor.read(cx).show_scrollbars.vertical)
8935 .then_some(style.scrollbar_width)
8936 .unwrap_or_default();
8937 let minimap_width = self
8938 .get_minimap_width(
8939 &settings.minimap,
8940 scrollbars_shown,
8941 text_width,
8942 em_width,
8943 font_size,
8944 rem_size,
8945 cx,
8946 )
8947 .unwrap_or_default();
8948
8949 let right_margin = minimap_width + vertical_scrollbar_width;
8950
8951 let editor_width =
8952 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
8953 let editor_margins = EditorMargins {
8954 gutter: gutter_dimensions,
8955 right: right_margin,
8956 };
8957
8958 snapshot = self.editor.update(cx, |editor, cx| {
8959 editor.last_bounds = Some(bounds);
8960 editor.gutter_dimensions = gutter_dimensions;
8961 editor.set_visible_line_count(
8962 (bounds.size.height / line_height) as f64,
8963 window,
8964 cx,
8965 );
8966 editor.set_visible_column_count(f64::from(editor_width / em_advance));
8967
8968 if matches!(
8969 editor.mode,
8970 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
8971 ) {
8972 snapshot
8973 } else {
8974 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
8975 let wrap_width = match editor.soft_wrap_mode(cx) {
8976 SoftWrap::GitDiff => None,
8977 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
8978 SoftWrap::EditorWidth => Some(editor_width),
8979 SoftWrap::Column(column) => Some(wrap_width_for(column)),
8980 SoftWrap::Bounded(column) => {
8981 Some(editor_width.min(wrap_width_for(column)))
8982 }
8983 };
8984
8985 if editor.set_wrap_width(wrap_width, cx) {
8986 editor.snapshot(window, cx)
8987 } else {
8988 snapshot
8989 }
8990 }
8991 });
8992
8993 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
8994 let gutter_hitbox = window.insert_hitbox(
8995 gutter_bounds(bounds, gutter_dimensions),
8996 HitboxBehavior::Normal,
8997 );
8998 let text_hitbox = window.insert_hitbox(
8999 Bounds {
9000 origin: gutter_hitbox.top_right(),
9001 size: size(text_width, bounds.size.height),
9002 },
9003 HitboxBehavior::Normal,
9004 );
9005
9006 // Offset the content_bounds from the text_bounds by the gutter margin (which
9007 // is roughly half a character wide) to make hit testing work more like how we want.
9008 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
9009 let content_origin = text_hitbox.origin + content_offset;
9010
9011 let height_in_lines = f64::from(bounds.size.height / line_height);
9012 let max_row = snapshot.max_point().row().as_f64();
9013
9014 // The max scroll position for the top of the window
9015 let max_scroll_top = if matches!(
9016 snapshot.mode,
9017 EditorMode::SingleLine
9018 | EditorMode::AutoHeight { .. }
9019 | EditorMode::Full {
9020 sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
9021 | SizingBehavior::SizeByContent,
9022 ..
9023 }
9024 ) {
9025 (max_row - height_in_lines + 1.).max(0.)
9026 } else {
9027 let settings = EditorSettings::get_global(cx);
9028 match settings.scroll_beyond_last_line {
9029 ScrollBeyondLastLine::OnePage => max_row,
9030 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
9031 ScrollBeyondLastLine::VerticalScrollMargin => {
9032 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
9033 .max(0.)
9034 }
9035 }
9036 };
9037
9038 let (
9039 autoscroll_request,
9040 autoscroll_containing_element,
9041 needs_horizontal_autoscroll,
9042 ) = self.editor.update(cx, |editor, cx| {
9043 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
9044
9045 let autoscroll_containing_element =
9046 autoscroll_request.is_some() || editor.has_pending_selection();
9047
9048 let (needs_horizontal_autoscroll, was_scrolled) = editor
9049 .autoscroll_vertically(
9050 bounds,
9051 line_height,
9052 max_scroll_top,
9053 autoscroll_request,
9054 window,
9055 cx,
9056 );
9057 if was_scrolled.0 {
9058 snapshot = editor.snapshot(window, cx);
9059 }
9060 (
9061 autoscroll_request,
9062 autoscroll_containing_element,
9063 needs_horizontal_autoscroll,
9064 )
9065 });
9066
9067 let mut scroll_position = snapshot.scroll_position();
9068 // The scroll position is a fractional point, the whole number of which represents
9069 // the top of the window in terms of display rows.
9070 let start_row = DisplayRow(scroll_position.y as u32);
9071 let max_row = snapshot.max_point().row();
9072 let end_row = cmp::min(
9073 (scroll_position.y + height_in_lines).ceil() as u32,
9074 max_row.next_row().0,
9075 );
9076 let end_row = DisplayRow(end_row);
9077
9078 let row_infos = snapshot
9079 .row_infos(start_row)
9080 .take((start_row..end_row).len())
9081 .collect::<Vec<RowInfo>>();
9082 let is_row_soft_wrapped = |row: usize| {
9083 row_infos
9084 .get(row)
9085 .is_none_or(|info| info.buffer_row.is_none())
9086 };
9087
9088 let start_anchor = if start_row == Default::default() {
9089 Anchor::min()
9090 } else {
9091 snapshot.buffer_snapshot().anchor_before(
9092 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
9093 )
9094 };
9095 let end_anchor = if end_row > max_row {
9096 Anchor::max()
9097 } else {
9098 snapshot.buffer_snapshot().anchor_before(
9099 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
9100 )
9101 };
9102
9103 let mut highlighted_rows = self
9104 .editor
9105 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
9106
9107 let is_light = cx.theme().appearance().is_light();
9108
9109 for (ix, row_info) in row_infos.iter().enumerate() {
9110 let Some(diff_status) = row_info.diff_status else {
9111 continue;
9112 };
9113
9114 let background_color = match diff_status.kind {
9115 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
9116 DiffHunkStatusKind::Deleted => {
9117 cx.theme().colors().version_control_deleted
9118 }
9119 DiffHunkStatusKind::Modified => {
9120 debug_panic!("modified diff status for row info");
9121 continue;
9122 }
9123 };
9124
9125 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
9126
9127 let hollow_highlight = LineHighlight {
9128 background: (background_color.opacity(if is_light {
9129 0.08
9130 } else {
9131 0.06
9132 }))
9133 .into(),
9134 border: Some(if is_light {
9135 background_color.opacity(0.48)
9136 } else {
9137 background_color.opacity(0.36)
9138 }),
9139 include_gutter: true,
9140 type_id: None,
9141 };
9142
9143 let filled_highlight = LineHighlight {
9144 background: solid_background(background_color.opacity(hunk_opacity)),
9145 border: None,
9146 include_gutter: true,
9147 type_id: None,
9148 };
9149
9150 let background = if Self::diff_hunk_hollow(diff_status, cx) {
9151 hollow_highlight
9152 } else {
9153 filled_highlight
9154 };
9155
9156 highlighted_rows
9157 .entry(start_row + DisplayRow(ix as u32))
9158 .or_insert(background);
9159 }
9160
9161 let highlighted_ranges = self
9162 .editor_with_selections(cx)
9163 .map(|editor| {
9164 editor.read(cx).background_highlights_in_range(
9165 start_anchor..end_anchor,
9166 &snapshot.display_snapshot,
9167 cx.theme(),
9168 )
9169 })
9170 .unwrap_or_default();
9171 let highlighted_gutter_ranges =
9172 self.editor.read(cx).gutter_highlights_in_range(
9173 start_anchor..end_anchor,
9174 &snapshot.display_snapshot,
9175 cx,
9176 );
9177
9178 let document_colors = self
9179 .editor
9180 .read(cx)
9181 .colors
9182 .as_ref()
9183 .map(|colors| colors.editor_display_highlights(&snapshot));
9184 let redacted_ranges = self.editor.read(cx).redacted_ranges(
9185 start_anchor..end_anchor,
9186 &snapshot.display_snapshot,
9187 cx,
9188 );
9189
9190 let (local_selections, selected_buffer_ids, selection_anchors): (
9191 Vec<Selection<Point>>,
9192 Vec<BufferId>,
9193 Arc<[Selection<Anchor>]>,
9194 ) = self
9195 .editor_with_selections(cx)
9196 .map(|editor| {
9197 editor.update(cx, |editor, cx| {
9198 let all_selections =
9199 editor.selections.all::<Point>(&snapshot.display_snapshot);
9200 let all_anchor_selections =
9201 editor.selections.all_anchors(&snapshot.display_snapshot);
9202 let selected_buffer_ids =
9203 if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
9204 Vec::new()
9205 } else {
9206 let mut selected_buffer_ids =
9207 Vec::with_capacity(all_selections.len());
9208
9209 for selection in all_selections {
9210 for buffer_id in snapshot
9211 .buffer_snapshot()
9212 .buffer_ids_for_range(selection.range())
9213 {
9214 if selected_buffer_ids.last() != Some(&buffer_id) {
9215 selected_buffer_ids.push(buffer_id);
9216 }
9217 }
9218 }
9219
9220 selected_buffer_ids
9221 };
9222
9223 let mut selections = editor.selections.disjoint_in_range(
9224 start_anchor..end_anchor,
9225 &snapshot.display_snapshot,
9226 );
9227 selections
9228 .extend(editor.selections.pending(&snapshot.display_snapshot));
9229
9230 (selections, selected_buffer_ids, all_anchor_selections)
9231 })
9232 })
9233 .unwrap_or_else(|| {
9234 (
9235 Vec::new(),
9236 Vec::new(),
9237 Arc::<[Selection<Anchor>]>::from(Vec::new()),
9238 )
9239 });
9240
9241 let (selections, mut active_rows, newest_selection_head) = self
9242 .layout_selections(
9243 start_anchor,
9244 end_anchor,
9245 &local_selections,
9246 &snapshot,
9247 start_row,
9248 end_row,
9249 window,
9250 cx,
9251 );
9252 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
9253 editor.active_breakpoints(start_row..end_row, window, cx)
9254 });
9255 for (display_row, (_, bp, state)) in &breakpoint_rows {
9256 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
9257 active_rows.entry(*display_row).or_default().breakpoint = true;
9258 }
9259 }
9260
9261 let line_numbers = self.layout_line_numbers(
9262 Some(&gutter_hitbox),
9263 gutter_dimensions,
9264 line_height,
9265 scroll_position,
9266 start_row..end_row,
9267 &row_infos,
9268 &active_rows,
9269 newest_selection_head,
9270 &snapshot,
9271 window,
9272 cx,
9273 );
9274
9275 // We add the gutter breakpoint indicator to breakpoint_rows after painting
9276 // line numbers so we don't paint a line number debug accent color if a user
9277 // has their mouse over that line when a breakpoint isn't there
9278 self.editor.update(cx, |editor, _| {
9279 if let Some(phantom_breakpoint) = &mut editor
9280 .gutter_breakpoint_indicator
9281 .0
9282 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
9283 {
9284 // Is there a non-phantom breakpoint on this line?
9285 phantom_breakpoint.collides_with_existing_breakpoint = true;
9286 breakpoint_rows
9287 .entry(phantom_breakpoint.display_row)
9288 .or_insert_with(|| {
9289 let position = snapshot.display_point_to_anchor(
9290 DisplayPoint::new(phantom_breakpoint.display_row, 0),
9291 Bias::Right,
9292 );
9293 let breakpoint = Breakpoint::new_standard();
9294 phantom_breakpoint.collides_with_existing_breakpoint = false;
9295 (position, breakpoint, None)
9296 });
9297 }
9298 });
9299
9300 let mut expand_toggles =
9301 window.with_element_namespace("expand_toggles", |window| {
9302 self.layout_expand_toggles(
9303 &gutter_hitbox,
9304 gutter_dimensions,
9305 em_width,
9306 line_height,
9307 scroll_position,
9308 &row_infos,
9309 window,
9310 cx,
9311 )
9312 });
9313
9314 let mut crease_toggles =
9315 window.with_element_namespace("crease_toggles", |window| {
9316 self.layout_crease_toggles(
9317 start_row..end_row,
9318 &row_infos,
9319 &active_rows,
9320 &snapshot,
9321 window,
9322 cx,
9323 )
9324 });
9325 let crease_trailers =
9326 window.with_element_namespace("crease_trailers", |window| {
9327 self.layout_crease_trailers(
9328 row_infos.iter().copied(),
9329 &snapshot,
9330 window,
9331 cx,
9332 )
9333 });
9334
9335 let display_hunks = self.layout_gutter_diff_hunks(
9336 line_height,
9337 &gutter_hitbox,
9338 start_row..end_row,
9339 &snapshot,
9340 window,
9341 cx,
9342 );
9343
9344 let merged_highlighted_ranges =
9345 if let Some((_, colors)) = document_colors.as_ref() {
9346 &highlighted_ranges
9347 .clone()
9348 .into_iter()
9349 .chain(colors.clone())
9350 .collect()
9351 } else {
9352 &highlighted_ranges
9353 };
9354 let bg_segments_per_row = Self::bg_segments_per_row(
9355 start_row..end_row,
9356 &selections,
9357 &merged_highlighted_ranges,
9358 self.style.background,
9359 );
9360
9361 let mut line_layouts = Self::layout_lines(
9362 start_row..end_row,
9363 &snapshot,
9364 &self.style,
9365 editor_width,
9366 is_row_soft_wrapped,
9367 &bg_segments_per_row,
9368 window,
9369 cx,
9370 );
9371 let new_renderer_widths = (!is_minimap).then(|| {
9372 line_layouts
9373 .iter()
9374 .flat_map(|layout| &layout.fragments)
9375 .filter_map(|fragment| {
9376 if let LineFragment::Element { id, size, .. } = fragment {
9377 Some((*id, size.width))
9378 } else {
9379 None
9380 }
9381 })
9382 });
9383 if new_renderer_widths.is_some_and(|new_renderer_widths| {
9384 self.editor.update(cx, |editor, cx| {
9385 editor.update_renderer_widths(new_renderer_widths, cx)
9386 })
9387 }) {
9388 // If the fold widths have changed, we need to prepaint
9389 // the element again to account for any changes in
9390 // wrapping.
9391 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
9392 }
9393
9394 let longest_line_blame_width = self
9395 .editor
9396 .update(cx, |editor, cx| {
9397 if !editor.show_git_blame_inline {
9398 return None;
9399 }
9400 let blame = editor.blame.as_ref()?;
9401 let (_, blame_entry) = blame
9402 .update(cx, |blame, cx| {
9403 let row_infos =
9404 snapshot.row_infos(snapshot.longest_row()).next()?;
9405 blame.blame_for_rows(&[row_infos], cx).next()
9406 })
9407 .flatten()?;
9408 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
9409 let inline_blame_padding =
9410 ProjectSettings::get_global(cx).git.inline_blame.padding as f32
9411 * em_advance;
9412 Some(
9413 element
9414 .layout_as_root(AvailableSpace::min_size(), window, cx)
9415 .width
9416 + inline_blame_padding,
9417 )
9418 })
9419 .unwrap_or(Pixels::ZERO);
9420
9421 let longest_line_width = layout_line(
9422 snapshot.longest_row(),
9423 &snapshot,
9424 style,
9425 editor_width,
9426 is_row_soft_wrapped,
9427 window,
9428 cx,
9429 )
9430 .width;
9431
9432 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
9433 text_hitbox.bounds,
9434 glyph_grid_cell,
9435 size(
9436 longest_line_width,
9437 Pixels::from(max_row.as_f64() * f64::from(line_height)),
9438 ),
9439 longest_line_blame_width,
9440 EditorSettings::get_global(cx),
9441 );
9442
9443 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
9444
9445 let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
9446 snapshot.sticky_header_excerpt(scroll_position.y)
9447 } else {
9448 None
9449 };
9450 let sticky_header_excerpt_id =
9451 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
9452
9453 let blocks = (!is_minimap)
9454 .then(|| {
9455 window.with_element_namespace("blocks", |window| {
9456 self.render_blocks(
9457 start_row..end_row,
9458 &snapshot,
9459 &hitbox,
9460 &text_hitbox,
9461 editor_width,
9462 &mut scroll_width,
9463 &editor_margins,
9464 em_width,
9465 gutter_dimensions.full_width(),
9466 line_height,
9467 &mut line_layouts,
9468 &local_selections,
9469 &selected_buffer_ids,
9470 selection_anchors.as_ref(),
9471 is_row_soft_wrapped,
9472 sticky_header_excerpt_id,
9473 window,
9474 cx,
9475 )
9476 })
9477 })
9478 .unwrap_or_else(|| Ok((Vec::default(), HashMap::default())));
9479 let (mut blocks, row_block_types) = match blocks {
9480 Ok(blocks) => blocks,
9481 Err(resized_blocks) => {
9482 self.editor.update(cx, |editor, cx| {
9483 editor.resize_blocks(
9484 resized_blocks,
9485 autoscroll_request.map(|(autoscroll, _)| autoscroll),
9486 cx,
9487 )
9488 });
9489 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
9490 }
9491 };
9492
9493 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
9494 window.with_element_namespace("blocks", |window| {
9495 self.layout_sticky_buffer_header(
9496 sticky_header_excerpt,
9497 scroll_position,
9498 line_height,
9499 right_margin,
9500 &snapshot,
9501 &hitbox,
9502 &selected_buffer_ids,
9503 &blocks,
9504 selection_anchors.as_ref(),
9505 window,
9506 cx,
9507 )
9508 })
9509 });
9510
9511 let start_buffer_row =
9512 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot()).row);
9513 let end_buffer_row =
9514 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot()).row);
9515
9516 let scroll_max: gpui::Point<ScrollPixelOffset> = point(
9517 ScrollPixelOffset::from(
9518 ((scroll_width - editor_width) / em_advance).max(0.0),
9519 ),
9520 max_scroll_top,
9521 );
9522
9523 self.editor.update(cx, |editor, cx| {
9524 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
9525 scroll_position.x = scroll_position.x.min(scroll_max.x);
9526 }
9527
9528 if needs_horizontal_autoscroll.0
9529 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
9530 start_row,
9531 editor_width,
9532 scroll_width,
9533 em_advance,
9534 &line_layouts,
9535 autoscroll_request,
9536 window,
9537 cx,
9538 )
9539 {
9540 scroll_position = new_scroll_position;
9541 }
9542 });
9543
9544 let scroll_pixel_position = point(
9545 scroll_position.x * f64::from(em_advance),
9546 scroll_position.y * f64::from(line_height),
9547 );
9548 let sticky_headers = if !is_minimap
9549 && is_singleton
9550 && EditorSettings::get_global(cx).sticky_scroll.enabled
9551 {
9552 self.layout_sticky_headers(
9553 &snapshot,
9554 editor_width,
9555 is_row_soft_wrapped,
9556 line_height,
9557 scroll_pixel_position,
9558 content_origin,
9559 &gutter_dimensions,
9560 &gutter_hitbox,
9561 &text_hitbox,
9562 window,
9563 cx,
9564 )
9565 } else {
9566 None
9567 };
9568 let indent_guides = self.layout_indent_guides(
9569 content_origin,
9570 text_hitbox.origin,
9571 start_buffer_row..end_buffer_row,
9572 scroll_pixel_position,
9573 line_height,
9574 &snapshot,
9575 window,
9576 cx,
9577 );
9578
9579 let crease_trailers =
9580 window.with_element_namespace("crease_trailers", |window| {
9581 self.prepaint_crease_trailers(
9582 crease_trailers,
9583 &line_layouts,
9584 line_height,
9585 content_origin,
9586 scroll_pixel_position,
9587 em_width,
9588 window,
9589 cx,
9590 )
9591 });
9592
9593 let (edit_prediction_popover, edit_prediction_popover_origin) = self
9594 .editor
9595 .update(cx, |editor, cx| {
9596 editor.render_edit_prediction_popover(
9597 &text_hitbox.bounds,
9598 content_origin,
9599 right_margin,
9600 &snapshot,
9601 start_row..end_row,
9602 scroll_position.y,
9603 scroll_position.y + height_in_lines,
9604 &line_layouts,
9605 line_height,
9606 scroll_position,
9607 scroll_pixel_position,
9608 newest_selection_head,
9609 editor_width,
9610 style,
9611 window,
9612 cx,
9613 )
9614 })
9615 .unzip();
9616
9617 let mut inline_diagnostics = self.layout_inline_diagnostics(
9618 &line_layouts,
9619 &crease_trailers,
9620 &row_block_types,
9621 content_origin,
9622 scroll_position,
9623 scroll_pixel_position,
9624 edit_prediction_popover_origin,
9625 start_row,
9626 end_row,
9627 line_height,
9628 em_width,
9629 style,
9630 window,
9631 cx,
9632 );
9633
9634 let mut inline_blame_layout = None;
9635 let mut inline_code_actions = None;
9636 if let Some(newest_selection_head) = newest_selection_head {
9637 let display_row = newest_selection_head.row();
9638 if (start_row..end_row).contains(&display_row)
9639 && !row_block_types.contains_key(&display_row)
9640 {
9641 inline_code_actions = self.layout_inline_code_actions(
9642 newest_selection_head,
9643 content_origin,
9644 scroll_position,
9645 scroll_pixel_position,
9646 line_height,
9647 &snapshot,
9648 window,
9649 cx,
9650 );
9651
9652 let line_ix = display_row.minus(start_row) as usize;
9653 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
9654 row_infos.get(line_ix),
9655 line_layouts.get(line_ix),
9656 crease_trailers.get(line_ix),
9657 ) {
9658 let crease_trailer_layout = crease_trailer.as_ref();
9659 if let Some(layout) = self.layout_inline_blame(
9660 display_row,
9661 row_info,
9662 line_layout,
9663 crease_trailer_layout,
9664 em_width,
9665 content_origin,
9666 scroll_position,
9667 scroll_pixel_position,
9668 line_height,
9669 &text_hitbox,
9670 window,
9671 cx,
9672 ) {
9673 inline_blame_layout = Some(layout);
9674 // Blame overrides inline diagnostics
9675 inline_diagnostics.remove(&display_row);
9676 }
9677 } else {
9678 log::error!(
9679 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
9680 line_layouts.len(): {}, \
9681 crease_trailers.len(): {}",
9682 line_ix,
9683 row_infos.len(),
9684 line_layouts.len(),
9685 crease_trailers.len(),
9686 );
9687 }
9688 }
9689 }
9690
9691 let blamed_display_rows = self.layout_blame_entries(
9692 &row_infos,
9693 em_width,
9694 scroll_position,
9695 line_height,
9696 &gutter_hitbox,
9697 gutter_dimensions.git_blame_entries_width,
9698 window,
9699 cx,
9700 );
9701
9702 let line_elements = self.prepaint_lines(
9703 start_row,
9704 &mut line_layouts,
9705 line_height,
9706 scroll_position,
9707 scroll_pixel_position,
9708 content_origin,
9709 window,
9710 cx,
9711 );
9712
9713 window.with_element_namespace("blocks", |window| {
9714 self.layout_blocks(
9715 &mut blocks,
9716 &hitbox,
9717 line_height,
9718 scroll_position,
9719 scroll_pixel_position,
9720 window,
9721 cx,
9722 );
9723 });
9724
9725 let cursors = self.collect_cursors(&snapshot, cx);
9726 let visible_row_range = start_row..end_row;
9727 let non_visible_cursors = cursors
9728 .iter()
9729 .any(|c| !visible_row_range.contains(&c.0.row()));
9730
9731 let visible_cursors = self.layout_visible_cursors(
9732 &snapshot,
9733 &selections,
9734 &row_block_types,
9735 start_row..end_row,
9736 &line_layouts,
9737 &text_hitbox,
9738 content_origin,
9739 scroll_position,
9740 scroll_pixel_position,
9741 line_height,
9742 em_width,
9743 em_advance,
9744 autoscroll_containing_element,
9745 window,
9746 cx,
9747 );
9748
9749 let scrollbars_layout = self.layout_scrollbars(
9750 &snapshot,
9751 &scrollbar_layout_information,
9752 content_offset,
9753 scroll_position,
9754 non_visible_cursors,
9755 right_margin,
9756 editor_width,
9757 window,
9758 cx,
9759 );
9760
9761 let gutter_settings = EditorSettings::get_global(cx).gutter;
9762
9763 let context_menu_layout =
9764 if let Some(newest_selection_head) = newest_selection_head {
9765 let newest_selection_point =
9766 newest_selection_head.to_point(&snapshot.display_snapshot);
9767 if (start_row..end_row).contains(&newest_selection_head.row()) {
9768 self.layout_cursor_popovers(
9769 line_height,
9770 &text_hitbox,
9771 content_origin,
9772 right_margin,
9773 start_row,
9774 scroll_pixel_position,
9775 &line_layouts,
9776 newest_selection_head,
9777 newest_selection_point,
9778 style,
9779 window,
9780 cx,
9781 )
9782 } else {
9783 None
9784 }
9785 } else {
9786 None
9787 };
9788
9789 self.layout_gutter_menu(
9790 line_height,
9791 &text_hitbox,
9792 content_origin,
9793 right_margin,
9794 scroll_pixel_position,
9795 gutter_dimensions.width - gutter_dimensions.left_padding,
9796 window,
9797 cx,
9798 );
9799
9800 let test_indicators = if gutter_settings.runnables {
9801 self.layout_run_indicators(
9802 line_height,
9803 start_row..end_row,
9804 &row_infos,
9805 scroll_position,
9806 &gutter_dimensions,
9807 &gutter_hitbox,
9808 &display_hunks,
9809 &snapshot,
9810 &mut breakpoint_rows,
9811 window,
9812 cx,
9813 )
9814 } else {
9815 Vec::new()
9816 };
9817
9818 let show_breakpoints = snapshot
9819 .show_breakpoints
9820 .unwrap_or(gutter_settings.breakpoints);
9821 let breakpoints = if show_breakpoints {
9822 self.layout_breakpoints(
9823 line_height,
9824 start_row..end_row,
9825 scroll_position,
9826 &gutter_dimensions,
9827 &gutter_hitbox,
9828 &display_hunks,
9829 &snapshot,
9830 breakpoint_rows,
9831 &row_infos,
9832 window,
9833 cx,
9834 )
9835 } else {
9836 Vec::new()
9837 };
9838
9839 self.layout_signature_help(
9840 &hitbox,
9841 content_origin,
9842 scroll_pixel_position,
9843 newest_selection_head,
9844 start_row,
9845 &line_layouts,
9846 line_height,
9847 em_width,
9848 context_menu_layout,
9849 window,
9850 cx,
9851 );
9852
9853 if !cx.has_active_drag() {
9854 self.layout_hover_popovers(
9855 &snapshot,
9856 &hitbox,
9857 start_row..end_row,
9858 content_origin,
9859 scroll_pixel_position,
9860 &line_layouts,
9861 line_height,
9862 em_width,
9863 context_menu_layout,
9864 window,
9865 cx,
9866 );
9867 }
9868
9869 let mouse_context_menu = self.layout_mouse_context_menu(
9870 &snapshot,
9871 start_row..end_row,
9872 content_origin,
9873 window,
9874 cx,
9875 );
9876
9877 window.with_element_namespace("crease_toggles", |window| {
9878 self.prepaint_crease_toggles(
9879 &mut crease_toggles,
9880 line_height,
9881 &gutter_dimensions,
9882 gutter_settings,
9883 scroll_pixel_position,
9884 &gutter_hitbox,
9885 window,
9886 cx,
9887 )
9888 });
9889
9890 window.with_element_namespace("expand_toggles", |window| {
9891 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
9892 });
9893
9894 let wrap_guides = self.layout_wrap_guides(
9895 em_advance,
9896 scroll_position,
9897 content_origin,
9898 scrollbars_layout.as_ref(),
9899 vertical_scrollbar_width,
9900 &hitbox,
9901 window,
9902 cx,
9903 );
9904
9905 let minimap = window.with_element_namespace("minimap", |window| {
9906 self.layout_minimap(
9907 &snapshot,
9908 minimap_width,
9909 scroll_position,
9910 &scrollbar_layout_information,
9911 scrollbars_layout.as_ref(),
9912 window,
9913 cx,
9914 )
9915 });
9916
9917 let invisible_symbol_font_size = font_size / 2.;
9918 let whitespace_map = &self
9919 .editor
9920 .read(cx)
9921 .buffer
9922 .read(cx)
9923 .language_settings(cx)
9924 .whitespace_map;
9925
9926 let tab_char = whitespace_map.tab.clone();
9927 let tab_len = tab_char.len();
9928 let tab_invisible = window.text_system().shape_line(
9929 tab_char,
9930 invisible_symbol_font_size,
9931 &[TextRun {
9932 len: tab_len,
9933 font: self.style.text.font(),
9934 color: cx.theme().colors().editor_invisible,
9935 ..Default::default()
9936 }],
9937 None,
9938 );
9939
9940 let space_char = whitespace_map.space.clone();
9941 let space_len = space_char.len();
9942 let space_invisible = window.text_system().shape_line(
9943 space_char,
9944 invisible_symbol_font_size,
9945 &[TextRun {
9946 len: space_len,
9947 font: self.style.text.font(),
9948 color: cx.theme().colors().editor_invisible,
9949 ..Default::default()
9950 }],
9951 None,
9952 );
9953
9954 let mode = snapshot.mode.clone();
9955
9956 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
9957 (vec![], vec![])
9958 } else {
9959 self.layout_diff_hunk_controls(
9960 start_row..end_row,
9961 &row_infos,
9962 &text_hitbox,
9963 newest_selection_head,
9964 line_height,
9965 right_margin,
9966 scroll_pixel_position,
9967 &display_hunks,
9968 &highlighted_rows,
9969 self.editor.clone(),
9970 window,
9971 cx,
9972 )
9973 };
9974
9975 let position_map = Rc::new(PositionMap {
9976 size: bounds.size,
9977 visible_row_range,
9978 scroll_position,
9979 scroll_pixel_position,
9980 scroll_max,
9981 line_layouts,
9982 line_height,
9983 em_width,
9984 em_advance,
9985 snapshot,
9986 gutter_hitbox: gutter_hitbox.clone(),
9987 text_hitbox: text_hitbox.clone(),
9988 inline_blame_bounds: inline_blame_layout
9989 .as_ref()
9990 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
9991 display_hunks: display_hunks.clone(),
9992 diff_hunk_control_bounds,
9993 });
9994
9995 self.editor.update(cx, |editor, _| {
9996 editor.last_position_map = Some(position_map.clone())
9997 });
9998
9999 EditorLayout {
10000 mode,
10001 position_map,
10002 visible_display_row_range: start_row..end_row,
10003 wrap_guides,
10004 indent_guides,
10005 hitbox,
10006 gutter_hitbox,
10007 display_hunks,
10008 content_origin,
10009 scrollbars_layout,
10010 minimap,
10011 active_rows,
10012 highlighted_rows,
10013 highlighted_ranges,
10014 highlighted_gutter_ranges,
10015 redacted_ranges,
10016 document_colors,
10017 line_elements,
10018 line_numbers,
10019 blamed_display_rows,
10020 inline_diagnostics,
10021 inline_blame_layout,
10022 inline_code_actions,
10023 blocks,
10024 cursors,
10025 visible_cursors,
10026 selections,
10027 edit_prediction_popover,
10028 diff_hunk_controls,
10029 mouse_context_menu,
10030 test_indicators,
10031 breakpoints,
10032 crease_toggles,
10033 crease_trailers,
10034 tab_invisible,
10035 space_invisible,
10036 sticky_buffer_header,
10037 sticky_headers,
10038 expand_toggles,
10039 }
10040 })
10041 })
10042 })
10043 }
10044
10045 fn paint(
10046 &mut self,
10047 _: Option<&GlobalElementId>,
10048 _inspector_id: Option<&gpui::InspectorElementId>,
10049 bounds: Bounds<gpui::Pixels>,
10050 _: &mut Self::RequestLayoutState,
10051 layout: &mut Self::PrepaintState,
10052 window: &mut Window,
10053 cx: &mut App,
10054 ) {
10055 if !layout.mode.is_minimap() {
10056 let focus_handle = self.editor.focus_handle(cx);
10057 let key_context = self
10058 .editor
10059 .update(cx, |editor, cx| editor.key_context(window, cx));
10060
10061 window.set_key_context(key_context);
10062 window.handle_input(
10063 &focus_handle,
10064 ElementInputHandler::new(bounds, self.editor.clone()),
10065 cx,
10066 );
10067 self.register_actions(window, cx);
10068 self.register_key_listeners(window, cx, layout);
10069 }
10070
10071 let text_style = TextStyleRefinement {
10072 font_size: Some(self.style.text.font_size),
10073 line_height: Some(self.style.text.line_height),
10074 ..Default::default()
10075 };
10076 let rem_size = self.rem_size(cx);
10077 window.with_rem_size(rem_size, |window| {
10078 window.with_text_style(Some(text_style), |window| {
10079 window.with_content_mask(Some(ContentMask { bounds }), |window| {
10080 self.paint_mouse_listeners(layout, window, cx);
10081 self.paint_background(layout, window, cx);
10082 self.paint_indent_guides(layout, window, cx);
10083
10084 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10085 self.paint_blamed_display_rows(layout, window, cx);
10086 self.paint_line_numbers(layout, window, cx);
10087 }
10088
10089 self.paint_text(layout, window, cx);
10090
10091 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10092 self.paint_gutter_highlights(layout, window, cx);
10093 self.paint_gutter_indicators(layout, window, cx);
10094 }
10095
10096 if !layout.blocks.is_empty() {
10097 window.with_element_namespace("blocks", |window| {
10098 self.paint_blocks(layout, window, cx);
10099 });
10100 }
10101
10102 window.with_element_namespace("blocks", |window| {
10103 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
10104 sticky_header.paint(window, cx)
10105 }
10106 });
10107
10108 self.paint_sticky_headers(layout, window, cx);
10109 self.paint_minimap(layout, window, cx);
10110 self.paint_scrollbars(layout, window, cx);
10111 self.paint_edit_prediction_popover(layout, window, cx);
10112 self.paint_mouse_context_menu(layout, window, cx);
10113 });
10114 })
10115 })
10116 }
10117}
10118
10119pub(super) fn gutter_bounds(
10120 editor_bounds: Bounds<Pixels>,
10121 gutter_dimensions: GutterDimensions,
10122) -> Bounds<Pixels> {
10123 Bounds {
10124 origin: editor_bounds.origin,
10125 size: size(gutter_dimensions.width, editor_bounds.size.height),
10126 }
10127}
10128
10129#[derive(Clone, Copy)]
10130struct ContextMenuLayout {
10131 y_flipped: bool,
10132 bounds: Bounds<Pixels>,
10133}
10134
10135/// Holds information required for layouting the editor scrollbars.
10136struct ScrollbarLayoutInformation {
10137 /// The bounds of the editor area (excluding the content offset).
10138 editor_bounds: Bounds<Pixels>,
10139 /// The available range to scroll within the document.
10140 scroll_range: Size<Pixels>,
10141 /// The space available for one glyph in the editor.
10142 glyph_grid_cell: Size<Pixels>,
10143}
10144
10145impl ScrollbarLayoutInformation {
10146 pub fn new(
10147 editor_bounds: Bounds<Pixels>,
10148 glyph_grid_cell: Size<Pixels>,
10149 document_size: Size<Pixels>,
10150 longest_line_blame_width: Pixels,
10151 settings: &EditorSettings,
10152 ) -> Self {
10153 let vertical_overscroll = match settings.scroll_beyond_last_line {
10154 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
10155 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
10156 ScrollBeyondLastLine::VerticalScrollMargin => {
10157 (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
10158 }
10159 };
10160
10161 let overscroll = size(longest_line_blame_width, vertical_overscroll);
10162
10163 ScrollbarLayoutInformation {
10164 editor_bounds,
10165 scroll_range: document_size + overscroll,
10166 glyph_grid_cell,
10167 }
10168 }
10169}
10170
10171impl IntoElement for EditorElement {
10172 type Element = Self;
10173
10174 fn into_element(self) -> Self::Element {
10175 self
10176 }
10177}
10178
10179pub struct EditorLayout {
10180 position_map: Rc<PositionMap>,
10181 hitbox: Hitbox,
10182 gutter_hitbox: Hitbox,
10183 content_origin: gpui::Point<Pixels>,
10184 scrollbars_layout: Option<EditorScrollbars>,
10185 minimap: Option<MinimapLayout>,
10186 mode: EditorMode,
10187 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
10188 indent_guides: Option<Vec<IndentGuideLayout>>,
10189 visible_display_row_range: Range<DisplayRow>,
10190 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
10191 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
10192 line_elements: SmallVec<[AnyElement; 1]>,
10193 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
10194 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10195 blamed_display_rows: Option<Vec<AnyElement>>,
10196 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
10197 inline_blame_layout: Option<InlineBlameLayout>,
10198 inline_code_actions: Option<AnyElement>,
10199 blocks: Vec<BlockLayout>,
10200 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10201 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10202 redacted_ranges: Vec<Range<DisplayPoint>>,
10203 cursors: Vec<(DisplayPoint, Hsla)>,
10204 visible_cursors: Vec<CursorLayout>,
10205 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
10206 test_indicators: Vec<AnyElement>,
10207 breakpoints: Vec<AnyElement>,
10208 crease_toggles: Vec<Option<AnyElement>>,
10209 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
10210 diff_hunk_controls: Vec<AnyElement>,
10211 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
10212 edit_prediction_popover: Option<AnyElement>,
10213 mouse_context_menu: Option<AnyElement>,
10214 tab_invisible: ShapedLine,
10215 space_invisible: ShapedLine,
10216 sticky_buffer_header: Option<AnyElement>,
10217 sticky_headers: Option<StickyHeaders>,
10218 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
10219}
10220
10221struct StickyHeaders {
10222 lines: Vec<StickyHeaderLine>,
10223 gutter_background: Hsla,
10224 content_background: Hsla,
10225 gutter_right_padding: Pixels,
10226}
10227
10228struct StickyHeaderLine {
10229 row: DisplayRow,
10230 offset: Pixels,
10231 line: LineWithInvisibles,
10232 line_number: Option<ShapedLine>,
10233 elements: SmallVec<[AnyElement; 1]>,
10234 available_text_width: Pixels,
10235 target_anchor: Anchor,
10236 hitbox: Hitbox,
10237}
10238
10239impl EditorLayout {
10240 fn line_end_overshoot(&self) -> Pixels {
10241 0.15 * self.position_map.line_height
10242 }
10243}
10244
10245impl StickyHeaders {
10246 fn paint(
10247 &mut self,
10248 layout: &mut EditorLayout,
10249 whitespace_setting: ShowWhitespaceSetting,
10250 window: &mut Window,
10251 cx: &mut App,
10252 ) {
10253 let line_height = layout.position_map.line_height;
10254
10255 for line in self.lines.iter_mut().rev() {
10256 window.paint_layer(
10257 Bounds::new(
10258 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10259 size(line.hitbox.size.width, line_height),
10260 ),
10261 |window| {
10262 let gutter_bounds = Bounds::new(
10263 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10264 size(layout.gutter_hitbox.size.width, line_height),
10265 );
10266 window.paint_quad(fill(gutter_bounds, self.gutter_background));
10267
10268 let text_bounds = Bounds::new(
10269 layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
10270 size(line.available_text_width, line_height),
10271 );
10272 window.paint_quad(fill(text_bounds, self.content_background));
10273
10274 if line.hitbox.is_hovered(window) {
10275 let hover_overlay = cx.theme().colors().panel_overlay_hover;
10276 window.paint_quad(fill(gutter_bounds, hover_overlay));
10277 window.paint_quad(fill(text_bounds, hover_overlay));
10278 }
10279
10280 line.paint(
10281 layout,
10282 self.gutter_right_padding,
10283 line.available_text_width,
10284 layout.content_origin,
10285 line_height,
10286 whitespace_setting,
10287 window,
10288 cx,
10289 );
10290 },
10291 );
10292
10293 window.set_cursor_style(CursorStyle::PointingHand, &line.hitbox);
10294 }
10295 }
10296}
10297
10298impl StickyHeaderLine {
10299 fn new(
10300 row: DisplayRow,
10301 offset: Pixels,
10302 mut line: LineWithInvisibles,
10303 line_number: Option<ShapedLine>,
10304 target_anchor: Anchor,
10305 line_height: Pixels,
10306 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
10307 content_origin: gpui::Point<Pixels>,
10308 gutter_hitbox: &Hitbox,
10309 text_hitbox: &Hitbox,
10310 window: &mut Window,
10311 cx: &mut App,
10312 ) -> Self {
10313 let mut elements = SmallVec::<[AnyElement; 1]>::new();
10314 line.prepaint_with_custom_offset(
10315 line_height,
10316 scroll_pixel_position,
10317 content_origin,
10318 offset,
10319 &mut elements,
10320 window,
10321 cx,
10322 );
10323
10324 let hitbox_bounds = Bounds::new(
10325 gutter_hitbox.origin + point(Pixels::ZERO, offset),
10326 size(text_hitbox.right() - gutter_hitbox.left(), line_height),
10327 );
10328 let available_text_width =
10329 (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
10330
10331 Self {
10332 row,
10333 offset,
10334 line,
10335 line_number,
10336 elements,
10337 available_text_width,
10338 target_anchor,
10339 hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
10340 }
10341 }
10342
10343 fn paint(
10344 &mut self,
10345 layout: &EditorLayout,
10346 gutter_right_padding: Pixels,
10347 available_text_width: Pixels,
10348 content_origin: gpui::Point<Pixels>,
10349 line_height: Pixels,
10350 whitespace_setting: ShowWhitespaceSetting,
10351 window: &mut Window,
10352 cx: &mut App,
10353 ) {
10354 window.with_content_mask(
10355 Some(ContentMask {
10356 bounds: Bounds::new(
10357 layout.position_map.text_hitbox.bounds.origin
10358 + point(Pixels::ZERO, self.offset),
10359 size(available_text_width, line_height),
10360 ),
10361 }),
10362 |window| {
10363 self.line.draw_with_custom_offset(
10364 layout,
10365 self.row,
10366 content_origin,
10367 self.offset,
10368 whitespace_setting,
10369 &[],
10370 window,
10371 cx,
10372 );
10373 for element in &mut self.elements {
10374 element.paint(window, cx);
10375 }
10376 },
10377 );
10378
10379 if let Some(line_number) = &self.line_number {
10380 let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
10381 let gutter_width = layout.gutter_hitbox.size.width;
10382 let origin = point(
10383 gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
10384 gutter_origin.y,
10385 );
10386 line_number.paint(origin, line_height, window, cx).log_err();
10387 }
10388 }
10389}
10390
10391#[derive(Debug)]
10392struct LineNumberSegment {
10393 shaped_line: ShapedLine,
10394 hitbox: Option<Hitbox>,
10395}
10396
10397#[derive(Debug)]
10398struct LineNumberLayout {
10399 segments: SmallVec<[LineNumberSegment; 1]>,
10400}
10401
10402struct ColoredRange<T> {
10403 start: T,
10404 end: T,
10405 color: Hsla,
10406}
10407
10408impl Along for ScrollbarAxes {
10409 type Unit = bool;
10410
10411 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
10412 match axis {
10413 ScrollbarAxis::Horizontal => self.horizontal,
10414 ScrollbarAxis::Vertical => self.vertical,
10415 }
10416 }
10417
10418 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
10419 match axis {
10420 ScrollbarAxis::Horizontal => ScrollbarAxes {
10421 horizontal: f(self.horizontal),
10422 vertical: self.vertical,
10423 },
10424 ScrollbarAxis::Vertical => ScrollbarAxes {
10425 horizontal: self.horizontal,
10426 vertical: f(self.vertical),
10427 },
10428 }
10429 }
10430}
10431
10432#[derive(Clone)]
10433struct EditorScrollbars {
10434 pub vertical: Option<ScrollbarLayout>,
10435 pub horizontal: Option<ScrollbarLayout>,
10436 pub visible: bool,
10437}
10438
10439impl EditorScrollbars {
10440 pub fn from_scrollbar_axes(
10441 show_scrollbar: ScrollbarAxes,
10442 layout_information: &ScrollbarLayoutInformation,
10443 content_offset: gpui::Point<Pixels>,
10444 scroll_position: gpui::Point<f64>,
10445 scrollbar_width: Pixels,
10446 right_margin: Pixels,
10447 editor_width: Pixels,
10448 show_scrollbars: bool,
10449 scrollbar_state: Option<&ActiveScrollbarState>,
10450 window: &mut Window,
10451 ) -> Self {
10452 let ScrollbarLayoutInformation {
10453 editor_bounds,
10454 scroll_range,
10455 glyph_grid_cell,
10456 } = layout_information;
10457
10458 let viewport_size = size(editor_width, editor_bounds.size.height);
10459
10460 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
10461 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
10462 Corner::BottomLeft,
10463 editor_bounds.bottom_left(),
10464 size(
10465 // The horizontal viewport size differs from the space available for the
10466 // horizontal scrollbar, so we have to manually stitch it together here.
10467 editor_bounds.size.width - right_margin,
10468 scrollbar_width,
10469 ),
10470 ),
10471 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
10472 Corner::TopRight,
10473 editor_bounds.top_right(),
10474 size(scrollbar_width, viewport_size.height),
10475 ),
10476 };
10477
10478 let mut create_scrollbar_layout = |axis| {
10479 let viewport_size = viewport_size.along(axis);
10480 let scroll_range = scroll_range.along(axis);
10481
10482 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
10483 (show_scrollbar.along(axis)
10484 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
10485 .then(|| {
10486 ScrollbarLayout::new(
10487 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
10488 viewport_size,
10489 scroll_range,
10490 glyph_grid_cell.along(axis),
10491 content_offset.along(axis),
10492 scroll_position.along(axis),
10493 show_scrollbars,
10494 axis,
10495 )
10496 .with_thumb_state(
10497 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
10498 )
10499 })
10500 };
10501
10502 Self {
10503 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
10504 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
10505 visible: show_scrollbars,
10506 }
10507 }
10508
10509 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
10510 [
10511 (&self.vertical, ScrollbarAxis::Vertical),
10512 (&self.horizontal, ScrollbarAxis::Horizontal),
10513 ]
10514 .into_iter()
10515 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
10516 }
10517
10518 /// Returns the currently hovered scrollbar axis, if any.
10519 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
10520 self.iter_scrollbars()
10521 .find(|s| s.0.hitbox.is_hovered(window))
10522 }
10523}
10524
10525#[derive(Clone)]
10526struct ScrollbarLayout {
10527 hitbox: Hitbox,
10528 visible_range: Range<ScrollOffset>,
10529 text_unit_size: Pixels,
10530 thumb_bounds: Option<Bounds<Pixels>>,
10531 thumb_state: ScrollbarThumbState,
10532}
10533
10534impl ScrollbarLayout {
10535 const BORDER_WIDTH: Pixels = px(1.0);
10536 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
10537 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
10538 const MIN_THUMB_SIZE: Pixels = px(25.0);
10539
10540 fn new(
10541 scrollbar_track_hitbox: Hitbox,
10542 viewport_size: Pixels,
10543 scroll_range: Pixels,
10544 glyph_space: Pixels,
10545 content_offset: Pixels,
10546 scroll_position: ScrollOffset,
10547 show_thumb: bool,
10548 axis: ScrollbarAxis,
10549 ) -> Self {
10550 let track_bounds = scrollbar_track_hitbox.bounds;
10551 // The length of the track available to the scrollbar thumb. We deliberately
10552 // exclude the content size here so that the thumb aligns with the content.
10553 let track_length = track_bounds.size.along(axis) - content_offset;
10554
10555 Self::new_with_hitbox_and_track_length(
10556 scrollbar_track_hitbox,
10557 track_length,
10558 viewport_size,
10559 scroll_range.into(),
10560 glyph_space,
10561 content_offset.into(),
10562 scroll_position,
10563 show_thumb,
10564 axis,
10565 )
10566 }
10567
10568 fn for_minimap(
10569 minimap_track_hitbox: Hitbox,
10570 visible_lines: f64,
10571 total_editor_lines: f64,
10572 minimap_line_height: Pixels,
10573 scroll_position: ScrollOffset,
10574 minimap_scroll_top: ScrollOffset,
10575 show_thumb: bool,
10576 ) -> Self {
10577 // The scrollbar thumb size is calculated as
10578 // (visible_content/total_content) Γ scrollbar_track_length.
10579 //
10580 // For the minimap's thumb layout, we leverage this by setting the
10581 // scrollbar track length to the entire document size (using minimap line
10582 // height). This creates a thumb that exactly represents the editor
10583 // viewport scaled to minimap proportions.
10584 //
10585 // We adjust the thumb position relative to `minimap_scroll_top` to
10586 // accommodate for the deliberately oversized track.
10587 //
10588 // This approach ensures that the minimap thumb accurately reflects the
10589 // editor's current scroll position whilst nicely synchronizing the minimap
10590 // thumb and scrollbar thumb.
10591 let scroll_range = total_editor_lines * f64::from(minimap_line_height);
10592 let viewport_size = visible_lines * f64::from(minimap_line_height);
10593
10594 let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
10595
10596 Self::new_with_hitbox_and_track_length(
10597 minimap_track_hitbox,
10598 Pixels::from(scroll_range),
10599 Pixels::from(viewport_size),
10600 scroll_range,
10601 minimap_line_height,
10602 track_top_offset,
10603 scroll_position,
10604 show_thumb,
10605 ScrollbarAxis::Vertical,
10606 )
10607 }
10608
10609 fn new_with_hitbox_and_track_length(
10610 scrollbar_track_hitbox: Hitbox,
10611 track_length: Pixels,
10612 viewport_size: Pixels,
10613 scroll_range: f64,
10614 glyph_space: Pixels,
10615 content_offset: ScrollOffset,
10616 scroll_position: ScrollOffset,
10617 show_thumb: bool,
10618 axis: ScrollbarAxis,
10619 ) -> Self {
10620 let text_units_per_page = f64::from(viewport_size / glyph_space);
10621 let visible_range = scroll_position..scroll_position + text_units_per_page;
10622 let total_text_units = scroll_range / f64::from(glyph_space);
10623
10624 let thumb_percentage = text_units_per_page / total_text_units;
10625 let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
10626 .max(ScrollbarLayout::MIN_THUMB_SIZE)
10627 .min(track_length);
10628
10629 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
10630
10631 let content_larger_than_viewport = text_unit_divisor > 0.;
10632
10633 let text_unit_size = if content_larger_than_viewport {
10634 Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
10635 } else {
10636 glyph_space
10637 };
10638
10639 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
10640 Self::thumb_bounds(
10641 &scrollbar_track_hitbox,
10642 content_offset,
10643 visible_range.start,
10644 text_unit_size,
10645 thumb_size,
10646 axis,
10647 )
10648 });
10649
10650 ScrollbarLayout {
10651 hitbox: scrollbar_track_hitbox,
10652 visible_range,
10653 text_unit_size,
10654 thumb_bounds,
10655 thumb_state: Default::default(),
10656 }
10657 }
10658
10659 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
10660 if let Some(thumb_state) = thumb_state {
10661 Self {
10662 thumb_state,
10663 ..self
10664 }
10665 } else {
10666 self
10667 }
10668 }
10669
10670 fn thumb_bounds(
10671 scrollbar_track: &Hitbox,
10672 content_offset: f64,
10673 visible_range_start: f64,
10674 text_unit_size: Pixels,
10675 thumb_size: Pixels,
10676 axis: ScrollbarAxis,
10677 ) -> Bounds<Pixels> {
10678 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
10679 origin
10680 + Pixels::from(
10681 content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
10682 )
10683 });
10684 Bounds::new(
10685 thumb_origin,
10686 scrollbar_track.size.apply_along(axis, |_| thumb_size),
10687 )
10688 }
10689
10690 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
10691 self.thumb_bounds
10692 .is_some_and(|bounds| bounds.contains(position))
10693 }
10694
10695 fn marker_quads_for_ranges(
10696 &self,
10697 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
10698 column: Option<usize>,
10699 ) -> Vec<PaintQuad> {
10700 struct MinMax {
10701 min: Pixels,
10702 max: Pixels,
10703 }
10704 let (x_range, height_limit) = if let Some(column) = column {
10705 let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
10706 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
10707 let end = start + column_width;
10708 (
10709 Range { start, end },
10710 MinMax {
10711 min: Self::MIN_MARKER_HEIGHT,
10712 max: px(f32::MAX),
10713 },
10714 )
10715 } else {
10716 (
10717 Range {
10718 start: Self::BORDER_WIDTH,
10719 end: self.hitbox.size.width,
10720 },
10721 MinMax {
10722 min: Self::LINE_MARKER_HEIGHT,
10723 max: Self::LINE_MARKER_HEIGHT,
10724 },
10725 )
10726 };
10727
10728 let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
10729 let mut pixel_ranges = row_ranges
10730 .into_iter()
10731 .map(|range| {
10732 let start_y = row_to_y(range.start);
10733 let end_y = row_to_y(range.end)
10734 + self
10735 .text_unit_size
10736 .max(height_limit.min)
10737 .min(height_limit.max);
10738 ColoredRange {
10739 start: start_y,
10740 end: end_y,
10741 color: range.color,
10742 }
10743 })
10744 .peekable();
10745
10746 let mut quads = Vec::new();
10747 while let Some(mut pixel_range) = pixel_ranges.next() {
10748 while let Some(next_pixel_range) = pixel_ranges.peek() {
10749 if pixel_range.end >= next_pixel_range.start - px(1.0)
10750 && pixel_range.color == next_pixel_range.color
10751 {
10752 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
10753 pixel_ranges.next();
10754 } else {
10755 break;
10756 }
10757 }
10758
10759 let bounds = Bounds::from_corners(
10760 point(x_range.start, pixel_range.start),
10761 point(x_range.end, pixel_range.end),
10762 );
10763 quads.push(quad(
10764 bounds,
10765 Corners::default(),
10766 pixel_range.color,
10767 Edges::default(),
10768 Hsla::transparent_black(),
10769 BorderStyle::default(),
10770 ));
10771 }
10772
10773 quads
10774 }
10775}
10776
10777struct MinimapLayout {
10778 pub minimap: AnyElement,
10779 pub thumb_layout: ScrollbarLayout,
10780 pub minimap_scroll_top: ScrollOffset,
10781 pub minimap_line_height: Pixels,
10782 pub thumb_border_style: MinimapThumbBorder,
10783 pub max_scroll_top: ScrollOffset,
10784}
10785
10786impl MinimapLayout {
10787 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
10788 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
10789 /// The minimap width as a percentage of the editor width.
10790 const MINIMAP_WIDTH_PCT: f32 = 0.15;
10791 /// Calculates the scroll top offset the minimap editor has to have based on the
10792 /// current scroll progress.
10793 fn calculate_minimap_top_offset(
10794 document_lines: f64,
10795 visible_editor_lines: f64,
10796 visible_minimap_lines: f64,
10797 scroll_position: f64,
10798 ) -> ScrollOffset {
10799 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
10800 if non_visible_document_lines == 0. {
10801 0.
10802 } else {
10803 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
10804 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
10805 }
10806 }
10807}
10808
10809struct CreaseTrailerLayout {
10810 element: AnyElement,
10811 bounds: Bounds<Pixels>,
10812}
10813
10814pub(crate) struct PositionMap {
10815 pub size: Size<Pixels>,
10816 pub line_height: Pixels,
10817 pub scroll_position: gpui::Point<ScrollOffset>,
10818 pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
10819 pub scroll_max: gpui::Point<ScrollOffset>,
10820 pub em_width: Pixels,
10821 pub em_advance: Pixels,
10822 pub visible_row_range: Range<DisplayRow>,
10823 pub line_layouts: Vec<LineWithInvisibles>,
10824 pub snapshot: EditorSnapshot,
10825 pub text_hitbox: Hitbox,
10826 pub gutter_hitbox: Hitbox,
10827 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
10828 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10829 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
10830}
10831
10832#[derive(Debug, Copy, Clone)]
10833pub struct PointForPosition {
10834 pub previous_valid: DisplayPoint,
10835 pub next_valid: DisplayPoint,
10836 pub exact_unclipped: DisplayPoint,
10837 pub column_overshoot_after_line_end: u32,
10838}
10839
10840impl PointForPosition {
10841 pub fn as_valid(&self) -> Option<DisplayPoint> {
10842 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
10843 Some(self.previous_valid)
10844 } else {
10845 None
10846 }
10847 }
10848
10849 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
10850 let Some(valid_point) = self.as_valid() else {
10851 return false;
10852 };
10853 let range = selection.range();
10854
10855 let candidate_row = valid_point.row();
10856 let candidate_col = valid_point.column();
10857
10858 let start_row = range.start.row();
10859 let start_col = range.start.column();
10860 let end_row = range.end.row();
10861 let end_col = range.end.column();
10862
10863 if candidate_row < start_row || candidate_row > end_row {
10864 false
10865 } else if start_row == end_row {
10866 candidate_col >= start_col && candidate_col < end_col
10867 } else if candidate_row == start_row {
10868 candidate_col >= start_col
10869 } else if candidate_row == end_row {
10870 candidate_col < end_col
10871 } else {
10872 true
10873 }
10874 }
10875}
10876
10877impl PositionMap {
10878 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
10879 let text_bounds = self.text_hitbox.bounds;
10880 let scroll_position = self.snapshot.scroll_position();
10881 let position = position - text_bounds.origin;
10882 let y = position.y.max(px(0.)).min(self.size.height);
10883 let x = position.x + (scroll_position.x as f32 * self.em_advance);
10884 let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
10885
10886 let (column, x_overshoot_after_line_end) = if let Some(line) = self
10887 .line_layouts
10888 .get(row as usize - scroll_position.y as usize)
10889 {
10890 if let Some(ix) = line.index_for_x(x) {
10891 (ix as u32, px(0.))
10892 } else {
10893 (line.len as u32, px(0.).max(x - line.width))
10894 }
10895 } else {
10896 (0, x)
10897 };
10898
10899 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
10900 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
10901 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
10902
10903 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
10904 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
10905 PointForPosition {
10906 previous_valid,
10907 next_valid,
10908 exact_unclipped,
10909 column_overshoot_after_line_end,
10910 }
10911 }
10912}
10913
10914struct BlockLayout {
10915 id: BlockId,
10916 x_offset: Pixels,
10917 row: Option<DisplayRow>,
10918 element: AnyElement,
10919 available_space: Size<AvailableSpace>,
10920 style: BlockStyle,
10921 overlaps_gutter: bool,
10922 is_buffer_header: bool,
10923}
10924
10925pub fn layout_line(
10926 row: DisplayRow,
10927 snapshot: &EditorSnapshot,
10928 style: &EditorStyle,
10929 text_width: Pixels,
10930 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
10931 window: &mut Window,
10932 cx: &mut App,
10933) -> LineWithInvisibles {
10934 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
10935 LineWithInvisibles::from_chunks(
10936 chunks,
10937 style,
10938 MAX_LINE_LEN,
10939 1,
10940 &snapshot.mode,
10941 text_width,
10942 is_row_soft_wrapped,
10943 &[],
10944 window,
10945 cx,
10946 )
10947 .pop()
10948 .unwrap()
10949}
10950
10951#[derive(Debug)]
10952pub struct IndentGuideLayout {
10953 origin: gpui::Point<Pixels>,
10954 length: Pixels,
10955 single_indent_width: Pixels,
10956 depth: u32,
10957 active: bool,
10958 settings: IndentGuideSettings,
10959}
10960
10961pub struct CursorLayout {
10962 origin: gpui::Point<Pixels>,
10963 block_width: Pixels,
10964 line_height: Pixels,
10965 color: Hsla,
10966 shape: CursorShape,
10967 block_text: Option<ShapedLine>,
10968 cursor_name: Option<AnyElement>,
10969}
10970
10971#[derive(Debug)]
10972pub struct CursorName {
10973 string: SharedString,
10974 color: Hsla,
10975 is_top_row: bool,
10976}
10977
10978impl CursorLayout {
10979 pub fn new(
10980 origin: gpui::Point<Pixels>,
10981 block_width: Pixels,
10982 line_height: Pixels,
10983 color: Hsla,
10984 shape: CursorShape,
10985 block_text: Option<ShapedLine>,
10986 ) -> CursorLayout {
10987 CursorLayout {
10988 origin,
10989 block_width,
10990 line_height,
10991 color,
10992 shape,
10993 block_text,
10994 cursor_name: None,
10995 }
10996 }
10997
10998 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10999 Bounds {
11000 origin: self.origin + origin,
11001 size: size(self.block_width, self.line_height),
11002 }
11003 }
11004
11005 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11006 match self.shape {
11007 CursorShape::Bar => Bounds {
11008 origin: self.origin + origin,
11009 size: size(px(2.0), self.line_height),
11010 },
11011 CursorShape::Block | CursorShape::Hollow => Bounds {
11012 origin: self.origin + origin,
11013 size: size(self.block_width, self.line_height),
11014 },
11015 CursorShape::Underline => Bounds {
11016 origin: self.origin
11017 + origin
11018 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11019 size: size(self.block_width, px(2.0)),
11020 },
11021 }
11022 }
11023
11024 pub fn layout(
11025 &mut self,
11026 origin: gpui::Point<Pixels>,
11027 cursor_name: Option<CursorName>,
11028 window: &mut Window,
11029 cx: &mut App,
11030 ) {
11031 if let Some(cursor_name) = cursor_name {
11032 let bounds = self.bounds(origin);
11033 let text_size = self.line_height / 1.5;
11034
11035 let name_origin = if cursor_name.is_top_row {
11036 point(bounds.right() - px(1.), bounds.top())
11037 } else {
11038 match self.shape {
11039 CursorShape::Bar => point(
11040 bounds.right() - px(2.),
11041 bounds.top() - text_size / 2. - px(1.),
11042 ),
11043 _ => point(
11044 bounds.right() - px(1.),
11045 bounds.top() - text_size / 2. - px(1.),
11046 ),
11047 }
11048 };
11049 let mut name_element = div()
11050 .bg(self.color)
11051 .text_size(text_size)
11052 .px_0p5()
11053 .line_height(text_size + px(2.))
11054 .text_color(cursor_name.color)
11055 .child(cursor_name.string)
11056 .into_any_element();
11057
11058 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11059
11060 self.cursor_name = Some(name_element);
11061 }
11062 }
11063
11064 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11065 let bounds = self.bounds(origin);
11066
11067 //Draw background or border quad
11068 let cursor = if matches!(self.shape, CursorShape::Hollow) {
11069 outline(bounds, self.color, BorderStyle::Solid)
11070 } else {
11071 fill(bounds, self.color)
11072 };
11073
11074 if let Some(name) = &mut self.cursor_name {
11075 name.paint(window, cx);
11076 }
11077
11078 window.paint_quad(cursor);
11079
11080 if let Some(block_text) = &self.block_text {
11081 block_text
11082 .paint(self.origin + origin, self.line_height, window, cx)
11083 .log_err();
11084 }
11085 }
11086
11087 pub fn shape(&self) -> CursorShape {
11088 self.shape
11089 }
11090}
11091
11092#[derive(Debug)]
11093pub struct HighlightedRange {
11094 pub start_y: Pixels,
11095 pub line_height: Pixels,
11096 pub lines: Vec<HighlightedRangeLine>,
11097 pub color: Hsla,
11098 pub corner_radius: Pixels,
11099}
11100
11101#[derive(Debug)]
11102pub struct HighlightedRangeLine {
11103 pub start_x: Pixels,
11104 pub end_x: Pixels,
11105}
11106
11107impl HighlightedRange {
11108 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
11109 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
11110 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
11111 self.paint_lines(
11112 self.start_y + self.line_height,
11113 &self.lines[1..],
11114 fill,
11115 bounds,
11116 window,
11117 );
11118 } else {
11119 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
11120 }
11121 }
11122
11123 fn paint_lines(
11124 &self,
11125 start_y: Pixels,
11126 lines: &[HighlightedRangeLine],
11127 fill: bool,
11128 _bounds: Bounds<Pixels>,
11129 window: &mut Window,
11130 ) {
11131 if lines.is_empty() {
11132 return;
11133 }
11134
11135 let first_line = lines.first().unwrap();
11136 let last_line = lines.last().unwrap();
11137
11138 let first_top_left = point(first_line.start_x, start_y);
11139 let first_top_right = point(first_line.end_x, start_y);
11140
11141 let curve_height = point(Pixels::ZERO, self.corner_radius);
11142 let curve_width = |start_x: Pixels, end_x: Pixels| {
11143 let max = (end_x - start_x) / 2.;
11144 let width = if max < self.corner_radius {
11145 max
11146 } else {
11147 self.corner_radius
11148 };
11149
11150 point(width, Pixels::ZERO)
11151 };
11152
11153 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
11154 let mut builder = if fill {
11155 gpui::PathBuilder::fill()
11156 } else {
11157 gpui::PathBuilder::stroke(px(1.))
11158 };
11159 builder.move_to(first_top_right - top_curve_width);
11160 builder.curve_to(first_top_right + curve_height, first_top_right);
11161
11162 let mut iter = lines.iter().enumerate().peekable();
11163 while let Some((ix, line)) = iter.next() {
11164 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
11165
11166 if let Some((_, next_line)) = iter.peek() {
11167 let next_top_right = point(next_line.end_x, bottom_right.y);
11168
11169 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
11170 Ordering::Equal => {
11171 builder.line_to(bottom_right);
11172 }
11173 Ordering::Less => {
11174 let curve_width = curve_width(next_top_right.x, bottom_right.x);
11175 builder.line_to(bottom_right - curve_height);
11176 if self.corner_radius > Pixels::ZERO {
11177 builder.curve_to(bottom_right - curve_width, bottom_right);
11178 }
11179 builder.line_to(next_top_right + curve_width);
11180 if self.corner_radius > Pixels::ZERO {
11181 builder.curve_to(next_top_right + curve_height, next_top_right);
11182 }
11183 }
11184 Ordering::Greater => {
11185 let curve_width = curve_width(bottom_right.x, next_top_right.x);
11186 builder.line_to(bottom_right - curve_height);
11187 if self.corner_radius > Pixels::ZERO {
11188 builder.curve_to(bottom_right + curve_width, bottom_right);
11189 }
11190 builder.line_to(next_top_right - curve_width);
11191 if self.corner_radius > Pixels::ZERO {
11192 builder.curve_to(next_top_right + curve_height, next_top_right);
11193 }
11194 }
11195 }
11196 } else {
11197 let curve_width = curve_width(line.start_x, line.end_x);
11198 builder.line_to(bottom_right - curve_height);
11199 if self.corner_radius > Pixels::ZERO {
11200 builder.curve_to(bottom_right - curve_width, bottom_right);
11201 }
11202
11203 let bottom_left = point(line.start_x, bottom_right.y);
11204 builder.line_to(bottom_left + curve_width);
11205 if self.corner_radius > Pixels::ZERO {
11206 builder.curve_to(bottom_left - curve_height, bottom_left);
11207 }
11208 }
11209 }
11210
11211 if first_line.start_x > last_line.start_x {
11212 let curve_width = curve_width(last_line.start_x, first_line.start_x);
11213 let second_top_left = point(last_line.start_x, start_y + self.line_height);
11214 builder.line_to(second_top_left + curve_height);
11215 if self.corner_radius > Pixels::ZERO {
11216 builder.curve_to(second_top_left + curve_width, second_top_left);
11217 }
11218 let first_bottom_left = point(first_line.start_x, second_top_left.y);
11219 builder.line_to(first_bottom_left - curve_width);
11220 if self.corner_radius > Pixels::ZERO {
11221 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
11222 }
11223 }
11224
11225 builder.line_to(first_top_left + curve_height);
11226 if self.corner_radius > Pixels::ZERO {
11227 builder.curve_to(first_top_left + top_curve_width, first_top_left);
11228 }
11229 builder.line_to(first_top_right - top_curve_width);
11230
11231 if let Ok(path) = builder.build() {
11232 window.paint_path(path, self.color);
11233 }
11234 }
11235}
11236
11237pub(crate) struct StickyHeader {
11238 pub item: language::OutlineItem<Anchor>,
11239 pub sticky_row: DisplayRow,
11240 pub start_point: Point,
11241 pub offset: ScrollOffset,
11242}
11243
11244enum CursorPopoverType {
11245 CodeContextMenu,
11246 EditPrediction,
11247}
11248
11249pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11250 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
11251}
11252
11253fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11254 (delta.pow(1.2) / 300.0).into()
11255}
11256
11257pub fn register_action<T: Action>(
11258 editor: &Entity<Editor>,
11259 window: &mut Window,
11260 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
11261) {
11262 let editor = editor.clone();
11263 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
11264 let action = action.downcast_ref().unwrap();
11265 if phase == DispatchPhase::Bubble {
11266 editor.update(cx, |editor, cx| {
11267 listener(editor, action, window, cx);
11268 })
11269 }
11270 })
11271}
11272
11273fn compute_auto_height_layout(
11274 editor: &mut Editor,
11275 min_lines: usize,
11276 max_lines: Option<usize>,
11277 max_line_number_width: Pixels,
11278 known_dimensions: Size<Option<Pixels>>,
11279 available_width: AvailableSpace,
11280 window: &mut Window,
11281 cx: &mut Context<Editor>,
11282) -> Option<Size<Pixels>> {
11283 let width = known_dimensions.width.or({
11284 if let AvailableSpace::Definite(available_width) = available_width {
11285 Some(available_width)
11286 } else {
11287 None
11288 }
11289 })?;
11290 if let Some(height) = known_dimensions.height {
11291 return Some(size(width, height));
11292 }
11293
11294 let style = editor.style.as_ref().unwrap();
11295 let font_id = window.text_system().resolve_font(&style.text.font());
11296 let font_size = style.text.font_size.to_pixels(window.rem_size());
11297 let line_height = style.text.line_height_in_pixels(window.rem_size());
11298 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
11299
11300 let mut snapshot = editor.snapshot(window, cx);
11301 let gutter_dimensions = snapshot
11302 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
11303 .or_else(|| {
11304 editor
11305 .offset_content
11306 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
11307 })
11308 .unwrap_or_default();
11309
11310 editor.gutter_dimensions = gutter_dimensions;
11311 let text_width = width - gutter_dimensions.width;
11312 let overscroll = size(em_width, px(0.));
11313
11314 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
11315 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
11316 && editor.set_wrap_width(Some(editor_width), cx)
11317 {
11318 snapshot = editor.snapshot(window, cx);
11319 }
11320
11321 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
11322
11323 let min_height = line_height * min_lines as f32;
11324 let content_height = scroll_height.max(min_height);
11325
11326 let final_height = if let Some(max_lines) = max_lines {
11327 let max_height = line_height * max_lines as f32;
11328 content_height.min(max_height)
11329 } else {
11330 content_height
11331 };
11332
11333 Some(size(width, final_height))
11334}
11335
11336#[cfg(test)]
11337mod tests {
11338 use super::*;
11339 use crate::{
11340 Editor, MultiBuffer, SelectionEffects,
11341 display_map::{BlockPlacement, BlockProperties},
11342 editor_tests::{init_test, update_test_language_settings},
11343 };
11344 use gpui::{TestAppContext, VisualTestContext};
11345 use language::language_settings;
11346 use log::info;
11347 use std::num::NonZeroU32;
11348 use util::test::sample_text;
11349
11350 #[gpui::test]
11351 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
11352 init_test(cx, |_| {});
11353
11354 let window = cx.add_window(|window, cx| {
11355 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11356 let mut editor = Editor::new(
11357 EditorMode::AutoHeight {
11358 min_lines: 1,
11359 max_lines: None,
11360 },
11361 buffer,
11362 None,
11363 window,
11364 cx,
11365 );
11366 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11367 editor
11368 });
11369 let cx = &mut VisualTestContext::from_window(*window, cx);
11370 let editor = window.root(cx).unwrap();
11371 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
11372
11373 for x in 1..=100 {
11374 let (_, state) = cx.draw(
11375 Default::default(),
11376 size(px(200. + 0.13 * x as f32), px(500.)),
11377 |_, _| EditorElement::new(&editor, style.clone()),
11378 );
11379
11380 assert!(
11381 state.position_map.scroll_max.x == 0.,
11382 "Soft wrapped editor should have no horizontal scrolling!"
11383 );
11384 }
11385 }
11386
11387 #[gpui::test]
11388 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
11389 init_test(cx, |_| {});
11390
11391 let window = cx.add_window(|window, cx| {
11392 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11393 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
11394 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11395 editor
11396 });
11397 let cx = &mut VisualTestContext::from_window(*window, cx);
11398 let editor = window.root(cx).unwrap();
11399 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
11400
11401 for x in 1..=100 {
11402 let (_, state) = cx.draw(
11403 Default::default(),
11404 size(px(200. + 0.13 * x as f32), px(500.)),
11405 |_, _| EditorElement::new(&editor, style.clone()),
11406 );
11407
11408 assert!(
11409 state.position_map.scroll_max.x == 0.,
11410 "Soft wrapped editor should have no horizontal scrolling!"
11411 );
11412 }
11413 }
11414
11415 #[gpui::test]
11416 fn test_shape_line_numbers(cx: &mut TestAppContext) {
11417 init_test(cx, |_| {});
11418 let window = cx.add_window(|window, cx| {
11419 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
11420 Editor::new(EditorMode::full(), buffer, None, window, cx)
11421 });
11422
11423 let editor = window.root(cx).unwrap();
11424 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
11425 let line_height = window
11426 .update(cx, |_, window, _| {
11427 style.text.line_height_in_pixels(window.rem_size())
11428 })
11429 .unwrap();
11430 let element = EditorElement::new(&editor, style);
11431 let snapshot = window
11432 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
11433 .unwrap();
11434
11435 let layouts = cx
11436 .update_window(*window, |_, window, cx| {
11437 element.layout_line_numbers(
11438 None,
11439 GutterDimensions {
11440 left_padding: Pixels::ZERO,
11441 right_padding: Pixels::ZERO,
11442 width: px(30.0),
11443 margin: Pixels::ZERO,
11444 git_blame_entries_width: None,
11445 },
11446 line_height,
11447 gpui::Point::default(),
11448 DisplayRow(0)..DisplayRow(6),
11449 &(0..6)
11450 .map(|row| RowInfo {
11451 buffer_row: Some(row),
11452 ..Default::default()
11453 })
11454 .collect::<Vec<_>>(),
11455 &BTreeMap::default(),
11456 Some(DisplayPoint::new(DisplayRow(0), 0)),
11457 &snapshot,
11458 window,
11459 cx,
11460 )
11461 })
11462 .unwrap();
11463 assert_eq!(layouts.len(), 6);
11464
11465 let relative_rows = window
11466 .update(cx, |editor, window, cx| {
11467 let snapshot = editor.snapshot(window, cx);
11468 element.calculate_relative_line_numbers(
11469 &snapshot,
11470 &(DisplayRow(0)..DisplayRow(6)),
11471 Some(DisplayRow(3)),
11472 false,
11473 )
11474 })
11475 .unwrap();
11476 assert_eq!(relative_rows[&DisplayRow(0)], 3);
11477 assert_eq!(relative_rows[&DisplayRow(1)], 2);
11478 assert_eq!(relative_rows[&DisplayRow(2)], 1);
11479 // current line has no relative number
11480 assert_eq!(relative_rows[&DisplayRow(4)], 1);
11481 assert_eq!(relative_rows[&DisplayRow(5)], 2);
11482
11483 // works if cursor is before screen
11484 let relative_rows = window
11485 .update(cx, |editor, window, cx| {
11486 let snapshot = editor.snapshot(window, cx);
11487 element.calculate_relative_line_numbers(
11488 &snapshot,
11489 &(DisplayRow(3)..DisplayRow(6)),
11490 Some(DisplayRow(1)),
11491 false,
11492 )
11493 })
11494 .unwrap();
11495 assert_eq!(relative_rows.len(), 3);
11496 assert_eq!(relative_rows[&DisplayRow(3)], 2);
11497 assert_eq!(relative_rows[&DisplayRow(4)], 3);
11498 assert_eq!(relative_rows[&DisplayRow(5)], 4);
11499
11500 // works if cursor is after screen
11501 let relative_rows = window
11502 .update(cx, |editor, window, cx| {
11503 let snapshot = editor.snapshot(window, cx);
11504 element.calculate_relative_line_numbers(
11505 &snapshot,
11506 &(DisplayRow(0)..DisplayRow(3)),
11507 Some(DisplayRow(6)),
11508 false,
11509 )
11510 })
11511 .unwrap();
11512 assert_eq!(relative_rows.len(), 3);
11513 assert_eq!(relative_rows[&DisplayRow(0)], 5);
11514 assert_eq!(relative_rows[&DisplayRow(1)], 4);
11515 assert_eq!(relative_rows[&DisplayRow(2)], 3);
11516
11517 const DELETED_LINE: u32 = 3;
11518 let layouts = cx
11519 .update_window(*window, |_, window, cx| {
11520 element.layout_line_numbers(
11521 None,
11522 GutterDimensions {
11523 left_padding: Pixels::ZERO,
11524 right_padding: Pixels::ZERO,
11525 width: px(30.0),
11526 margin: Pixels::ZERO,
11527 git_blame_entries_width: None,
11528 },
11529 line_height,
11530 gpui::Point::default(),
11531 DisplayRow(0)..DisplayRow(6),
11532 &(0..6)
11533 .map(|row| RowInfo {
11534 buffer_row: Some(row),
11535 diff_status: (row == DELETED_LINE).then(|| {
11536 DiffHunkStatus::deleted(
11537 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
11538 )
11539 }),
11540 ..Default::default()
11541 })
11542 .collect::<Vec<_>>(),
11543 &BTreeMap::default(),
11544 Some(DisplayPoint::new(DisplayRow(0), 0)),
11545 &snapshot,
11546 window,
11547 cx,
11548 )
11549 })
11550 .unwrap();
11551 assert_eq!(layouts.len(), 5,);
11552 assert!(
11553 layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
11554 "Deleted line should not have a line number"
11555 );
11556 }
11557
11558 #[gpui::test]
11559 fn test_shape_line_numbers_wrapping(cx: &mut TestAppContext) {
11560 init_test(cx, |_| {});
11561 let window = cx.add_window(|window, cx| {
11562 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
11563 Editor::new(EditorMode::full(), buffer, None, window, cx)
11564 });
11565
11566 update_test_language_settings(cx, |s| {
11567 s.defaults.preferred_line_length = Some(5_u32);
11568 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
11569 });
11570
11571 let editor = window.root(cx).unwrap();
11572 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
11573 let line_height = window
11574 .update(cx, |_, window, _| {
11575 style.text.line_height_in_pixels(window.rem_size())
11576 })
11577 .unwrap();
11578 let element = EditorElement::new(&editor, style);
11579 let snapshot = window
11580 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
11581 .unwrap();
11582
11583 let layouts = cx
11584 .update_window(*window, |_, window, cx| {
11585 element.layout_line_numbers(
11586 None,
11587 GutterDimensions {
11588 left_padding: Pixels::ZERO,
11589 right_padding: Pixels::ZERO,
11590 width: px(30.0),
11591 margin: Pixels::ZERO,
11592 git_blame_entries_width: None,
11593 },
11594 line_height,
11595 gpui::Point::default(),
11596 DisplayRow(0)..DisplayRow(6),
11597 &(0..6)
11598 .map(|row| RowInfo {
11599 buffer_row: Some(row),
11600 ..Default::default()
11601 })
11602 .collect::<Vec<_>>(),
11603 &BTreeMap::default(),
11604 Some(DisplayPoint::new(DisplayRow(0), 0)),
11605 &snapshot,
11606 window,
11607 cx,
11608 )
11609 })
11610 .unwrap();
11611 assert_eq!(layouts.len(), 3);
11612
11613 let relative_rows = window
11614 .update(cx, |editor, window, cx| {
11615 let snapshot = editor.snapshot(window, cx);
11616 element.calculate_relative_line_numbers(
11617 &snapshot,
11618 &(DisplayRow(0)..DisplayRow(6)),
11619 Some(DisplayRow(3)),
11620 true,
11621 )
11622 })
11623 .unwrap();
11624
11625 assert_eq!(relative_rows[&DisplayRow(0)], 3);
11626 assert_eq!(relative_rows[&DisplayRow(1)], 2);
11627 assert_eq!(relative_rows[&DisplayRow(2)], 1);
11628 // current line has no relative number
11629 assert_eq!(relative_rows[&DisplayRow(4)], 1);
11630 assert_eq!(relative_rows[&DisplayRow(5)], 2);
11631
11632 let layouts = cx
11633 .update_window(*window, |_, window, cx| {
11634 element.layout_line_numbers(
11635 None,
11636 GutterDimensions {
11637 left_padding: Pixels::ZERO,
11638 right_padding: Pixels::ZERO,
11639 width: px(30.0),
11640 margin: Pixels::ZERO,
11641 git_blame_entries_width: None,
11642 },
11643 line_height,
11644 gpui::Point::default(),
11645 DisplayRow(0)..DisplayRow(6),
11646 &(0..6)
11647 .map(|row| RowInfo {
11648 buffer_row: Some(row),
11649 diff_status: Some(DiffHunkStatus::deleted(
11650 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
11651 )),
11652 ..Default::default()
11653 })
11654 .collect::<Vec<_>>(),
11655 &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
11656 Some(DisplayPoint::new(DisplayRow(0), 0)),
11657 &snapshot,
11658 window,
11659 cx,
11660 )
11661 })
11662 .unwrap();
11663 assert!(
11664 layouts.is_empty(),
11665 "Deleted lines should have no line number"
11666 );
11667
11668 let relative_rows = window
11669 .update(cx, |editor, window, cx| {
11670 let snapshot = editor.snapshot(window, cx);
11671 element.calculate_relative_line_numbers(
11672 &snapshot,
11673 &(DisplayRow(0)..DisplayRow(6)),
11674 Some(DisplayRow(3)),
11675 true,
11676 )
11677 })
11678 .unwrap();
11679
11680 // Deleted lines should still have relative numbers
11681 assert_eq!(relative_rows[&DisplayRow(0)], 3);
11682 assert_eq!(relative_rows[&DisplayRow(1)], 2);
11683 assert_eq!(relative_rows[&DisplayRow(2)], 1);
11684 // current line, even if deleted, has no relative number
11685 assert_eq!(relative_rows[&DisplayRow(4)], 1);
11686 assert_eq!(relative_rows[&DisplayRow(5)], 2);
11687 }
11688
11689 #[gpui::test]
11690 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
11691 init_test(cx, |_| {});
11692
11693 let window = cx.add_window(|window, cx| {
11694 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
11695 Editor::new(EditorMode::full(), buffer, None, window, cx)
11696 });
11697 let cx = &mut VisualTestContext::from_window(*window, cx);
11698 let editor = window.root(cx).unwrap();
11699 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
11700
11701 window
11702 .update(cx, |editor, window, cx| {
11703 editor.cursor_shape = CursorShape::Block;
11704 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
11705 s.select_ranges([
11706 Point::new(0, 0)..Point::new(1, 0),
11707 Point::new(3, 2)..Point::new(3, 3),
11708 Point::new(5, 6)..Point::new(6, 0),
11709 ]);
11710 });
11711 })
11712 .unwrap();
11713
11714 let (_, state) = cx.draw(
11715 point(px(500.), px(500.)),
11716 size(px(500.), px(500.)),
11717 |_, _| EditorElement::new(&editor, style),
11718 );
11719
11720 assert_eq!(state.selections.len(), 1);
11721 let local_selections = &state.selections[0].1;
11722 assert_eq!(local_selections.len(), 3);
11723 // moves cursor back one line
11724 assert_eq!(
11725 local_selections[0].head,
11726 DisplayPoint::new(DisplayRow(0), 6)
11727 );
11728 assert_eq!(
11729 local_selections[0].range,
11730 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
11731 );
11732
11733 // moves cursor back one column
11734 assert_eq!(
11735 local_selections[1].range,
11736 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
11737 );
11738 assert_eq!(
11739 local_selections[1].head,
11740 DisplayPoint::new(DisplayRow(3), 2)
11741 );
11742
11743 // leaves cursor on the max point
11744 assert_eq!(
11745 local_selections[2].range,
11746 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
11747 );
11748 assert_eq!(
11749 local_selections[2].head,
11750 DisplayPoint::new(DisplayRow(6), 0)
11751 );
11752
11753 // active lines does not include 1 (even though the range of the selection does)
11754 assert_eq!(
11755 state.active_rows.keys().cloned().collect::<Vec<_>>(),
11756 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
11757 );
11758 }
11759
11760 #[gpui::test]
11761 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
11762 init_test(cx, |_| {});
11763
11764 let window = cx.add_window(|window, cx| {
11765 let buffer = MultiBuffer::build_simple("", cx);
11766 Editor::new(EditorMode::full(), buffer, None, window, cx)
11767 });
11768 let cx = &mut VisualTestContext::from_window(*window, cx);
11769 let editor = window.root(cx).unwrap();
11770 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
11771 window
11772 .update(cx, |editor, window, cx| {
11773 editor.set_placeholder_text("hello", window, cx);
11774 editor.insert_blocks(
11775 [BlockProperties {
11776 style: BlockStyle::Fixed,
11777 placement: BlockPlacement::Above(Anchor::min()),
11778 height: Some(3),
11779 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
11780 priority: 0,
11781 }],
11782 None,
11783 cx,
11784 );
11785
11786 // Blur the editor so that it displays placeholder text.
11787 window.blur();
11788 })
11789 .unwrap();
11790
11791 let (_, state) = cx.draw(
11792 point(px(500.), px(500.)),
11793 size(px(500.), px(500.)),
11794 |_, _| EditorElement::new(&editor, style),
11795 );
11796 assert_eq!(state.position_map.line_layouts.len(), 4);
11797 assert_eq!(state.line_numbers.len(), 1);
11798 assert_eq!(
11799 state
11800 .line_numbers
11801 .get(&MultiBufferRow(0))
11802 .map(|line_number| line_number
11803 .segments
11804 .first()
11805 .unwrap()
11806 .shaped_line
11807 .text
11808 .as_ref()),
11809 Some("1")
11810 );
11811 }
11812
11813 #[gpui::test]
11814 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
11815 const TAB_SIZE: u32 = 4;
11816
11817 let input_text = "\t \t|\t| a b";
11818 let expected_invisibles = vec![
11819 Invisible::Tab {
11820 line_start_offset: 0,
11821 line_end_offset: TAB_SIZE as usize,
11822 },
11823 Invisible::Whitespace {
11824 line_offset: TAB_SIZE as usize,
11825 },
11826 Invisible::Tab {
11827 line_start_offset: TAB_SIZE as usize + 1,
11828 line_end_offset: TAB_SIZE as usize * 2,
11829 },
11830 Invisible::Tab {
11831 line_start_offset: TAB_SIZE as usize * 2 + 1,
11832 line_end_offset: TAB_SIZE as usize * 3,
11833 },
11834 Invisible::Whitespace {
11835 line_offset: TAB_SIZE as usize * 3 + 1,
11836 },
11837 Invisible::Whitespace {
11838 line_offset: TAB_SIZE as usize * 3 + 3,
11839 },
11840 ];
11841 assert_eq!(
11842 expected_invisibles.len(),
11843 input_text
11844 .chars()
11845 .filter(|initial_char| initial_char.is_whitespace())
11846 .count(),
11847 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
11848 );
11849
11850 for show_line_numbers in [true, false] {
11851 init_test(cx, |s| {
11852 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
11853 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
11854 });
11855
11856 let actual_invisibles = collect_invisibles_from_new_editor(
11857 cx,
11858 EditorMode::full(),
11859 input_text,
11860 px(500.0),
11861 show_line_numbers,
11862 );
11863
11864 assert_eq!(expected_invisibles, actual_invisibles);
11865 }
11866 }
11867
11868 #[gpui::test]
11869 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
11870 init_test(cx, |s| {
11871 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
11872 s.defaults.tab_size = NonZeroU32::new(4);
11873 });
11874
11875 for editor_mode_without_invisibles in [
11876 EditorMode::SingleLine,
11877 EditorMode::AutoHeight {
11878 min_lines: 1,
11879 max_lines: Some(100),
11880 },
11881 ] {
11882 for show_line_numbers in [true, false] {
11883 let invisibles = collect_invisibles_from_new_editor(
11884 cx,
11885 editor_mode_without_invisibles.clone(),
11886 "\t\t\t| | a b",
11887 px(500.0),
11888 show_line_numbers,
11889 );
11890 assert!(
11891 invisibles.is_empty(),
11892 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
11893 );
11894 }
11895 }
11896 }
11897
11898 #[gpui::test]
11899 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
11900 let tab_size = 4;
11901 let input_text = "a\tbcd ".repeat(9);
11902 let repeated_invisibles = [
11903 Invisible::Tab {
11904 line_start_offset: 1,
11905 line_end_offset: tab_size as usize,
11906 },
11907 Invisible::Whitespace {
11908 line_offset: tab_size as usize + 3,
11909 },
11910 Invisible::Whitespace {
11911 line_offset: tab_size as usize + 4,
11912 },
11913 Invisible::Whitespace {
11914 line_offset: tab_size as usize + 5,
11915 },
11916 Invisible::Whitespace {
11917 line_offset: tab_size as usize + 6,
11918 },
11919 Invisible::Whitespace {
11920 line_offset: tab_size as usize + 7,
11921 },
11922 ];
11923 let expected_invisibles = std::iter::once(repeated_invisibles)
11924 .cycle()
11925 .take(9)
11926 .flatten()
11927 .collect::<Vec<_>>();
11928 assert_eq!(
11929 expected_invisibles.len(),
11930 input_text
11931 .chars()
11932 .filter(|initial_char| initial_char.is_whitespace())
11933 .count(),
11934 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
11935 );
11936 info!("Expected invisibles: {expected_invisibles:?}");
11937
11938 init_test(cx, |_| {});
11939
11940 // Put the same string with repeating whitespace pattern into editors of various size,
11941 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
11942 let resize_step = 10.0;
11943 let mut editor_width = 200.0;
11944 while editor_width <= 1000.0 {
11945 for show_line_numbers in [true, false] {
11946 update_test_language_settings(cx, |s| {
11947 s.defaults.tab_size = NonZeroU32::new(tab_size);
11948 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
11949 s.defaults.preferred_line_length = Some(editor_width as u32);
11950 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
11951 });
11952
11953 let actual_invisibles = collect_invisibles_from_new_editor(
11954 cx,
11955 EditorMode::full(),
11956 &input_text,
11957 px(editor_width),
11958 show_line_numbers,
11959 );
11960
11961 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
11962 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
11963 let mut i = 0;
11964 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
11965 i = actual_index;
11966 match expected_invisibles.get(i) {
11967 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
11968 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
11969 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
11970 _ => {
11971 panic!(
11972 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
11973 )
11974 }
11975 },
11976 None => {
11977 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
11978 }
11979 }
11980 }
11981 let missing_expected_invisibles = &expected_invisibles[i + 1..];
11982 assert!(
11983 missing_expected_invisibles.is_empty(),
11984 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
11985 );
11986
11987 editor_width += resize_step;
11988 }
11989 }
11990 }
11991
11992 fn collect_invisibles_from_new_editor(
11993 cx: &mut TestAppContext,
11994 editor_mode: EditorMode,
11995 input_text: &str,
11996 editor_width: Pixels,
11997 show_line_numbers: bool,
11998 ) -> Vec<Invisible> {
11999 info!(
12000 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
12001 f32::from(editor_width)
12002 );
12003 let window = cx.add_window(|window, cx| {
12004 let buffer = MultiBuffer::build_simple(input_text, cx);
12005 Editor::new(editor_mode, buffer, None, window, cx)
12006 });
12007 let cx = &mut VisualTestContext::from_window(*window, cx);
12008 let editor = window.root(cx).unwrap();
12009
12010 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
12011 window
12012 .update(cx, |editor, _, cx| {
12013 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12014 editor.set_wrap_width(Some(editor_width), cx);
12015 editor.set_show_line_numbers(show_line_numbers, cx);
12016 })
12017 .unwrap();
12018 let (_, state) = cx.draw(
12019 point(px(500.), px(500.)),
12020 size(px(500.), px(500.)),
12021 |_, _| EditorElement::new(&editor, style),
12022 );
12023 state
12024 .position_map
12025 .line_layouts
12026 .iter()
12027 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
12028 .cloned()
12029 .collect()
12030 }
12031
12032 #[gpui::test]
12033 fn test_merge_overlapping_ranges() {
12034 let base_bg = Hsla::white();
12035 let color1 = Hsla {
12036 h: 0.0,
12037 s: 0.5,
12038 l: 0.5,
12039 a: 0.5,
12040 };
12041 let color2 = Hsla {
12042 h: 120.0,
12043 s: 0.5,
12044 l: 0.5,
12045 a: 0.5,
12046 };
12047
12048 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
12049 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
12050 v.iter()
12051 .map(|(r, _)| (r.start.column(), r.end.column()))
12052 .collect()
12053 };
12054
12055 // Test overlapping ranges blend colors
12056 let overlapping = vec![
12057 (display_point(5)..display_point(15), color1),
12058 (display_point(10)..display_point(20), color2),
12059 ];
12060 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
12061 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12062
12063 // Test middle segment should have blended color
12064 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
12065 assert_eq!(result[1].1, blended);
12066
12067 // Test adjacent same-color ranges merge
12068 let adjacent_same = vec![
12069 (display_point(5)..display_point(10), color1),
12070 (display_point(10)..display_point(15), color1),
12071 ];
12072 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
12073 assert_eq!(cols(&result), vec![(5, 15)]);
12074
12075 // Test contained range splits
12076 let contained = vec![
12077 (display_point(5)..display_point(20), color1),
12078 (display_point(10)..display_point(15), color2),
12079 ];
12080 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
12081 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12082
12083 // Test multiple overlaps split at every boundary
12084 let color3 = Hsla {
12085 h: 240.0,
12086 s: 0.5,
12087 l: 0.5,
12088 a: 0.5,
12089 };
12090 let complex = vec![
12091 (display_point(5)..display_point(12), color1),
12092 (display_point(8)..display_point(16), color2),
12093 (display_point(10)..display_point(14), color3),
12094 ];
12095 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
12096 assert_eq!(
12097 cols(&result),
12098 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
12099 );
12100 }
12101
12102 #[gpui::test]
12103 fn test_bg_segments_per_row() {
12104 let base_bg = Hsla::white();
12105
12106 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
12107 {
12108 let selection_color = Hsla {
12109 h: 200.0,
12110 s: 0.5,
12111 l: 0.5,
12112 a: 0.5,
12113 };
12114 let player_color = PlayerColor {
12115 cursor: selection_color,
12116 background: selection_color,
12117 selection: selection_color,
12118 };
12119
12120 let spanning_selection = SelectionLayout {
12121 head: DisplayPoint::new(DisplayRow(3), 7),
12122 cursor_shape: CursorShape::Bar,
12123 is_newest: true,
12124 is_local: true,
12125 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
12126 active_rows: DisplayRow(1)..DisplayRow(4),
12127 user_name: None,
12128 };
12129
12130 let selections = vec![(player_color, vec![spanning_selection])];
12131 let result = EditorElement::bg_segments_per_row(
12132 DisplayRow(0)..DisplayRow(5),
12133 &selections,
12134 &[],
12135 base_bg,
12136 );
12137
12138 assert_eq!(result.len(), 5);
12139 assert!(result[0].is_empty());
12140 assert_eq!(result[1].len(), 1);
12141 assert_eq!(result[2].len(), 1);
12142 assert_eq!(result[3].len(), 1);
12143 assert!(result[4].is_empty());
12144
12145 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12146 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12147 assert_eq!(result[1][0].0.end.column(), u32::MAX);
12148 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12149 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12150 assert_eq!(result[2][0].0.end.column(), u32::MAX);
12151 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
12152 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
12153 }
12154
12155 // Case B: selection ends exactly at the start of row 3, excluding row 3
12156 {
12157 let selection_color = Hsla {
12158 h: 120.0,
12159 s: 0.5,
12160 l: 0.5,
12161 a: 0.5,
12162 };
12163 let player_color = PlayerColor {
12164 cursor: selection_color,
12165 background: selection_color,
12166 selection: selection_color,
12167 };
12168
12169 let selection = SelectionLayout {
12170 head: DisplayPoint::new(DisplayRow(2), 0),
12171 cursor_shape: CursorShape::Bar,
12172 is_newest: true,
12173 is_local: true,
12174 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
12175 active_rows: DisplayRow(1)..DisplayRow(3),
12176 user_name: None,
12177 };
12178
12179 let selections = vec![(player_color, vec![selection])];
12180 let result = EditorElement::bg_segments_per_row(
12181 DisplayRow(0)..DisplayRow(4),
12182 &selections,
12183 &[],
12184 base_bg,
12185 );
12186
12187 assert_eq!(result.len(), 4);
12188 assert!(result[0].is_empty());
12189 assert_eq!(result[1].len(), 1);
12190 assert_eq!(result[2].len(), 1);
12191 assert!(result[3].is_empty());
12192
12193 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12194 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12195 assert_eq!(result[1][0].0.end.column(), u32::MAX);
12196 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12197 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12198 assert_eq!(result[2][0].0.end.column(), u32::MAX);
12199 }
12200 }
12201
12202 #[cfg(test)]
12203 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
12204 TextRun {
12205 len,
12206 color,
12207 ..Default::default()
12208 }
12209 }
12210
12211 #[gpui::test]
12212 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
12213 init_test(cx, |_| {});
12214
12215 let dx = |start: u32, end: u32| {
12216 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
12217 };
12218
12219 let text_color = Hsla {
12220 h: 210.0,
12221 s: 0.1,
12222 l: 0.4,
12223 a: 1.0,
12224 };
12225 let bg_1 = Hsla {
12226 h: 30.0,
12227 s: 0.6,
12228 l: 0.8,
12229 a: 1.0,
12230 };
12231 let bg_2 = Hsla {
12232 h: 200.0,
12233 s: 0.6,
12234 l: 0.2,
12235 a: 1.0,
12236 };
12237 let min_contrast = 45.0;
12238 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
12239 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
12240
12241 // Case A: single run; disjoint segments inside the run
12242 {
12243 let runs = vec![generate_test_run(20, text_color)];
12244 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
12245 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12246 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
12247 assert_eq!(
12248 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12249 vec![5, 5, 2, 4, 4]
12250 );
12251 assert_eq!(out[0].color, text_color);
12252 assert_eq!(out[1].color, adjusted_bg1);
12253 assert_eq!(out[2].color, text_color);
12254 assert_eq!(out[3].color, adjusted_bg2);
12255 assert_eq!(out[4].color, text_color);
12256 }
12257
12258 // Case B: multiple runs; segment extends to end of line (u32::MAX)
12259 {
12260 let runs = vec![
12261 generate_test_run(8, text_color),
12262 generate_test_run(7, text_color),
12263 ];
12264 let segs = vec![(dx(6, u32::MAX), bg_1)];
12265 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12266 // Expected slices across runs: [0,6) [6,8) | [0,7)
12267 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
12268 assert_eq!(out[0].color, text_color);
12269 assert_eq!(out[1].color, adjusted_bg1);
12270 assert_eq!(out[2].color, adjusted_bg1);
12271 }
12272
12273 // Case C: multi-byte characters
12274 {
12275 // for text: "Hello π δΈη!"
12276 let runs = vec![
12277 generate_test_run(5, text_color), // "Hello"
12278 generate_test_run(6, text_color), // " π "
12279 generate_test_run(6, text_color), // "δΈη"
12280 generate_test_run(1, text_color), // "!"
12281 ];
12282 // selecting "π δΈ"
12283 let segs = vec![(dx(6, 14), bg_1)];
12284 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12285 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
12286 assert_eq!(
12287 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12288 vec![5, 1, 5, 3, 3, 1]
12289 );
12290 assert_eq!(out[0].color, text_color); // "Hello"
12291 assert_eq!(out[2].color, adjusted_bg1); // "π "
12292 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
12293 assert_eq!(out[4].color, text_color); // "η"
12294 assert_eq!(out[5].color, text_color); // "!"
12295 }
12296
12297 // Case D: split multiple consecutive text runs with segments
12298 {
12299 let segs = vec![
12300 (dx(2, 4), bg_1), // selecting "cd"
12301 (dx(4, 8), bg_2), // selecting "efgh"
12302 (dx(9, 11), bg_1), // selecting "jk"
12303 (dx(12, 16), bg_2), // selecting "mnop"
12304 (dx(18, 19), bg_1), // selecting "s"
12305 ];
12306
12307 // for text: "abcdef"
12308 let runs = vec![
12309 generate_test_run(2, text_color), // ab
12310 generate_test_run(4, text_color), // cdef
12311 ];
12312 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12313 // new splits "ab", "cd", "ef"
12314 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
12315 assert_eq!(out[0].color, text_color);
12316 assert_eq!(out[1].color, adjusted_bg1);
12317 assert_eq!(out[2].color, adjusted_bg2);
12318
12319 // for text: "ghijklmn"
12320 let runs = vec![
12321 generate_test_run(3, text_color), // ghi
12322 generate_test_run(2, text_color), // jk
12323 generate_test_run(3, text_color), // lmn
12324 ];
12325 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
12326 // new splits "gh", "i", "jk", "l", "mn"
12327 assert_eq!(
12328 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12329 vec![2, 1, 2, 1, 2]
12330 );
12331 assert_eq!(out[0].color, adjusted_bg2);
12332 assert_eq!(out[1].color, text_color);
12333 assert_eq!(out[2].color, adjusted_bg1);
12334 assert_eq!(out[3].color, text_color);
12335 assert_eq!(out[4].color, adjusted_bg2);
12336
12337 // for text: "opqrs"
12338 let runs = vec![
12339 generate_test_run(1, text_color), // o
12340 generate_test_run(4, text_color), // pqrs
12341 ];
12342 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
12343 // new splits "o", "p", "qr", "s"
12344 assert_eq!(
12345 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12346 vec![1, 1, 2, 1]
12347 );
12348 assert_eq!(out[0].color, adjusted_bg2);
12349 assert_eq!(out[1].color, adjusted_bg2);
12350 assert_eq!(out[2].color, text_color);
12351 assert_eq!(out[3].color, adjusted_bg1);
12352 }
12353 }
12354}