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