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