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