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