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