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