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