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