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