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, FontWeight,
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, StyledText, TextAlign, TextRun,
50 TextStyleRefinement, WeakEntity, Window, anchored, deferred, div, fill, linear_color_stop,
51 linear_gradient, outline, 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, ItemHandle, ItemSettings, OpenInTerminal, OpenTerminal, RevealInProjectPanel,
98 Workspace,
99 item::{BreadcrumbText, Item, ItemBufferKind},
100 notifications::NotifyTaskExt,
101};
102
103/// Determines what kinds of highlights should be applied to a lines background.
104#[derive(Clone, Copy, Default)]
105struct LineHighlightSpec {
106 selection: bool,
107 breakpoint: bool,
108 _active_stack_frame: bool,
109}
110
111#[derive(Debug)]
112struct SelectionLayout {
113 head: DisplayPoint,
114 cursor_shape: CursorShape,
115 is_newest: bool,
116 is_local: bool,
117 range: Range<DisplayPoint>,
118 active_rows: Range<DisplayRow>,
119 user_name: Option<SharedString>,
120}
121
122struct InlineBlameLayout {
123 element: AnyElement,
124 bounds: Bounds<Pixels>,
125 buffer_id: BufferId,
126 entry: BlameEntry,
127}
128
129impl SelectionLayout {
130 fn new<T: ToPoint + ToDisplayPoint + Clone>(
131 selection: Selection<T>,
132 line_mode: bool,
133 cursor_offset: bool,
134 cursor_shape: CursorShape,
135 map: &DisplaySnapshot,
136 is_newest: bool,
137 is_local: bool,
138 user_name: Option<SharedString>,
139 ) -> Self {
140 let point_selection = selection.map(|p| p.to_point(map.buffer_snapshot()));
141 let display_selection = point_selection.map(|p| p.to_display_point(map));
142 let mut range = display_selection.range();
143 let mut head = display_selection.head();
144 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
145 ..map.next_line_boundary(point_selection.end).1.row();
146
147 // vim visual line mode
148 if line_mode {
149 let point_range = map.expand_to_line(point_selection.range());
150 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
151 }
152
153 // any vim visual mode (including line mode)
154 if cursor_offset && !range.is_empty() && !selection.reversed {
155 if head.column() > 0 {
156 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left);
157 } else if head.row().0 > 0 && head != map.max_point() {
158 head = map.clip_point(
159 DisplayPoint::new(
160 head.row().previous_row(),
161 map.line_len(head.row().previous_row()),
162 ),
163 Bias::Left,
164 );
165 // updating range.end is a no-op unless you're cursor is
166 // on the newline containing a multi-buffer divider
167 // in which case the clip_point may have moved the head up
168 // an additional row.
169 range.end = DisplayPoint::new(head.row().next_row(), 0);
170 active_rows.end = head.row();
171 }
172 }
173
174 Self {
175 head,
176 cursor_shape,
177 is_newest,
178 is_local,
179 range,
180 active_rows,
181 user_name,
182 }
183 }
184}
185
186#[derive(Default)]
187struct RenderBlocksOutput {
188 blocks: Vec<BlockLayout>,
189 row_block_types: HashMap<DisplayRow, bool>,
190 resized_blocks: Option<HashMap<CustomBlockId, u32>>,
191}
192
193pub struct EditorElement {
194 editor: Entity<Editor>,
195 style: EditorStyle,
196}
197
198impl EditorElement {
199 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
200
201 pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
202 Self {
203 editor: editor.clone(),
204 style,
205 }
206 }
207
208 fn register_actions(&self, window: &mut Window, cx: &mut App) {
209 let editor = &self.editor;
210 editor.update(cx, |editor, cx| {
211 for action in editor.editor_actions.borrow().values() {
212 (action)(editor, window, cx)
213 }
214 });
215
216 crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
217 crate::clangd_ext::apply_related_actions(editor, window, cx);
218
219 register_action(editor, window, Editor::open_context_menu);
220 register_action(editor, window, Editor::move_left);
221 register_action(editor, window, Editor::move_right);
222 register_action(editor, window, Editor::move_down);
223 register_action(editor, window, Editor::move_down_by_lines);
224 register_action(editor, window, Editor::select_down_by_lines);
225 register_action(editor, window, Editor::move_up);
226 register_action(editor, window, Editor::move_up_by_lines);
227 register_action(editor, window, Editor::select_up_by_lines);
228 register_action(editor, window, Editor::select_page_down);
229 register_action(editor, window, Editor::select_page_up);
230 register_action(editor, window, Editor::cancel);
231 register_action(editor, window, Editor::newline);
232 register_action(editor, window, Editor::newline_above);
233 register_action(editor, window, Editor::newline_below);
234 register_action(editor, window, Editor::backspace);
235 register_action(editor, window, Editor::blame_hover);
236 register_action(editor, window, Editor::delete);
237 register_action(editor, window, Editor::tab);
238 register_action(editor, window, Editor::next_snippet_tabstop);
239 register_action(editor, window, Editor::previous_snippet_tabstop);
240 register_action(editor, window, Editor::backtab);
241 register_action(editor, window, Editor::indent);
242 register_action(editor, window, Editor::outdent);
243 register_action(editor, window, Editor::autoindent);
244 register_action(editor, window, Editor::delete_line);
245 register_action(editor, window, Editor::join_lines);
246 register_action(editor, window, Editor::sort_lines_by_length);
247 register_action(editor, window, Editor::sort_lines_case_sensitive);
248 register_action(editor, window, Editor::sort_lines_case_insensitive);
249 register_action(editor, window, Editor::reverse_lines);
250 register_action(editor, window, Editor::shuffle_lines);
251 register_action(editor, window, Editor::rotate_selections_forward);
252 register_action(editor, window, Editor::rotate_selections_backward);
253 register_action(editor, window, Editor::convert_indentation_to_spaces);
254 register_action(editor, window, Editor::convert_indentation_to_tabs);
255 register_action(editor, window, Editor::convert_to_upper_case);
256 register_action(editor, window, Editor::convert_to_lower_case);
257 register_action(editor, window, Editor::convert_to_title_case);
258 register_action(editor, window, Editor::convert_to_snake_case);
259 register_action(editor, window, Editor::convert_to_kebab_case);
260 register_action(editor, window, Editor::convert_to_upper_camel_case);
261 register_action(editor, window, Editor::convert_to_lower_camel_case);
262 register_action(editor, window, Editor::convert_to_opposite_case);
263 register_action(editor, window, Editor::convert_to_sentence_case);
264 register_action(editor, window, Editor::toggle_case);
265 register_action(editor, window, Editor::convert_to_rot13);
266 register_action(editor, window, Editor::convert_to_rot47);
267 register_action(editor, window, Editor::delete_to_previous_word_start);
268 register_action(editor, window, Editor::delete_to_previous_subword_start);
269 register_action(editor, window, Editor::delete_to_next_word_end);
270 register_action(editor, window, Editor::delete_to_next_subword_end);
271 register_action(editor, window, Editor::delete_to_beginning_of_line);
272 register_action(editor, window, Editor::delete_to_end_of_line);
273 register_action(editor, window, Editor::cut_to_end_of_line);
274 register_action(editor, window, Editor::duplicate_line_up);
275 register_action(editor, window, Editor::duplicate_line_down);
276 register_action(editor, window, Editor::duplicate_selection);
277 register_action(editor, window, Editor::move_line_up);
278 register_action(editor, window, Editor::move_line_down);
279 register_action(editor, window, Editor::transpose);
280 register_action(editor, window, Editor::rewrap);
281 register_action(editor, window, Editor::cut);
282 register_action(editor, window, Editor::kill_ring_cut);
283 register_action(editor, window, Editor::kill_ring_yank);
284 register_action(editor, window, Editor::copy);
285 register_action(editor, window, Editor::copy_and_trim);
286 register_action(editor, window, Editor::diff_clipboard_with_selection);
287 register_action(editor, window, Editor::paste);
288 register_action(editor, window, Editor::undo);
289 register_action(editor, window, Editor::redo);
290 register_action(editor, window, Editor::move_page_up);
291 register_action(editor, window, Editor::move_page_down);
292 register_action(editor, window, Editor::next_screen);
293 register_action(editor, window, Editor::scroll_cursor_top);
294 register_action(editor, window, Editor::scroll_cursor_center);
295 register_action(editor, window, Editor::scroll_cursor_bottom);
296 register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
297 register_action(editor, window, |editor, _: &LineDown, window, cx| {
298 editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
299 });
300 register_action(editor, window, |editor, _: &LineUp, window, cx| {
301 editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
302 });
303 register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
304 editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
305 });
306 register_action(
307 editor,
308 window,
309 |editor, HandleInput(text): &HandleInput, window, cx| {
310 if text.is_empty() {
311 return;
312 }
313 editor.handle_input(text, window, cx);
314 },
315 );
316 register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
317 editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
318 });
319 register_action(editor, window, |editor, _: &PageDown, window, cx| {
320 editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
321 });
322 register_action(editor, window, |editor, _: &PageUp, window, cx| {
323 editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
324 });
325 register_action(editor, window, Editor::move_to_previous_word_start);
326 register_action(editor, window, Editor::move_to_previous_subword_start);
327 register_action(editor, window, Editor::move_to_next_word_end);
328 register_action(editor, window, Editor::move_to_next_subword_end);
329 register_action(editor, window, Editor::move_to_beginning_of_line);
330 register_action(editor, window, Editor::move_to_end_of_line);
331 register_action(editor, window, Editor::move_to_start_of_paragraph);
332 register_action(editor, window, Editor::move_to_end_of_paragraph);
333 register_action(editor, window, Editor::move_to_beginning);
334 register_action(editor, window, Editor::move_to_end);
335 register_action(editor, window, Editor::move_to_start_of_excerpt);
336 register_action(editor, window, Editor::move_to_start_of_next_excerpt);
337 register_action(editor, window, Editor::move_to_end_of_excerpt);
338 register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
339 register_action(editor, window, Editor::select_up);
340 register_action(editor, window, Editor::select_down);
341 register_action(editor, window, Editor::select_left);
342 register_action(editor, window, Editor::select_right);
343 register_action(editor, window, Editor::select_to_previous_word_start);
344 register_action(editor, window, Editor::select_to_previous_subword_start);
345 register_action(editor, window, Editor::select_to_next_word_end);
346 register_action(editor, window, Editor::select_to_next_subword_end);
347 register_action(editor, window, Editor::select_to_beginning_of_line);
348 register_action(editor, window, Editor::select_to_end_of_line);
349 register_action(editor, window, Editor::select_to_start_of_paragraph);
350 register_action(editor, window, Editor::select_to_end_of_paragraph);
351 register_action(editor, window, Editor::select_to_start_of_excerpt);
352 register_action(editor, window, Editor::select_to_start_of_next_excerpt);
353 register_action(editor, window, Editor::select_to_end_of_excerpt);
354 register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
355 register_action(editor, window, Editor::select_to_beginning);
356 register_action(editor, window, Editor::select_to_end);
357 register_action(editor, window, Editor::select_all);
358 register_action(editor, window, |editor, action, window, cx| {
359 editor.select_all_matches(action, window, cx).log_err();
360 });
361 register_action(editor, window, Editor::select_line);
362 register_action(editor, window, Editor::split_selection_into_lines);
363 register_action(editor, window, Editor::add_selection_above);
364 register_action(editor, window, Editor::add_selection_below);
365 register_action(editor, window, Editor::insert_snippet_at_selections);
366 register_action(editor, window, |editor, action, window, cx| {
367 editor.select_next(action, window, cx).log_err();
368 });
369 register_action(editor, window, |editor, action, window, cx| {
370 editor.select_previous(action, window, cx).log_err();
371 });
372 register_action(editor, window, |editor, action, window, cx| {
373 editor.find_next_match(action, window, cx).log_err();
374 });
375 register_action(editor, window, |editor, action, window, cx| {
376 editor.find_previous_match(action, window, cx).log_err();
377 });
378 register_action(editor, window, Editor::toggle_comments);
379 register_action(editor, window, Editor::select_larger_syntax_node);
380 register_action(editor, window, Editor::select_smaller_syntax_node);
381 register_action(editor, window, Editor::select_next_syntax_node);
382 register_action(editor, window, Editor::select_prev_syntax_node);
383 register_action(editor, window, Editor::unwrap_syntax_node);
384 register_action(editor, window, Editor::select_enclosing_symbol);
385 register_action(editor, window, Editor::move_to_enclosing_bracket);
386 register_action(editor, window, Editor::undo_selection);
387 register_action(editor, window, Editor::redo_selection);
388 if editor.read(cx).buffer_kind(cx) == ItemBufferKind::Multibuffer {
389 register_action(editor, window, Editor::expand_excerpts);
390 register_action(editor, window, Editor::expand_excerpts_up);
391 register_action(editor, window, Editor::expand_excerpts_down);
392 }
393 register_action(editor, window, Editor::go_to_diagnostic);
394 register_action(editor, window, Editor::go_to_prev_diagnostic);
395 register_action(editor, window, Editor::go_to_next_hunk);
396 register_action(editor, window, Editor::go_to_prev_hunk);
397 register_action(editor, window, Editor::go_to_next_document_highlight);
398 register_action(editor, window, Editor::go_to_prev_document_highlight);
399 register_action(editor, window, |editor, action, window, cx| {
400 editor
401 .go_to_definition(action, window, cx)
402 .detach_and_log_err(cx);
403 });
404 register_action(editor, window, |editor, action, window, cx| {
405 editor
406 .go_to_definition_split(action, window, cx)
407 .detach_and_log_err(cx);
408 });
409 register_action(editor, window, |editor, action, window, cx| {
410 editor
411 .go_to_declaration(action, window, cx)
412 .detach_and_log_err(cx);
413 });
414 register_action(editor, window, |editor, action, window, cx| {
415 editor
416 .go_to_declaration_split(action, window, cx)
417 .detach_and_log_err(cx);
418 });
419 register_action(editor, window, |editor, action, window, cx| {
420 editor
421 .go_to_implementation(action, window, cx)
422 .detach_and_log_err(cx);
423 });
424 register_action(editor, window, |editor, action, window, cx| {
425 editor
426 .go_to_implementation_split(action, window, cx)
427 .detach_and_log_err(cx);
428 });
429 register_action(editor, window, |editor, action, window, cx| {
430 editor
431 .go_to_type_definition(action, window, cx)
432 .detach_and_log_err(cx);
433 });
434 register_action(editor, window, |editor, action, window, cx| {
435 editor
436 .go_to_type_definition_split(action, window, cx)
437 .detach_and_log_err(cx);
438 });
439 register_action(editor, window, Editor::open_url);
440 register_action(editor, window, Editor::open_selected_filename);
441 register_action(editor, window, Editor::fold);
442 register_action(editor, window, Editor::fold_at_level);
443 register_action(editor, window, Editor::fold_at_level_1);
444 register_action(editor, window, Editor::fold_at_level_2);
445 register_action(editor, window, Editor::fold_at_level_3);
446 register_action(editor, window, Editor::fold_at_level_4);
447 register_action(editor, window, Editor::fold_at_level_5);
448 register_action(editor, window, Editor::fold_at_level_6);
449 register_action(editor, window, Editor::fold_at_level_7);
450 register_action(editor, window, Editor::fold_at_level_8);
451 register_action(editor, window, Editor::fold_at_level_9);
452 register_action(editor, window, Editor::fold_all);
453 register_action(editor, window, Editor::fold_function_bodies);
454 register_action(editor, window, Editor::fold_recursive);
455 register_action(editor, window, Editor::toggle_fold);
456 register_action(editor, window, Editor::toggle_fold_recursive);
457 register_action(editor, window, Editor::toggle_fold_all);
458 register_action(editor, window, Editor::unfold_lines);
459 register_action(editor, window, Editor::unfold_recursive);
460 register_action(editor, window, Editor::unfold_all);
461 register_action(editor, window, Editor::fold_selected_ranges);
462 register_action(editor, window, Editor::set_mark);
463 register_action(editor, window, Editor::swap_selection_ends);
464 register_action(editor, window, Editor::show_completions);
465 register_action(editor, window, Editor::show_word_completions);
466 register_action(editor, window, Editor::toggle_code_actions);
467 register_action(editor, window, Editor::open_excerpts);
468 register_action(editor, window, Editor::open_excerpts_in_split);
469 register_action(editor, window, Editor::toggle_soft_wrap);
470 register_action(editor, window, Editor::toggle_tab_bar);
471 register_action(editor, window, Editor::toggle_line_numbers);
472 register_action(editor, window, Editor::toggle_relative_line_numbers);
473 register_action(editor, window, Editor::toggle_indent_guides);
474 register_action(editor, window, Editor::toggle_inlay_hints);
475 register_action(editor, window, Editor::toggle_edit_predictions);
476 if editor.read(cx).diagnostics_enabled() {
477 register_action(editor, window, Editor::toggle_diagnostics);
478 }
479 if editor.read(cx).inline_diagnostics_enabled() {
480 register_action(editor, window, Editor::toggle_inline_diagnostics);
481 }
482 if editor.read(cx).supports_minimap(cx) {
483 register_action(editor, window, Editor::toggle_minimap);
484 }
485 register_action(editor, window, hover_popover::hover);
486 register_action(editor, window, Editor::reveal_in_finder);
487 register_action(editor, window, Editor::copy_path);
488 register_action(editor, window, Editor::copy_relative_path);
489 register_action(editor, window, Editor::copy_file_name);
490 register_action(editor, window, Editor::copy_file_name_without_extension);
491 register_action(editor, window, Editor::copy_highlight_json);
492 register_action(editor, window, Editor::copy_permalink_to_line);
493 register_action(editor, window, Editor::open_permalink_to_line);
494 register_action(editor, window, Editor::copy_file_location);
495 register_action(editor, window, Editor::toggle_git_blame);
496 register_action(editor, window, Editor::toggle_git_blame_inline);
497 register_action(editor, window, Editor::open_git_blame_commit);
498 register_action(editor, window, Editor::toggle_selected_diff_hunks);
499 register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
500 register_action(editor, window, Editor::stage_and_next);
501 register_action(editor, window, Editor::unstage_and_next);
502 register_action(editor, window, Editor::expand_all_diff_hunks);
503 register_action(editor, window, Editor::collapse_all_diff_hunks);
504 register_action(editor, window, Editor::go_to_previous_change);
505 register_action(editor, window, Editor::go_to_next_change);
506 register_action(editor, window, Editor::go_to_prev_reference);
507 register_action(editor, window, Editor::go_to_next_reference);
508
509 register_action(editor, window, |editor, action, window, cx| {
510 if let Some(task) = editor.format(action, window, cx) {
511 task.detach_and_notify_err(window, cx);
512 } else {
513 cx.propagate();
514 }
515 });
516 register_action(editor, window, |editor, action, window, cx| {
517 if let Some(task) = editor.format_selections(action, window, cx) {
518 task.detach_and_notify_err(window, cx);
519 } else {
520 cx.propagate();
521 }
522 });
523 register_action(editor, window, |editor, action, window, cx| {
524 if let Some(task) = editor.organize_imports(action, window, cx) {
525 task.detach_and_notify_err(window, cx);
526 } else {
527 cx.propagate();
528 }
529 });
530 register_action(editor, window, Editor::restart_language_server);
531 register_action(editor, window, Editor::stop_language_server);
532 register_action(editor, window, Editor::show_character_palette);
533 register_action(editor, window, |editor, action, window, cx| {
534 if let Some(task) = editor.confirm_completion(action, window, cx) {
535 task.detach_and_notify_err(window, cx);
536 } else {
537 cx.propagate();
538 }
539 });
540 register_action(editor, window, |editor, action, window, cx| {
541 if let Some(task) = editor.confirm_completion_replace(action, window, cx) {
542 task.detach_and_notify_err(window, cx);
543 } else {
544 cx.propagate();
545 }
546 });
547 register_action(editor, window, |editor, action, window, cx| {
548 if let Some(task) = editor.confirm_completion_insert(action, window, cx) {
549 task.detach_and_notify_err(window, cx);
550 } else {
551 cx.propagate();
552 }
553 });
554 register_action(editor, window, |editor, action, window, cx| {
555 if let Some(task) = editor.compose_completion(action, window, cx) {
556 task.detach_and_notify_err(window, cx);
557 } else {
558 cx.propagate();
559 }
560 });
561 register_action(editor, window, |editor, action, window, cx| {
562 if let Some(task) = editor.confirm_code_action(action, window, cx) {
563 task.detach_and_notify_err(window, cx);
564 } else {
565 cx.propagate();
566 }
567 });
568 register_action(editor, window, |editor, action, window, cx| {
569 if let Some(task) = editor.rename(action, window, cx) {
570 task.detach_and_notify_err(window, cx);
571 } else {
572 cx.propagate();
573 }
574 });
575 register_action(editor, window, |editor, action, window, cx| {
576 if let Some(task) = editor.confirm_rename(action, window, cx) {
577 task.detach_and_notify_err(window, cx);
578 } else {
579 cx.propagate();
580 }
581 });
582 register_action(editor, window, |editor, action, window, cx| {
583 if let Some(task) = editor.find_all_references(action, window, cx) {
584 task.detach_and_log_err(cx);
585 } else {
586 cx.propagate();
587 }
588 });
589 register_action(editor, window, Editor::show_signature_help);
590 register_action(editor, window, Editor::signature_help_prev);
591 register_action(editor, window, Editor::signature_help_next);
592 register_action(editor, window, Editor::show_edit_prediction);
593 register_action(editor, window, Editor::context_menu_first);
594 register_action(editor, window, Editor::context_menu_prev);
595 register_action(editor, window, Editor::context_menu_next);
596 register_action(editor, window, Editor::context_menu_last);
597 register_action(editor, window, Editor::display_cursor_names);
598 register_action(editor, window, Editor::unique_lines_case_insensitive);
599 register_action(editor, window, Editor::unique_lines_case_sensitive);
600 register_action(editor, window, Editor::accept_next_word_edit_prediction);
601 register_action(editor, window, Editor::accept_next_line_edit_prediction);
602 register_action(editor, window, Editor::accept_edit_prediction);
603 register_action(editor, window, Editor::restore_file);
604 register_action(editor, window, Editor::git_restore);
605 register_action(editor, window, Editor::apply_all_diff_hunks);
606 register_action(editor, window, Editor::apply_selected_diff_hunks);
607 register_action(editor, window, Editor::open_active_item_in_terminal);
608 register_action(editor, window, Editor::reload_file);
609 register_action(editor, window, Editor::spawn_nearest_task);
610 register_action(editor, window, Editor::insert_uuid_v4);
611 register_action(editor, window, Editor::insert_uuid_v7);
612 register_action(editor, window, Editor::open_selections_in_multibuffer);
613 register_action(editor, window, Editor::toggle_breakpoint);
614 register_action(editor, window, Editor::edit_log_breakpoint);
615 register_action(editor, window, Editor::enable_breakpoint);
616 register_action(editor, window, Editor::disable_breakpoint);
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 if self.editor.read(cx).use_base_text_line_numbers {
3269 row_info.base_text_row?.0 + 1
3270 } else {
3271 row_info.buffer_row? + 1
3272 };
3273 let relative_number = relative_rows.get(&display_row);
3274 if !(relative_line_numbers_enabled && relative_number.is_some())
3275 && row_info
3276 .diff_status
3277 .is_some_and(|status| status.is_deleted())
3278 && !self.editor.read(cx).use_base_text_line_numbers
3279 {
3280 return None;
3281 }
3282
3283 let number = relative_number.unwrap_or(&non_relative_number);
3284 write!(&mut line_number, "{number}").unwrap();
3285
3286 let color = active_rows
3287 .get(&display_row)
3288 .map(|spec| {
3289 if spec.breakpoint {
3290 cx.theme().colors().debugger_accent
3291 } else {
3292 cx.theme().colors().editor_active_line_number
3293 }
3294 })
3295 .unwrap_or_else(|| cx.theme().colors().editor_line_number);
3296 let shaped_line =
3297 self.shape_line_number(SharedString::from(&line_number), color, window);
3298 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
3299 let line_origin = gutter_hitbox.map(|hitbox| {
3300 hitbox.origin
3301 + point(
3302 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
3303 ix as f32 * line_height
3304 - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height)),
3305 )
3306 });
3307
3308 #[cfg(not(test))]
3309 let hitbox = line_origin.map(|line_origin| {
3310 window.insert_hitbox(
3311 Bounds::new(line_origin, size(shaped_line.width, line_height)),
3312 HitboxBehavior::Normal,
3313 )
3314 });
3315 #[cfg(test)]
3316 let hitbox = {
3317 let _ = line_origin;
3318 None
3319 };
3320
3321 let segment = LineNumberSegment {
3322 shaped_line,
3323 hitbox,
3324 };
3325
3326 let buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
3327 let multi_buffer_row = MultiBufferRow(buffer_row);
3328
3329 Some((multi_buffer_row, segment))
3330 });
3331
3332 let mut line_numbers: HashMap<MultiBufferRow, LineNumberLayout> = HashMap::default();
3333 for (buffer_row, segment) in segments {
3334 line_numbers
3335 .entry(buffer_row)
3336 .or_insert_with(|| LineNumberLayout {
3337 segments: Default::default(),
3338 })
3339 .segments
3340 .push(segment);
3341 }
3342 Arc::new(line_numbers)
3343 }
3344
3345 fn layout_crease_toggles(
3346 &self,
3347 rows: Range<DisplayRow>,
3348 row_infos: &[RowInfo],
3349 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3350 snapshot: &EditorSnapshot,
3351 window: &mut Window,
3352 cx: &mut App,
3353 ) -> Vec<Option<AnyElement>> {
3354 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
3355 && snapshot.mode.is_full()
3356 && self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
3357 if include_fold_statuses {
3358 row_infos
3359 .iter()
3360 .enumerate()
3361 .map(|(ix, info)| {
3362 if info.expand_info.is_some() {
3363 return None;
3364 }
3365 let row = info.multibuffer_row?;
3366 let display_row = DisplayRow(rows.start.0 + ix as u32);
3367 let active = active_rows.contains_key(&display_row);
3368
3369 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
3370 })
3371 .collect()
3372 } else {
3373 Vec::new()
3374 }
3375 }
3376
3377 fn layout_crease_trailers(
3378 &self,
3379 buffer_rows: impl IntoIterator<Item = RowInfo>,
3380 snapshot: &EditorSnapshot,
3381 window: &mut Window,
3382 cx: &mut App,
3383 ) -> Vec<Option<AnyElement>> {
3384 buffer_rows
3385 .into_iter()
3386 .map(|row_info| {
3387 if row_info.expand_info.is_some() {
3388 return None;
3389 }
3390 if let Some(row) = row_info.multibuffer_row {
3391 snapshot.render_crease_trailer(row, window, cx)
3392 } else {
3393 None
3394 }
3395 })
3396 .collect()
3397 }
3398
3399 fn bg_segments_per_row(
3400 rows: Range<DisplayRow>,
3401 selections: &[(PlayerColor, Vec<SelectionLayout>)],
3402 highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
3403 base_background: Hsla,
3404 ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
3405 if rows.start >= rows.end {
3406 return Vec::new();
3407 }
3408 if !base_background.is_opaque() {
3409 // We don't actually know what color is behind this editor.
3410 return Vec::new();
3411 }
3412 let highlight_iter = highlight_ranges.iter().cloned();
3413 let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
3414 let color = player_color.selection;
3415 layouts.iter().filter_map(move |selection_layout| {
3416 if selection_layout.range.start != selection_layout.range.end {
3417 Some((selection_layout.range.clone(), color))
3418 } else {
3419 None
3420 }
3421 })
3422 });
3423 let mut per_row_map = vec![Vec::new(); rows.len()];
3424 for (range, color) in highlight_iter.chain(selection_iter) {
3425 let covered_rows = if range.end.column() == 0 {
3426 cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
3427 } else {
3428 cmp::max(range.start.row(), rows.start)
3429 ..cmp::min(range.end.row().next_row(), rows.end)
3430 };
3431 for row in covered_rows.iter_rows() {
3432 let seg_start = if row == range.start.row() {
3433 range.start
3434 } else {
3435 DisplayPoint::new(row, 0)
3436 };
3437 let seg_end = if row == range.end.row() && range.end.column() != 0 {
3438 range.end
3439 } else {
3440 DisplayPoint::new(row, u32::MAX)
3441 };
3442 let ix = row.minus(rows.start) as usize;
3443 debug_assert!(row >= rows.start && row < rows.end);
3444 debug_assert!(ix < per_row_map.len());
3445 per_row_map[ix].push((seg_start..seg_end, color));
3446 }
3447 }
3448 for row_segments in per_row_map.iter_mut() {
3449 if row_segments.is_empty() {
3450 continue;
3451 }
3452 let segments = mem::take(row_segments);
3453 let merged = Self::merge_overlapping_ranges(segments, base_background);
3454 *row_segments = merged;
3455 }
3456 per_row_map
3457 }
3458
3459 /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
3460 /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
3461 ///
3462 /// Expects `start.row() == end.row()` for each range.
3463 fn merge_overlapping_ranges(
3464 ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3465 base_background: Hsla,
3466 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
3467 struct Boundary {
3468 pos: DisplayPoint,
3469 is_start: bool,
3470 index: usize,
3471 color: Hsla,
3472 }
3473
3474 let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
3475 for (index, (range, color)) in ranges.iter().enumerate() {
3476 debug_assert!(
3477 range.start.row() == range.end.row(),
3478 "expects single-row ranges"
3479 );
3480 if range.start < range.end {
3481 boundaries.push(Boundary {
3482 pos: range.start,
3483 is_start: true,
3484 index,
3485 color: *color,
3486 });
3487 boundaries.push(Boundary {
3488 pos: range.end,
3489 is_start: false,
3490 index,
3491 color: *color,
3492 });
3493 }
3494 }
3495
3496 if boundaries.is_empty() {
3497 return Vec::new();
3498 }
3499
3500 boundaries
3501 .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
3502
3503 let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
3504 let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
3505
3506 let mut i = 0;
3507 let mut start_pos = boundaries[0].pos;
3508
3509 let boundaries_len = boundaries.len();
3510 while i < boundaries_len {
3511 let current_boundary_pos = boundaries[i].pos;
3512 if start_pos < current_boundary_pos {
3513 if !active_ranges.is_empty() {
3514 let mut color = base_background;
3515 for &(_, c) in &active_ranges {
3516 color = Hsla::blend(color, c);
3517 }
3518 if let Some((last_range, last_color)) = processed_ranges.last_mut() {
3519 if *last_color == color && last_range.end == start_pos {
3520 last_range.end = current_boundary_pos;
3521 } else {
3522 processed_ranges.push((start_pos..current_boundary_pos, color));
3523 }
3524 } else {
3525 processed_ranges.push((start_pos..current_boundary_pos, color));
3526 }
3527 }
3528 }
3529 while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
3530 let active_range = &boundaries[i];
3531 if active_range.is_start {
3532 let idx = active_range.index;
3533 let pos = active_ranges
3534 .binary_search_by_key(&idx, |(i, _)| *i)
3535 .unwrap_or_else(|p| p);
3536 active_ranges.insert(pos, (idx, active_range.color));
3537 } else {
3538 let idx = active_range.index;
3539 if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
3540 active_ranges.remove(pos);
3541 }
3542 }
3543 i += 1;
3544 }
3545 start_pos = current_boundary_pos;
3546 }
3547
3548 processed_ranges
3549 }
3550
3551 fn layout_lines(
3552 rows: Range<DisplayRow>,
3553 snapshot: &EditorSnapshot,
3554 style: &EditorStyle,
3555 editor_width: Pixels,
3556 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3557 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
3558 window: &mut Window,
3559 cx: &mut App,
3560 ) -> Vec<LineWithInvisibles> {
3561 if rows.start >= rows.end {
3562 return Vec::new();
3563 }
3564
3565 // Show the placeholder when the editor is empty
3566 if snapshot.is_empty() {
3567 let font_size = style.text.font_size.to_pixels(window.rem_size());
3568 let placeholder_color = cx.theme().colors().text_placeholder;
3569 let placeholder_text = snapshot.placeholder_text();
3570
3571 let placeholder_lines = placeholder_text
3572 .as_ref()
3573 .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
3574
3575 let placeholder_line_count = placeholder_lines.len();
3576
3577 placeholder_lines
3578 .into_iter()
3579 .skip(rows.start.0 as usize)
3580 .chain(iter::repeat(""))
3581 .take(cmp::max(rows.len(), placeholder_line_count))
3582 .map(move |line| {
3583 let run = TextRun {
3584 len: line.len(),
3585 font: style.text.font(),
3586 color: placeholder_color,
3587 ..Default::default()
3588 };
3589 let line = window.text_system().shape_line(
3590 line.to_string().into(),
3591 font_size,
3592 &[run],
3593 None,
3594 );
3595 LineWithInvisibles {
3596 width: line.width,
3597 len: line.len,
3598 fragments: smallvec![LineFragment::Text(line)],
3599 invisibles: Vec::new(),
3600 font_size,
3601 }
3602 })
3603 .collect()
3604 } else {
3605 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
3606 LineWithInvisibles::from_chunks(
3607 chunks,
3608 style,
3609 MAX_LINE_LEN,
3610 rows.len(),
3611 &snapshot.mode,
3612 editor_width,
3613 is_row_soft_wrapped,
3614 bg_segments_per_row,
3615 window,
3616 cx,
3617 )
3618 }
3619 }
3620
3621 fn prepaint_lines(
3622 &self,
3623 start_row: DisplayRow,
3624 line_layouts: &mut [LineWithInvisibles],
3625 line_height: Pixels,
3626 scroll_position: gpui::Point<ScrollOffset>,
3627 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
3628 content_origin: gpui::Point<Pixels>,
3629 window: &mut Window,
3630 cx: &mut App,
3631 ) -> SmallVec<[AnyElement; 1]> {
3632 let mut line_elements = SmallVec::new();
3633 for (ix, line) in line_layouts.iter_mut().enumerate() {
3634 let row = start_row + DisplayRow(ix as u32);
3635 line.prepaint(
3636 line_height,
3637 scroll_position,
3638 scroll_pixel_position,
3639 row,
3640 content_origin,
3641 &mut line_elements,
3642 window,
3643 cx,
3644 );
3645 }
3646 line_elements
3647 }
3648
3649 fn render_block(
3650 &self,
3651 block: &Block,
3652 available_width: AvailableSpace,
3653 block_id: BlockId,
3654 block_row_start: DisplayRow,
3655 snapshot: &EditorSnapshot,
3656 text_x: Pixels,
3657 rows: &Range<DisplayRow>,
3658 line_layouts: &[LineWithInvisibles],
3659 editor_margins: &EditorMargins,
3660 line_height: Pixels,
3661 em_width: Pixels,
3662 text_hitbox: &Hitbox,
3663 editor_width: Pixels,
3664 scroll_width: &mut Pixels,
3665 resized_blocks: &mut HashMap<CustomBlockId, u32>,
3666 row_block_types: &mut HashMap<DisplayRow, bool>,
3667 selections: &[Selection<Point>],
3668 selected_buffer_ids: &Vec<BufferId>,
3669 latest_selection_anchors: &HashMap<BufferId, Anchor>,
3670 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3671 sticky_header_excerpt_id: Option<ExcerptId>,
3672 block_resize_offset: &mut i32,
3673 window: &mut Window,
3674 cx: &mut App,
3675 ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
3676 let mut x_position = None;
3677 let mut element = match block {
3678 Block::Custom(custom) => {
3679 let block_start = custom.start().to_point(&snapshot.buffer_snapshot());
3680 let block_end = custom.end().to_point(&snapshot.buffer_snapshot());
3681 if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
3682 return None;
3683 }
3684 let align_to = block_start.to_display_point(snapshot);
3685 let x_and_width = |layout: &LineWithInvisibles| {
3686 Some((
3687 text_x + layout.x_for_index(align_to.column() as usize),
3688 text_x + layout.width,
3689 ))
3690 };
3691 let line_ix = align_to.row().0.checked_sub(rows.start.0);
3692 x_position =
3693 if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
3694 x_and_width(layout)
3695 } else {
3696 x_and_width(&layout_line(
3697 align_to.row(),
3698 snapshot,
3699 &self.style,
3700 editor_width,
3701 is_row_soft_wrapped,
3702 window,
3703 cx,
3704 ))
3705 };
3706
3707 let anchor_x = x_position.unwrap().0;
3708
3709 let selected = selections
3710 .binary_search_by(|selection| {
3711 if selection.end <= block_start {
3712 Ordering::Less
3713 } else if selection.start >= block_end {
3714 Ordering::Greater
3715 } else {
3716 Ordering::Equal
3717 }
3718 })
3719 .is_ok();
3720
3721 div()
3722 .size_full()
3723 .child(custom.render(&mut BlockContext {
3724 window,
3725 app: cx,
3726 anchor_x,
3727 margins: editor_margins,
3728 line_height,
3729 em_width,
3730 block_id,
3731 selected,
3732 max_width: text_hitbox.size.width.max(*scroll_width),
3733 editor_style: &self.style,
3734 }))
3735 .into_any()
3736 }
3737
3738 Block::FoldedBuffer {
3739 first_excerpt,
3740 height,
3741 ..
3742 } => {
3743 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
3744 let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
3745
3746 let jump_data = header_jump_data(
3747 snapshot,
3748 block_row_start,
3749 *height,
3750 first_excerpt,
3751 latest_selection_anchors,
3752 );
3753 result
3754 .child(self.render_buffer_header(
3755 first_excerpt,
3756 true,
3757 selected,
3758 false,
3759 jump_data,
3760 window,
3761 cx,
3762 ))
3763 .into_any_element()
3764 }
3765
3766 Block::ExcerptBoundary { .. } => {
3767 let color = cx.theme().colors().clone();
3768 let mut result = v_flex().id(block_id).w_full();
3769
3770 result = result.child(
3771 h_flex().relative().child(
3772 div()
3773 .top(line_height / 2.)
3774 .absolute()
3775 .w_full()
3776 .h_px()
3777 .bg(color.border_variant),
3778 ),
3779 );
3780
3781 result.into_any()
3782 }
3783
3784 Block::BufferHeader { excerpt, height } => {
3785 let mut result = v_flex().id(block_id).w_full();
3786
3787 let jump_data = header_jump_data(
3788 snapshot,
3789 block_row_start,
3790 *height,
3791 excerpt,
3792 latest_selection_anchors,
3793 );
3794
3795 if sticky_header_excerpt_id != Some(excerpt.id) {
3796 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3797
3798 result = result.child(div().pr(editor_margins.right).child(
3799 self.render_buffer_header(
3800 excerpt, false, selected, false, jump_data, window, cx,
3801 ),
3802 ));
3803 } else {
3804 result =
3805 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3806 }
3807
3808 result.into_any()
3809 }
3810 };
3811
3812 // Discover the element's content height, then round up to the nearest multiple of line height.
3813 let preliminary_size = element.layout_as_root(
3814 size(available_width, AvailableSpace::MinContent),
3815 window,
3816 cx,
3817 );
3818 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
3819 let final_size = if preliminary_size.height == quantized_height {
3820 preliminary_size
3821 } else {
3822 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
3823 };
3824 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
3825
3826 let effective_row_start = block_row_start.0 as i32 + *block_resize_offset;
3827 debug_assert!(effective_row_start >= 0);
3828 let mut row = DisplayRow(effective_row_start.max(0) as u32);
3829
3830 let mut x_offset = px(0.);
3831 let mut is_block = true;
3832
3833 if let BlockId::Custom(custom_block_id) = block_id
3834 && block.has_height()
3835 {
3836 if block.place_near()
3837 && let Some((x_target, line_width)) = x_position
3838 {
3839 let margin = em_width * 2;
3840 if line_width + final_size.width + margin
3841 < editor_width + editor_margins.gutter.full_width()
3842 && !row_block_types.contains_key(&(row - 1))
3843 && element_height_in_lines == 1
3844 {
3845 x_offset = line_width + margin;
3846 row = row - 1;
3847 is_block = false;
3848 element_height_in_lines = 0;
3849 row_block_types.insert(row, is_block);
3850 } else {
3851 let max_offset =
3852 editor_width + editor_margins.gutter.full_width() - final_size.width;
3853 let min_offset = (x_target + em_width - final_size.width)
3854 .max(editor_margins.gutter.full_width());
3855 x_offset = x_target.min(max_offset).max(min_offset);
3856 }
3857 };
3858 if element_height_in_lines != block.height() {
3859 *block_resize_offset += element_height_in_lines as i32 - block.height() as i32;
3860 resized_blocks.insert(custom_block_id, element_height_in_lines);
3861 }
3862 }
3863 for i in 0..element_height_in_lines {
3864 row_block_types.insert(row + i, is_block);
3865 }
3866
3867 Some((element, final_size, row, x_offset))
3868 }
3869
3870 fn render_buffer_header(
3871 &self,
3872 for_excerpt: &ExcerptInfo,
3873 is_folded: bool,
3874 is_selected: bool,
3875 is_sticky: bool,
3876 jump_data: JumpData,
3877 window: &mut Window,
3878 cx: &mut App,
3879 ) -> impl IntoElement {
3880 let editor = self.editor.read(cx);
3881 let multi_buffer = editor.buffer.read(cx);
3882 let is_read_only = self.editor.read(cx).read_only(cx);
3883 let editor_handle: &dyn ItemHandle = &self.editor;
3884
3885 let breadcrumbs = if is_selected {
3886 editor.breadcrumbs_inner(cx.theme(), cx)
3887 } else {
3888 None
3889 };
3890
3891 let file_status = multi_buffer
3892 .all_diff_hunks_expanded()
3893 .then(|| editor.status_for_buffer_id(for_excerpt.buffer_id, cx))
3894 .flatten();
3895 let indicator = multi_buffer
3896 .buffer(for_excerpt.buffer_id)
3897 .and_then(|buffer| {
3898 let buffer = buffer.read(cx);
3899 let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
3900 (true, _) => Some(Color::Warning),
3901 (_, true) => Some(Color::Accent),
3902 (false, false) => None,
3903 };
3904 indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
3905 });
3906
3907 let include_root = editor
3908 .project
3909 .as_ref()
3910 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
3911 .unwrap_or_default();
3912 let file = for_excerpt.buffer.file();
3913 let can_open_excerpts = Editor::can_open_excerpts_in_file(file);
3914 let path_style = file.map(|file| file.path_style(cx));
3915 let relative_path = for_excerpt.buffer.resolve_file_path(include_root, cx);
3916 let (parent_path, filename) = if let Some(path) = &relative_path {
3917 if let Some(path_style) = path_style {
3918 let (dir, file_name) = path_style.split(path);
3919 (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
3920 } else {
3921 (None, Some(path.clone()))
3922 }
3923 } else {
3924 (None, None)
3925 };
3926 let focus_handle = editor.focus_handle(cx);
3927 let colors = cx.theme().colors();
3928
3929 let header = div()
3930 .p_1()
3931 .w_full()
3932 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3933 .child(
3934 h_flex()
3935 .size_full()
3936 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3937 .pl_1()
3938 .pr_2()
3939 .rounded_sm()
3940 .gap_1p5()
3941 .when(is_sticky, |el| el.shadow_md())
3942 .border_1()
3943 .map(|border| {
3944 let border_color = if is_selected
3945 && is_folded
3946 && focus_handle.contains_focused(window, cx)
3947 {
3948 colors.border_focused
3949 } else {
3950 colors.border
3951 };
3952 border.border_color(border_color)
3953 })
3954 .bg(colors.editor_subheader_background)
3955 .hover(|style| style.bg(colors.element_hover))
3956 .map(|header| {
3957 let editor = self.editor.clone();
3958 let buffer_id = for_excerpt.buffer_id;
3959 let toggle_chevron_icon =
3960 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3961 let button_size = rems_from_px(28.);
3962
3963 header.child(
3964 div()
3965 .hover(|style| style.bg(colors.element_selected))
3966 .rounded_xs()
3967 .child(
3968 ButtonLike::new("toggle-buffer-fold")
3969 .style(ButtonStyle::Transparent)
3970 .height(button_size.into())
3971 .width(button_size)
3972 .children(toggle_chevron_icon)
3973 .tooltip({
3974 let focus_handle = focus_handle.clone();
3975 let is_folded_for_tooltip = is_folded;
3976 move |_window, cx| {
3977 Tooltip::with_meta_in(
3978 if is_folded_for_tooltip {
3979 "Unfold Excerpt"
3980 } else {
3981 "Fold Excerpt"
3982 },
3983 Some(&ToggleFold),
3984 format!(
3985 "{} to toggle all",
3986 text_for_keystroke(
3987 &Modifiers::alt(),
3988 "click",
3989 cx
3990 )
3991 ),
3992 &focus_handle,
3993 cx,
3994 )
3995 }
3996 })
3997 .on_click(move |event, window, cx| {
3998 if event.modifiers().alt {
3999 // Alt+click toggles all buffers
4000 editor.update(cx, |editor, cx| {
4001 editor.toggle_fold_all(
4002 &ToggleFoldAll,
4003 window,
4004 cx,
4005 );
4006 });
4007 } else {
4008 // Regular click toggles single buffer
4009 if is_folded {
4010 editor.update(cx, |editor, cx| {
4011 editor.unfold_buffer(buffer_id, cx);
4012 });
4013 } else {
4014 editor.update(cx, |editor, cx| {
4015 editor.fold_buffer(buffer_id, cx);
4016 });
4017 }
4018 }
4019 }),
4020 ),
4021 )
4022 })
4023 .children(
4024 editor
4025 .addons
4026 .values()
4027 .filter_map(|addon| {
4028 addon.render_buffer_header_controls(for_excerpt, window, cx)
4029 })
4030 .take(1),
4031 )
4032 .when(!is_read_only, |this| {
4033 this.child(
4034 h_flex()
4035 .size_3()
4036 .justify_center()
4037 .flex_shrink_0()
4038 .children(indicator),
4039 )
4040 })
4041 .child(
4042 h_flex()
4043 .cursor_pointer()
4044 .id("path_header_block")
4045 .min_w_0()
4046 .size_full()
4047 .justify_between()
4048 .overflow_hidden()
4049 .child(h_flex().min_w_0().flex_1().gap_0p5().map(|path_header| {
4050 let filename = filename
4051 .map(SharedString::from)
4052 .unwrap_or_else(|| "untitled".into());
4053
4054 path_header
4055 .when(ItemSettings::get_global(cx).file_icons, |el| {
4056 let path = path::Path::new(filename.as_str());
4057 let icon =
4058 FileIcons::get_icon(path, cx).unwrap_or_default();
4059
4060 el.child(Icon::from_path(icon).color(Color::Muted))
4061 })
4062 .child(
4063 ButtonLike::new("filename-button")
4064 .child(
4065 Label::new(filename)
4066 .single_line()
4067 .color(file_status_label_color(file_status))
4068 .buffer_font(cx)
4069 .when(
4070 file_status.is_some_and(|s| s.is_deleted()),
4071 |label| label.strikethrough(),
4072 ),
4073 )
4074 .on_click(window.listener_for(&self.editor, {
4075 let jump_data = jump_data.clone();
4076 move |editor, e: &ClickEvent, window, cx| {
4077 editor.open_excerpts_common(
4078 Some(jump_data.clone()),
4079 e.modifiers().secondary(),
4080 window,
4081 cx,
4082 );
4083 }
4084 })),
4085 )
4086 .when_some(parent_path, |then, path| {
4087 then.child(
4088 Label::new(path)
4089 .buffer_font(cx)
4090 .truncate_start()
4091 .color(
4092 if file_status
4093 .is_some_and(FileStatus::is_deleted)
4094 {
4095 Color::Custom(colors.text_disabled)
4096 } else {
4097 Color::Custom(colors.text_muted)
4098 },
4099 ),
4100 )
4101 })
4102 .when_some(breadcrumbs, |then, breadcrumbs| {
4103 then.child(render_breadcrumb_text(
4104 breadcrumbs,
4105 None,
4106 editor_handle,
4107 window,
4108 cx,
4109 ))
4110 })
4111 }))
4112 .when(
4113 can_open_excerpts && is_selected && relative_path.is_some(),
4114 |el| {
4115 el.child(
4116 Button::new("open-file-button", "Open File")
4117 .style(ButtonStyle::OutlinedGhost)
4118 .key_binding(KeyBinding::for_action_in(
4119 &OpenExcerpts,
4120 &focus_handle,
4121 cx,
4122 ))
4123 .on_click(window.listener_for(&self.editor, {
4124 let jump_data = jump_data.clone();
4125 move |editor, e: &ClickEvent, window, cx| {
4126 editor.open_excerpts_common(
4127 Some(jump_data.clone()),
4128 e.modifiers().secondary(),
4129 window,
4130 cx,
4131 );
4132 }
4133 })),
4134 )
4135 },
4136 )
4137 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
4138 .on_click(window.listener_for(&self.editor, {
4139 let buffer_id = for_excerpt.buffer_id;
4140 move |editor, e: &ClickEvent, window, cx| {
4141 if e.modifiers().alt {
4142 editor.open_excerpts_common(
4143 Some(jump_data.clone()),
4144 e.modifiers().secondary(),
4145 window,
4146 cx,
4147 );
4148 return;
4149 }
4150
4151 if is_folded {
4152 editor.unfold_buffer(buffer_id, cx);
4153 } else {
4154 editor.fold_buffer(buffer_id, cx);
4155 }
4156 }
4157 })),
4158 ),
4159 );
4160
4161 let file = for_excerpt.buffer.file().cloned();
4162 let editor = self.editor.clone();
4163
4164 right_click_menu("buffer-header-context-menu")
4165 .trigger(move |_, _, _| header)
4166 .menu(move |window, cx| {
4167 let menu_context = focus_handle.clone();
4168 let editor = editor.clone();
4169 let file = file.clone();
4170 ContextMenu::build(window, cx, move |mut menu, window, cx| {
4171 if let Some(file) = file
4172 && let Some(project) = editor.read(cx).project()
4173 && let Some(worktree) =
4174 project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
4175 {
4176 let path_style = file.path_style(cx);
4177 let worktree = worktree.read(cx);
4178 let relative_path = file.path();
4179 let entry_for_path = worktree.entry_for_path(relative_path);
4180 let abs_path = entry_for_path.map(|e| {
4181 e.canonical_path.as_deref().map_or_else(
4182 || worktree.absolutize(relative_path),
4183 Path::to_path_buf,
4184 )
4185 });
4186 let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
4187
4188 let parent_abs_path = abs_path
4189 .as_ref()
4190 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
4191 let relative_path = has_relative_path
4192 .then_some(relative_path)
4193 .map(ToOwned::to_owned);
4194
4195 let visible_in_project_panel =
4196 relative_path.is_some() && worktree.is_visible();
4197 let reveal_in_project_panel = entry_for_path
4198 .filter(|_| visible_in_project_panel)
4199 .map(|entry| entry.id);
4200 menu = menu
4201 .when_some(abs_path, |menu, abs_path| {
4202 menu.entry(
4203 "Copy Path",
4204 Some(Box::new(zed_actions::workspace::CopyPath)),
4205 window.handler_for(&editor, move |_, _, cx| {
4206 cx.write_to_clipboard(ClipboardItem::new_string(
4207 abs_path.to_string_lossy().into_owned(),
4208 ));
4209 }),
4210 )
4211 })
4212 .when_some(relative_path, |menu, relative_path| {
4213 menu.entry(
4214 "Copy Relative Path",
4215 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
4216 window.handler_for(&editor, move |_, _, cx| {
4217 cx.write_to_clipboard(ClipboardItem::new_string(
4218 relative_path.display(path_style).to_string(),
4219 ));
4220 }),
4221 )
4222 })
4223 .when(
4224 reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
4225 |menu| menu.separator(),
4226 )
4227 .when_some(reveal_in_project_panel, |menu, entry_id| {
4228 menu.entry(
4229 "Reveal In Project Panel",
4230 Some(Box::new(RevealInProjectPanel::default())),
4231 window.handler_for(&editor, move |editor, _, cx| {
4232 if let Some(project) = &mut editor.project {
4233 project.update(cx, |_, cx| {
4234 cx.emit(project::Event::RevealInProjectPanel(
4235 entry_id,
4236 ))
4237 });
4238 }
4239 }),
4240 )
4241 })
4242 .when_some(parent_abs_path, |menu, parent_abs_path| {
4243 menu.entry(
4244 "Open in Terminal",
4245 Some(Box::new(OpenInTerminal)),
4246 window.handler_for(&editor, move |_, window, cx| {
4247 window.dispatch_action(
4248 OpenTerminal {
4249 working_directory: parent_abs_path.clone(),
4250 }
4251 .boxed_clone(),
4252 cx,
4253 );
4254 }),
4255 )
4256 });
4257 }
4258
4259 menu.context(menu_context)
4260 })
4261 })
4262 }
4263
4264 fn render_blocks(
4265 &self,
4266 rows: Range<DisplayRow>,
4267 snapshot: &EditorSnapshot,
4268 hitbox: &Hitbox,
4269 text_hitbox: &Hitbox,
4270 editor_width: Pixels,
4271 scroll_width: &mut Pixels,
4272 editor_margins: &EditorMargins,
4273 em_width: Pixels,
4274 text_x: Pixels,
4275 line_height: Pixels,
4276 line_layouts: &mut [LineWithInvisibles],
4277 selections: &[Selection<Point>],
4278 selected_buffer_ids: &Vec<BufferId>,
4279 latest_selection_anchors: &HashMap<BufferId, Anchor>,
4280 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4281 sticky_header_excerpt_id: Option<ExcerptId>,
4282 window: &mut Window,
4283 cx: &mut App,
4284 ) -> RenderBlocksOutput {
4285 let (fixed_blocks, non_fixed_blocks) = snapshot
4286 .blocks_in_range(rows.clone())
4287 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
4288
4289 let mut focused_block = self
4290 .editor
4291 .update(cx, |editor, _| editor.take_focused_block());
4292 let mut fixed_block_max_width = Pixels::ZERO;
4293 let mut blocks = Vec::new();
4294 let mut resized_blocks = HashMap::default();
4295 let mut row_block_types = HashMap::default();
4296 let mut block_resize_offset: i32 = 0;
4297
4298 for (row, block) in fixed_blocks {
4299 let block_id = block.id();
4300
4301 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4302 focused_block = None;
4303 }
4304
4305 if let Some((element, element_size, row, x_offset)) = self.render_block(
4306 block,
4307 AvailableSpace::MinContent,
4308 block_id,
4309 row,
4310 snapshot,
4311 text_x,
4312 &rows,
4313 line_layouts,
4314 editor_margins,
4315 line_height,
4316 em_width,
4317 text_hitbox,
4318 editor_width,
4319 scroll_width,
4320 &mut resized_blocks,
4321 &mut row_block_types,
4322 selections,
4323 selected_buffer_ids,
4324 latest_selection_anchors,
4325 is_row_soft_wrapped,
4326 sticky_header_excerpt_id,
4327 &mut block_resize_offset,
4328 window,
4329 cx,
4330 ) {
4331 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
4332 blocks.push(BlockLayout {
4333 id: block_id,
4334 x_offset,
4335 row: Some(row),
4336 element,
4337 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
4338 style: BlockStyle::Fixed,
4339 overlaps_gutter: true,
4340 is_buffer_header: block.is_buffer_header(),
4341 });
4342 }
4343 }
4344
4345 for (row, block) in non_fixed_blocks {
4346 let style = block.style();
4347 let width = match (style, block.place_near()) {
4348 (_, true) => AvailableSpace::MinContent,
4349 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
4350 (BlockStyle::Flex, _) => hitbox
4351 .size
4352 .width
4353 .max(fixed_block_max_width)
4354 .max(editor_margins.gutter.width + *scroll_width)
4355 .into(),
4356 (BlockStyle::Fixed, _) => unreachable!(),
4357 };
4358 let block_id = block.id();
4359
4360 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4361 focused_block = None;
4362 }
4363
4364 if let Some((element, element_size, row, x_offset)) = self.render_block(
4365 block,
4366 width,
4367 block_id,
4368 row,
4369 snapshot,
4370 text_x,
4371 &rows,
4372 line_layouts,
4373 editor_margins,
4374 line_height,
4375 em_width,
4376 text_hitbox,
4377 editor_width,
4378 scroll_width,
4379 &mut resized_blocks,
4380 &mut row_block_types,
4381 selections,
4382 selected_buffer_ids,
4383 latest_selection_anchors,
4384 is_row_soft_wrapped,
4385 sticky_header_excerpt_id,
4386 &mut block_resize_offset,
4387 window,
4388 cx,
4389 ) {
4390 blocks.push(BlockLayout {
4391 id: block_id,
4392 x_offset,
4393 row: Some(row),
4394 element,
4395 available_space: size(width, element_size.height.into()),
4396 style,
4397 overlaps_gutter: !block.place_near(),
4398 is_buffer_header: block.is_buffer_header(),
4399 });
4400 }
4401 }
4402
4403 if let Some(focused_block) = focused_block
4404 && let Some(focus_handle) = focused_block.focus_handle.upgrade()
4405 && focus_handle.is_focused(window)
4406 && let Some(block) = snapshot.block_for_id(focused_block.id)
4407 {
4408 let style = block.style();
4409 let width = match style {
4410 BlockStyle::Fixed => AvailableSpace::MinContent,
4411 BlockStyle::Flex => AvailableSpace::Definite(
4412 hitbox
4413 .size
4414 .width
4415 .max(fixed_block_max_width)
4416 .max(editor_margins.gutter.width + *scroll_width),
4417 ),
4418 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
4419 };
4420
4421 if let Some((element, element_size, _, x_offset)) = self.render_block(
4422 &block,
4423 width,
4424 focused_block.id,
4425 rows.end,
4426 snapshot,
4427 text_x,
4428 &rows,
4429 line_layouts,
4430 editor_margins,
4431 line_height,
4432 em_width,
4433 text_hitbox,
4434 editor_width,
4435 scroll_width,
4436 &mut resized_blocks,
4437 &mut row_block_types,
4438 selections,
4439 selected_buffer_ids,
4440 latest_selection_anchors,
4441 is_row_soft_wrapped,
4442 sticky_header_excerpt_id,
4443 &mut block_resize_offset,
4444 window,
4445 cx,
4446 ) {
4447 blocks.push(BlockLayout {
4448 id: block.id(),
4449 x_offset,
4450 row: None,
4451 element,
4452 available_space: size(width, element_size.height.into()),
4453 style,
4454 overlaps_gutter: true,
4455 is_buffer_header: block.is_buffer_header(),
4456 });
4457 }
4458 }
4459
4460 if resized_blocks.is_empty() {
4461 *scroll_width =
4462 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
4463 }
4464
4465 RenderBlocksOutput {
4466 blocks,
4467 row_block_types,
4468 resized_blocks: (!resized_blocks.is_empty()).then_some(resized_blocks),
4469 }
4470 }
4471
4472 fn layout_blocks(
4473 &self,
4474 blocks: &mut Vec<BlockLayout>,
4475 hitbox: &Hitbox,
4476 line_height: Pixels,
4477 scroll_position: gpui::Point<ScrollOffset>,
4478 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4479 window: &mut Window,
4480 cx: &mut App,
4481 ) {
4482 for block in blocks {
4483 let mut origin = if let Some(row) = block.row {
4484 hitbox.origin
4485 + point(
4486 block.x_offset,
4487 Pixels::from(
4488 (row.as_f64() - scroll_position.y)
4489 * ScrollPixelOffset::from(line_height),
4490 ),
4491 )
4492 } else {
4493 // Position the block outside the visible area
4494 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
4495 };
4496
4497 if !matches!(block.style, BlockStyle::Sticky) {
4498 origin += point(Pixels::from(-scroll_pixel_position.x), Pixels::ZERO);
4499 }
4500
4501 let focus_handle =
4502 block
4503 .element
4504 .prepaint_as_root(origin, block.available_space, window, cx);
4505
4506 if let Some(focus_handle) = focus_handle {
4507 self.editor.update(cx, |editor, _cx| {
4508 editor.set_focused_block(FocusedBlock {
4509 id: block.id,
4510 focus_handle: focus_handle.downgrade(),
4511 });
4512 });
4513 }
4514 }
4515 }
4516
4517 fn layout_sticky_buffer_header(
4518 &self,
4519 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
4520 scroll_position: gpui::Point<ScrollOffset>,
4521 line_height: Pixels,
4522 right_margin: Pixels,
4523 snapshot: &EditorSnapshot,
4524 hitbox: &Hitbox,
4525 selected_buffer_ids: &Vec<BufferId>,
4526 blocks: &[BlockLayout],
4527 latest_selection_anchors: &HashMap<BufferId, Anchor>,
4528 window: &mut Window,
4529 cx: &mut App,
4530 ) -> AnyElement {
4531 let jump_data = header_jump_data(
4532 snapshot,
4533 DisplayRow(scroll_position.y as u32),
4534 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4535 excerpt,
4536 latest_selection_anchors,
4537 );
4538
4539 let editor_bg_color = cx.theme().colors().editor_background;
4540
4541 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4542
4543 let available_width = hitbox.bounds.size.width - right_margin;
4544
4545 let mut header = v_flex()
4546 .w_full()
4547 .relative()
4548 .child(
4549 div()
4550 .w(available_width)
4551 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4552 .bg(linear_gradient(
4553 0.,
4554 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4555 linear_color_stop(editor_bg_color, 0.6),
4556 ))
4557 .absolute()
4558 .top_0(),
4559 )
4560 .child(
4561 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4562 .into_any_element(),
4563 )
4564 .into_any_element();
4565
4566 let mut origin = hitbox.origin;
4567 // Move floating header up to avoid colliding with the next buffer header.
4568 for block in blocks.iter() {
4569 if !block.is_buffer_header {
4570 continue;
4571 }
4572
4573 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position.y as u32) else {
4574 continue;
4575 };
4576
4577 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4578 let offset = scroll_position.y - max_row as f64;
4579
4580 if offset > 0.0 {
4581 origin.y -= Pixels::from(offset * ScrollPixelOffset::from(line_height));
4582 }
4583 break;
4584 }
4585
4586 let size = size(
4587 AvailableSpace::Definite(available_width),
4588 AvailableSpace::MinContent,
4589 );
4590
4591 header.prepaint_as_root(origin, size, window, cx);
4592
4593 header
4594 }
4595
4596 fn layout_sticky_headers(
4597 &self,
4598 snapshot: &EditorSnapshot,
4599 editor_width: Pixels,
4600 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4601 line_height: Pixels,
4602 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4603 content_origin: gpui::Point<Pixels>,
4604 gutter_dimensions: &GutterDimensions,
4605 gutter_hitbox: &Hitbox,
4606 text_hitbox: &Hitbox,
4607 style: &EditorStyle,
4608 relative_line_numbers: RelativeLineNumbers,
4609 relative_to: Option<DisplayRow>,
4610 window: &mut Window,
4611 cx: &mut App,
4612 ) -> Option<StickyHeaders> {
4613 let show_line_numbers = snapshot
4614 .show_line_numbers
4615 .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
4616
4617 let rows = Self::sticky_headers(self.editor.read(cx), snapshot, style, cx);
4618
4619 let mut lines = Vec::<StickyHeaderLine>::new();
4620
4621 for StickyHeader {
4622 item,
4623 sticky_row,
4624 start_point,
4625 offset,
4626 } in rows.into_iter().rev()
4627 {
4628 let line = layout_line(
4629 sticky_row,
4630 snapshot,
4631 &self.style,
4632 editor_width,
4633 is_row_soft_wrapped,
4634 window,
4635 cx,
4636 );
4637
4638 let line_number = show_line_numbers.then(|| {
4639 let relative_number = relative_to.and_then(|base| match relative_line_numbers {
4640 RelativeLineNumbers::Disabled => None,
4641 RelativeLineNumbers::Enabled => {
4642 Some(snapshot.relative_line_delta_to_point(base, start_point))
4643 }
4644 RelativeLineNumbers::Wrapped => {
4645 Some(snapshot.relative_wrapped_line_delta_to_point(base, start_point))
4646 }
4647 });
4648 let number = relative_number
4649 .filter(|&delta| delta != 0)
4650 .map(|delta| delta.unsigned_abs() as u32)
4651 .unwrap_or(start_point.row + 1);
4652 let color = cx.theme().colors().editor_line_number;
4653 self.shape_line_number(SharedString::from(number.to_string()), color, window)
4654 });
4655
4656 lines.push(StickyHeaderLine::new(
4657 sticky_row,
4658 line_height * offset as f32,
4659 line,
4660 line_number,
4661 item.range.start,
4662 line_height,
4663 scroll_pixel_position,
4664 content_origin,
4665 gutter_hitbox,
4666 text_hitbox,
4667 window,
4668 cx,
4669 ));
4670 }
4671
4672 lines.reverse();
4673 if lines.is_empty() {
4674 return None;
4675 }
4676
4677 Some(StickyHeaders {
4678 lines,
4679 gutter_background: cx.theme().colors().editor_gutter_background,
4680 content_background: self.style.background,
4681 gutter_right_padding: gutter_dimensions.right_padding,
4682 })
4683 }
4684
4685 pub(crate) fn sticky_headers(
4686 editor: &Editor,
4687 snapshot: &EditorSnapshot,
4688 style: &EditorStyle,
4689 cx: &App,
4690 ) -> Vec<StickyHeader> {
4691 let scroll_top = snapshot.scroll_position().y;
4692
4693 let mut end_rows = Vec::<DisplayRow>::new();
4694 let mut rows = Vec::<StickyHeader>::new();
4695
4696 let items = editor.sticky_headers(style, cx).unwrap_or_default();
4697
4698 for item in items {
4699 let start_point = item.range.start.to_point(snapshot.buffer_snapshot());
4700 let end_point = item.range.end.to_point(snapshot.buffer_snapshot());
4701
4702 let sticky_row = snapshot
4703 .display_snapshot
4704 .point_to_display_point(start_point, Bias::Left)
4705 .row();
4706 let end_row = snapshot
4707 .display_snapshot
4708 .point_to_display_point(end_point, Bias::Left)
4709 .row();
4710 let max_sticky_row = end_row.previous_row();
4711 if max_sticky_row <= sticky_row {
4712 continue;
4713 }
4714
4715 while end_rows
4716 .last()
4717 .is_some_and(|&last_end| last_end < sticky_row)
4718 {
4719 end_rows.pop();
4720 }
4721 let depth = end_rows.len();
4722 let adjusted_scroll_top = scroll_top + depth as f64;
4723
4724 if sticky_row.as_f64() >= adjusted_scroll_top || end_row.as_f64() <= adjusted_scroll_top
4725 {
4726 continue;
4727 }
4728
4729 let max_scroll_offset = max_sticky_row.as_f64() - scroll_top;
4730 let offset = (depth as f64).min(max_scroll_offset);
4731
4732 end_rows.push(end_row);
4733 rows.push(StickyHeader {
4734 item,
4735 sticky_row,
4736 start_point,
4737 offset,
4738 });
4739 }
4740
4741 rows
4742 }
4743
4744 fn layout_cursor_popovers(
4745 &self,
4746 line_height: Pixels,
4747 text_hitbox: &Hitbox,
4748 content_origin: gpui::Point<Pixels>,
4749 right_margin: Pixels,
4750 start_row: DisplayRow,
4751 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4752 line_layouts: &[LineWithInvisibles],
4753 cursor: DisplayPoint,
4754 cursor_point: Point,
4755 style: &EditorStyle,
4756 window: &mut Window,
4757 cx: &mut App,
4758 ) -> Option<ContextMenuLayout> {
4759 let mut min_menu_height = Pixels::ZERO;
4760 let mut max_menu_height = Pixels::ZERO;
4761 let mut height_above_menu = Pixels::ZERO;
4762 let height_below_menu = Pixels::ZERO;
4763 let mut edit_prediction_popover_visible = false;
4764 let mut context_menu_visible = false;
4765 let context_menu_placement;
4766
4767 {
4768 let editor = self.editor.read(cx);
4769 if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
4770 {
4771 height_above_menu +=
4772 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4773 edit_prediction_popover_visible = true;
4774 }
4775
4776 if editor.context_menu_visible()
4777 && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
4778 {
4779 let (min_height_in_lines, max_height_in_lines) = editor
4780 .context_menu_options
4781 .as_ref()
4782 .map_or((3, 12), |options| {
4783 (options.min_entries_visible, options.max_entries_visible)
4784 });
4785
4786 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4787 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4788 context_menu_visible = true;
4789 }
4790 context_menu_placement = editor
4791 .context_menu_options
4792 .as_ref()
4793 .and_then(|options| options.placement.clone());
4794 }
4795
4796 let visible = edit_prediction_popover_visible || context_menu_visible;
4797 if !visible {
4798 return None;
4799 }
4800
4801 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4802 let target_position = content_origin
4803 + gpui::Point {
4804 x: cmp::max(
4805 px(0.),
4806 Pixels::from(
4807 ScrollPixelOffset::from(
4808 cursor_row_layout.x_for_index(cursor.column() as usize),
4809 ) - scroll_pixel_position.x,
4810 ),
4811 ),
4812 y: cmp::max(
4813 px(0.),
4814 Pixels::from(
4815 cursor.row().next_row().as_f64() * ScrollPixelOffset::from(line_height)
4816 - scroll_pixel_position.y,
4817 ),
4818 ),
4819 };
4820
4821 let viewport_bounds =
4822 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4823 right: -right_margin - MENU_GAP,
4824 ..Default::default()
4825 });
4826
4827 let min_height = height_above_menu + min_menu_height + height_below_menu;
4828 let max_height = height_above_menu + max_menu_height + height_below_menu;
4829 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4830 target_position,
4831 line_height,
4832 min_height,
4833 max_height,
4834 context_menu_placement,
4835 text_hitbox,
4836 viewport_bounds,
4837 window,
4838 cx,
4839 |height, max_width_for_stable_x, y_flipped, window, cx| {
4840 // First layout the menu to get its size - others can be at least this wide.
4841 let context_menu = if context_menu_visible {
4842 let menu_height = if y_flipped {
4843 height - height_below_menu
4844 } else {
4845 height - height_above_menu
4846 };
4847 let mut element = self
4848 .render_context_menu(line_height, menu_height, window, cx)
4849 .expect("Visible context menu should always render.");
4850 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4851 Some((CursorPopoverType::CodeContextMenu, element, size))
4852 } else {
4853 None
4854 };
4855 let min_width = context_menu
4856 .as_ref()
4857 .map_or(px(0.), |(_, _, size)| size.width);
4858 let max_width = max_width_for_stable_x.max(
4859 context_menu
4860 .as_ref()
4861 .map_or(px(0.), |(_, _, size)| size.width),
4862 );
4863
4864 let edit_prediction = if edit_prediction_popover_visible {
4865 self.editor.update(cx, move |editor, cx| {
4866 let accept_binding = editor.accept_edit_prediction_keybind(
4867 EditPredictionGranularity::Full,
4868 window,
4869 cx,
4870 );
4871 let mut element = editor.render_edit_prediction_cursor_popover(
4872 min_width,
4873 max_width,
4874 cursor_point,
4875 style,
4876 accept_binding.keystroke(),
4877 window,
4878 cx,
4879 )?;
4880 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4881 Some((CursorPopoverType::EditPrediction, element, size))
4882 })
4883 } else {
4884 None
4885 };
4886 vec![edit_prediction, context_menu]
4887 .into_iter()
4888 .flatten()
4889 .collect::<Vec<_>>()
4890 },
4891 )?;
4892
4893 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4894 .iter()
4895 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4896 let last_ix = laid_out_popovers.len() - 1;
4897 let menu_is_last = menu_ix == last_ix;
4898 let first_popover_bounds = laid_out_popovers[0].1;
4899 let last_popover_bounds = laid_out_popovers[last_ix].1;
4900
4901 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4902 // right, and otherwise it goes below or to the right.
4903 let mut target_bounds = Bounds::from_corners(
4904 first_popover_bounds.origin,
4905 last_popover_bounds.bottom_right(),
4906 );
4907 target_bounds.size.width = menu_bounds.size.width;
4908
4909 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4910 // based on this is preferred for layout stability.
4911 let mut max_target_bounds = target_bounds;
4912 max_target_bounds.size.height = max_height;
4913 if y_flipped {
4914 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4915 }
4916
4917 // Add spacing around `target_bounds` and `max_target_bounds`.
4918 let mut extend_amount = Edges::all(MENU_GAP);
4919 if y_flipped {
4920 extend_amount.bottom = line_height;
4921 } else {
4922 extend_amount.top = line_height;
4923 }
4924 let target_bounds = target_bounds.extend(extend_amount);
4925 let max_target_bounds = max_target_bounds.extend(extend_amount);
4926
4927 let must_place_above_or_below =
4928 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4929 laid_out_popovers[menu_ix + 1..]
4930 .iter()
4931 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4932 } else {
4933 false
4934 };
4935
4936 let aside_bounds = self.layout_context_menu_aside(
4937 y_flipped,
4938 *menu_bounds,
4939 target_bounds,
4940 max_target_bounds,
4941 max_menu_height,
4942 must_place_above_or_below,
4943 text_hitbox,
4944 viewport_bounds,
4945 window,
4946 cx,
4947 );
4948
4949 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4950 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4951 Some(*bounds)
4952 } else {
4953 None
4954 }
4955 }) {
4956 let bounds = if let Some(aside_bounds) = aside_bounds {
4957 menu_bounds.union(&aside_bounds)
4958 } else {
4959 menu_bounds
4960 };
4961 return Some(ContextMenuLayout { y_flipped, bounds });
4962 }
4963
4964 None
4965 }
4966
4967 fn layout_gutter_menu(
4968 &self,
4969 line_height: Pixels,
4970 text_hitbox: &Hitbox,
4971 content_origin: gpui::Point<Pixels>,
4972 right_margin: Pixels,
4973 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
4974 gutter_overshoot: Pixels,
4975 window: &mut Window,
4976 cx: &mut App,
4977 ) {
4978 let editor = self.editor.read(cx);
4979 if !editor.context_menu_visible() {
4980 return;
4981 }
4982 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4983 editor.context_menu_origin()
4984 else {
4985 return;
4986 };
4987 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4988 // indicator than just a plain first column of the text field.
4989 let target_position = content_origin
4990 + gpui::Point {
4991 x: -gutter_overshoot,
4992 y: Pixels::from(
4993 gutter_row.next_row().as_f64() * ScrollPixelOffset::from(line_height)
4994 - scroll_pixel_position.y,
4995 ),
4996 };
4997
4998 let (min_height_in_lines, max_height_in_lines) = editor
4999 .context_menu_options
5000 .as_ref()
5001 .map_or((3, 12), |options| {
5002 (options.min_entries_visible, options.max_entries_visible)
5003 });
5004
5005 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
5006 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
5007 let viewport_bounds =
5008 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
5009 right: -right_margin - MENU_GAP,
5010 ..Default::default()
5011 });
5012 self.layout_popovers_above_or_below_line(
5013 target_position,
5014 line_height,
5015 min_height,
5016 max_height,
5017 editor
5018 .context_menu_options
5019 .as_ref()
5020 .and_then(|options| options.placement.clone()),
5021 text_hitbox,
5022 viewport_bounds,
5023 window,
5024 cx,
5025 move |height, _max_width_for_stable_x, _, window, cx| {
5026 let mut element = self
5027 .render_context_menu(line_height, height, window, cx)
5028 .expect("Visible context menu should always render.");
5029 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
5030 vec![(CursorPopoverType::CodeContextMenu, element, size)]
5031 },
5032 );
5033 }
5034
5035 fn layout_popovers_above_or_below_line(
5036 &self,
5037 target_position: gpui::Point<Pixels>,
5038 line_height: Pixels,
5039 min_height: Pixels,
5040 max_height: Pixels,
5041 placement: Option<ContextMenuPlacement>,
5042 text_hitbox: &Hitbox,
5043 viewport_bounds: Bounds<Pixels>,
5044 window: &mut Window,
5045 cx: &mut App,
5046 make_sized_popovers: impl FnOnce(
5047 Pixels,
5048 Pixels,
5049 bool,
5050 &mut Window,
5051 &mut App,
5052 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
5053 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
5054 let text_style = TextStyleRefinement {
5055 line_height: Some(DefiniteLength::Fraction(
5056 BufferLineHeight::Comfortable.value(),
5057 )),
5058 ..Default::default()
5059 };
5060 window.with_text_style(Some(text_style), |window| {
5061 // If the max height won't fit below and there is more space above, put it above the line.
5062 let bottom_y_when_flipped = target_position.y - line_height;
5063 let available_above = bottom_y_when_flipped - text_hitbox.top();
5064 let available_below = text_hitbox.bottom() - target_position.y;
5065 let y_overflows_below = max_height > available_below;
5066 let mut y_flipped = match placement {
5067 Some(ContextMenuPlacement::Above) => true,
5068 Some(ContextMenuPlacement::Below) => false,
5069 None => y_overflows_below && available_above > available_below,
5070 };
5071 let mut height = cmp::min(
5072 max_height,
5073 if y_flipped {
5074 available_above
5075 } else {
5076 available_below
5077 },
5078 );
5079
5080 // If the min height doesn't fit within text bounds, instead fit within the window.
5081 if height < min_height {
5082 let available_above = bottom_y_when_flipped;
5083 let available_below = viewport_bounds.bottom() - target_position.y;
5084 let (y_flipped_override, height_override) = match placement {
5085 Some(ContextMenuPlacement::Above) => {
5086 (true, cmp::min(available_above, min_height))
5087 }
5088 Some(ContextMenuPlacement::Below) => {
5089 (false, cmp::min(available_below, min_height))
5090 }
5091 None => {
5092 if available_below > min_height {
5093 (false, min_height)
5094 } else if available_above > min_height {
5095 (true, min_height)
5096 } else if available_above > available_below {
5097 (true, available_above)
5098 } else {
5099 (false, available_below)
5100 }
5101 }
5102 };
5103 y_flipped = y_flipped_override;
5104 height = height_override;
5105 }
5106
5107 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
5108
5109 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
5110 // for very narrow windows.
5111 let popovers =
5112 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
5113 if popovers.is_empty() {
5114 return None;
5115 }
5116
5117 let max_width = popovers
5118 .iter()
5119 .map(|(_, _, size)| size.width)
5120 .max()
5121 .unwrap_or_default();
5122
5123 let mut current_position = gpui::Point {
5124 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
5125 // overflow. Include space for the scrollbar.
5126 x: target_position
5127 .x
5128 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
5129 y: if y_flipped {
5130 bottom_y_when_flipped
5131 } else {
5132 target_position.y
5133 },
5134 };
5135
5136 let mut laid_out_popovers = popovers
5137 .into_iter()
5138 .map(|(popover_type, element, size)| {
5139 if y_flipped {
5140 current_position.y -= size.height;
5141 }
5142 let position = current_position;
5143 window.defer_draw(element, current_position, 1);
5144 if !y_flipped {
5145 current_position.y += size.height + MENU_GAP;
5146 } else {
5147 current_position.y -= MENU_GAP;
5148 }
5149 (popover_type, Bounds::new(position, size))
5150 })
5151 .collect::<Vec<_>>();
5152
5153 if y_flipped {
5154 laid_out_popovers.reverse();
5155 }
5156
5157 Some((laid_out_popovers, y_flipped))
5158 })
5159 }
5160
5161 fn layout_context_menu_aside(
5162 &self,
5163 y_flipped: bool,
5164 menu_bounds: Bounds<Pixels>,
5165 target_bounds: Bounds<Pixels>,
5166 max_target_bounds: Bounds<Pixels>,
5167 max_height: Pixels,
5168 must_place_above_or_below: bool,
5169 text_hitbox: &Hitbox,
5170 viewport_bounds: Bounds<Pixels>,
5171 window: &mut Window,
5172 cx: &mut App,
5173 ) -> Option<Bounds<Pixels>> {
5174 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
5175 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
5176 && !must_place_above_or_below
5177 {
5178 let max_width = cmp::min(
5179 available_within_viewport.right - px(1.),
5180 MENU_ASIDE_MAX_WIDTH,
5181 );
5182 let mut aside = self.render_context_menu_aside(
5183 size(max_width, max_height - POPOVER_Y_PADDING),
5184 window,
5185 cx,
5186 )?;
5187 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5188 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
5189 Some((aside, right_position, size))
5190 } else {
5191 let max_size = size(
5192 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
5193 // won't be needed here.
5194 cmp::min(
5195 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
5196 viewport_bounds.right(),
5197 ),
5198 cmp::min(
5199 max_height,
5200 cmp::max(
5201 available_within_viewport.top,
5202 available_within_viewport.bottom,
5203 ),
5204 ) - POPOVER_Y_PADDING,
5205 );
5206 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
5207 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
5208
5209 let top_position = point(
5210 menu_bounds.origin.x,
5211 target_bounds.top() - actual_size.height,
5212 );
5213 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
5214
5215 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
5216 // Prefer to fit on the same side of the line as the menu, then on the other side of
5217 // the line.
5218 if !y_flipped && wanted.height < available.bottom {
5219 Some(bottom_position)
5220 } else if !y_flipped && wanted.height < available.top {
5221 Some(top_position)
5222 } else if y_flipped && wanted.height < available.top {
5223 Some(top_position)
5224 } else if y_flipped && wanted.height < available.bottom {
5225 Some(bottom_position)
5226 } else {
5227 None
5228 }
5229 };
5230
5231 // Prefer choosing a direction using max sizes rather than actual size for stability.
5232 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
5233 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
5234 let aside_position = fit_within(available_within_text, wanted)
5235 // Fallback: fit max size in window.
5236 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
5237 // Fallback: fit actual size in window.
5238 .or_else(|| fit_within(available_within_viewport, actual_size));
5239
5240 aside_position.map(|position| (aside, position, actual_size))
5241 };
5242
5243 // Skip drawing if it doesn't fit anywhere.
5244 if let Some((aside, position, size)) = positioned_aside {
5245 let aside_bounds = Bounds::new(position, size);
5246 window.defer_draw(aside, position, 2);
5247 return Some(aside_bounds);
5248 }
5249
5250 None
5251 }
5252
5253 fn render_context_menu(
5254 &self,
5255 line_height: Pixels,
5256 height: Pixels,
5257 window: &mut Window,
5258 cx: &mut App,
5259 ) -> Option<AnyElement> {
5260 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
5261 self.editor.update(cx, |editor, cx| {
5262 editor.render_context_menu(max_height_in_lines, window, cx)
5263 })
5264 }
5265
5266 fn render_context_menu_aside(
5267 &self,
5268 max_size: Size<Pixels>,
5269 window: &mut Window,
5270 cx: &mut App,
5271 ) -> Option<AnyElement> {
5272 if max_size.width < px(100.) || max_size.height < px(12.) {
5273 None
5274 } else {
5275 self.editor.update(cx, |editor, cx| {
5276 editor.render_context_menu_aside(max_size, window, cx)
5277 })
5278 }
5279 }
5280
5281 fn layout_mouse_context_menu(
5282 &self,
5283 editor_snapshot: &EditorSnapshot,
5284 visible_range: Range<DisplayRow>,
5285 content_origin: gpui::Point<Pixels>,
5286 window: &mut Window,
5287 cx: &mut App,
5288 ) -> Option<AnyElement> {
5289 let position = self.editor.update(cx, |editor, cx| {
5290 let visible_start_point = editor.display_to_pixel_point(
5291 DisplayPoint::new(visible_range.start, 0),
5292 editor_snapshot,
5293 window,
5294 cx,
5295 )?;
5296 let visible_end_point = editor.display_to_pixel_point(
5297 DisplayPoint::new(visible_range.end, 0),
5298 editor_snapshot,
5299 window,
5300 cx,
5301 )?;
5302
5303 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5304 let (source_display_point, position) = match mouse_context_menu.position {
5305 MenuPosition::PinnedToScreen(point) => (None, point),
5306 MenuPosition::PinnedToEditor { source, offset } => {
5307 let source_display_point = source.to_display_point(editor_snapshot);
5308 let source_point =
5309 editor.to_pixel_point(source, editor_snapshot, window, cx)?;
5310 let position = content_origin + source_point + offset;
5311 (Some(source_display_point), position)
5312 }
5313 };
5314
5315 let source_included = source_display_point.is_none_or(|source_display_point| {
5316 visible_range
5317 .to_inclusive()
5318 .contains(&source_display_point.row())
5319 });
5320 let position_included =
5321 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
5322 if !source_included && !position_included {
5323 None
5324 } else {
5325 Some(position)
5326 }
5327 })?;
5328
5329 let text_style = TextStyleRefinement {
5330 line_height: Some(DefiniteLength::Fraction(
5331 BufferLineHeight::Comfortable.value(),
5332 )),
5333 ..Default::default()
5334 };
5335 window.with_text_style(Some(text_style), |window| {
5336 let mut element = self.editor.read_with(cx, |editor, _| {
5337 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
5338 let context_menu = mouse_context_menu.context_menu.clone();
5339
5340 Some(
5341 deferred(
5342 anchored()
5343 .position(position)
5344 .child(context_menu)
5345 .anchor(Corner::TopLeft)
5346 .snap_to_window_with_margin(px(8.)),
5347 )
5348 .with_priority(1)
5349 .into_any(),
5350 )
5351 })?;
5352
5353 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
5354 Some(element)
5355 })
5356 }
5357
5358 fn layout_hover_popovers(
5359 &self,
5360 snapshot: &EditorSnapshot,
5361 hitbox: &Hitbox,
5362 visible_display_row_range: Range<DisplayRow>,
5363 content_origin: gpui::Point<Pixels>,
5364 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5365 line_layouts: &[LineWithInvisibles],
5366 line_height: Pixels,
5367 em_width: Pixels,
5368 context_menu_layout: Option<ContextMenuLayout>,
5369 window: &mut Window,
5370 cx: &mut App,
5371 ) {
5372 struct MeasuredHoverPopover {
5373 element: AnyElement,
5374 size: Size<Pixels>,
5375 horizontal_offset: Pixels,
5376 }
5377
5378 let max_size = size(
5379 (120. * em_width) // Default size
5380 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5381 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5382 (16. * line_height) // Default size
5383 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5384 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5385 );
5386
5387 // Don't show hover popovers when context menu is open to avoid overlap
5388 let has_context_menu = self.editor.read(cx).mouse_context_menu.is_some();
5389 if has_context_menu {
5390 return;
5391 }
5392
5393 let hover_popovers = self.editor.update(cx, |editor, cx| {
5394 editor.hover_state.render(
5395 snapshot,
5396 visible_display_row_range.clone(),
5397 max_size,
5398 &editor.text_layout_details(window),
5399 window,
5400 cx,
5401 )
5402 });
5403 let Some((popover_position, hover_popovers)) = hover_popovers else {
5404 return;
5405 };
5406
5407 // This is safe because we check on layout whether the required row is available
5408 let hovered_row_layout = &line_layouts[popover_position
5409 .row()
5410 .minus(visible_display_row_range.start)
5411 as usize];
5412
5413 // Compute Hovered Point
5414 let x = hovered_row_layout.x_for_index(popover_position.column() as usize)
5415 - Pixels::from(scroll_pixel_position.x);
5416 let y = Pixels::from(
5417 popover_position.row().as_f64() * ScrollPixelOffset::from(line_height)
5418 - scroll_pixel_position.y,
5419 );
5420 let hovered_point = content_origin + point(x, y);
5421
5422 let mut overall_height = Pixels::ZERO;
5423 let mut measured_hover_popovers = Vec::new();
5424 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
5425 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
5426 let horizontal_offset =
5427 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
5428 .min(Pixels::ZERO);
5429 match position {
5430 itertools::Position::Middle | itertools::Position::Last => {
5431 overall_height += HOVER_POPOVER_GAP
5432 }
5433 _ => {}
5434 }
5435 overall_height += size.height;
5436 measured_hover_popovers.push(MeasuredHoverPopover {
5437 element: hover_popover,
5438 size,
5439 horizontal_offset,
5440 });
5441 }
5442
5443 fn draw_occluder(
5444 width: Pixels,
5445 origin: gpui::Point<Pixels>,
5446 window: &mut Window,
5447 cx: &mut App,
5448 ) {
5449 let mut occlusion = div()
5450 .size_full()
5451 .occlude()
5452 .on_mouse_move(|_, _, cx| cx.stop_propagation())
5453 .into_any_element();
5454 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
5455 window.defer_draw(occlusion, origin, 2);
5456 }
5457
5458 fn place_popovers_above(
5459 hovered_point: gpui::Point<Pixels>,
5460 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5461 window: &mut Window,
5462 cx: &mut App,
5463 ) {
5464 let mut current_y = hovered_point.y;
5465 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5466 let size = popover.size;
5467 let popover_origin = point(
5468 hovered_point.x + popover.horizontal_offset,
5469 current_y - size.height,
5470 );
5471
5472 window.defer_draw(popover.element, popover_origin, 2);
5473 if position != itertools::Position::Last {
5474 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
5475 draw_occluder(size.width, origin, window, cx);
5476 }
5477
5478 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5479 }
5480 }
5481
5482 fn place_popovers_below(
5483 hovered_point: gpui::Point<Pixels>,
5484 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5485 line_height: Pixels,
5486 window: &mut Window,
5487 cx: &mut App,
5488 ) {
5489 let mut current_y = hovered_point.y + line_height;
5490 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5491 let size = popover.size;
5492 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5493
5494 window.defer_draw(popover.element, popover_origin, 2);
5495 if position != itertools::Position::Last {
5496 let origin = point(popover_origin.x, popover_origin.y + size.height);
5497 draw_occluder(size.width, origin, window, cx);
5498 }
5499
5500 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5501 }
5502 }
5503
5504 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5505 context_menu_layout
5506 .as_ref()
5507 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5508 };
5509
5510 let can_place_above = {
5511 let mut bounds_above = Vec::new();
5512 let mut current_y = hovered_point.y;
5513 for popover in &measured_hover_popovers {
5514 let size = popover.size;
5515 let popover_origin = point(
5516 hovered_point.x + popover.horizontal_offset,
5517 current_y - size.height,
5518 );
5519 bounds_above.push(Bounds::new(popover_origin, size));
5520 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5521 }
5522 bounds_above
5523 .iter()
5524 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5525 };
5526
5527 let can_place_below = || {
5528 let mut bounds_below = Vec::new();
5529 let mut current_y = hovered_point.y + line_height;
5530 for popover in &measured_hover_popovers {
5531 let size = popover.size;
5532 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5533 bounds_below.push(Bounds::new(popover_origin, size));
5534 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5535 }
5536 bounds_below
5537 .iter()
5538 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5539 };
5540
5541 if can_place_above {
5542 // try placing above hovered point
5543 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5544 } else if can_place_below() {
5545 // try placing below hovered point
5546 place_popovers_below(
5547 hovered_point,
5548 measured_hover_popovers,
5549 line_height,
5550 window,
5551 cx,
5552 );
5553 } else {
5554 // try to place popovers around the context menu
5555 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5556 let total_width = measured_hover_popovers
5557 .iter()
5558 .map(|p| p.size.width)
5559 .max()
5560 .unwrap_or(Pixels::ZERO);
5561 let y_for_horizontal_positioning = if menu.y_flipped {
5562 menu.bounds.bottom() - overall_height
5563 } else {
5564 menu.bounds.top()
5565 };
5566 let possible_origins = vec![
5567 // left of context menu
5568 point(
5569 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
5570 y_for_horizontal_positioning,
5571 ),
5572 // right of context menu
5573 point(
5574 menu.bounds.right() + HOVER_POPOVER_GAP,
5575 y_for_horizontal_positioning,
5576 ),
5577 // top of context menu
5578 point(
5579 menu.bounds.left(),
5580 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
5581 ),
5582 // bottom of context menu
5583 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5584 ];
5585 possible_origins.into_iter().find(|&origin| {
5586 Bounds::new(origin, size(total_width, overall_height))
5587 .is_contained_within(hitbox)
5588 })
5589 });
5590 if let Some(origin) = origin_surrounding_menu {
5591 let mut current_y = origin.y;
5592 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5593 let size = popover.size;
5594 let popover_origin = point(origin.x, current_y);
5595
5596 window.defer_draw(popover.element, popover_origin, 2);
5597 if position != itertools::Position::Last {
5598 let origin = point(popover_origin.x, popover_origin.y + size.height);
5599 draw_occluder(size.width, origin, window, cx);
5600 }
5601
5602 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5603 }
5604 } else {
5605 // fallback to existing above/below cursor logic
5606 // this might overlap menu or overflow in rare case
5607 if can_place_above {
5608 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5609 } else {
5610 place_popovers_below(
5611 hovered_point,
5612 measured_hover_popovers,
5613 line_height,
5614 window,
5615 cx,
5616 );
5617 }
5618 }
5619 }
5620 }
5621
5622 fn layout_word_diff_highlights(
5623 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5624 row_infos: &[RowInfo],
5625 start_row: DisplayRow,
5626 snapshot: &EditorSnapshot,
5627 highlighted_ranges: &mut Vec<(Range<DisplayPoint>, Hsla)>,
5628 cx: &mut App,
5629 ) {
5630 let colors = cx.theme().colors();
5631
5632 let word_highlights = display_hunks
5633 .into_iter()
5634 .filter_map(|(hunk, _)| match hunk {
5635 DisplayDiffHunk::Unfolded {
5636 word_diffs, status, ..
5637 } => Some((word_diffs, status)),
5638 _ => None,
5639 })
5640 .filter(|(_, status)| status.is_modified())
5641 .flat_map(|(word_diffs, _)| word_diffs)
5642 .filter_map(|word_diff| {
5643 let start_point = word_diff.start.to_display_point(&snapshot.display_snapshot);
5644 let end_point = word_diff.end.to_display_point(&snapshot.display_snapshot);
5645 let start_row_offset = start_point.row().0.saturating_sub(start_row.0) as usize;
5646
5647 row_infos
5648 .get(start_row_offset)
5649 .and_then(|row_info| row_info.diff_status)
5650 .and_then(|diff_status| {
5651 let background_color = match diff_status.kind {
5652 DiffHunkStatusKind::Added => colors.version_control_word_added,
5653 DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,
5654 DiffHunkStatusKind::Modified => {
5655 debug_panic!("modified diff status for row info");
5656 return None;
5657 }
5658 };
5659 Some((start_point..end_point, background_color))
5660 })
5661 });
5662
5663 highlighted_ranges.extend(word_highlights);
5664 }
5665
5666 fn layout_diff_hunk_controls(
5667 &self,
5668 row_range: Range<DisplayRow>,
5669 row_infos: &[RowInfo],
5670 text_hitbox: &Hitbox,
5671 newest_cursor_position: Option<DisplayPoint>,
5672 line_height: Pixels,
5673 right_margin: Pixels,
5674 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5675 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5676 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
5677 editor: Entity<Editor>,
5678 window: &mut Window,
5679 cx: &mut App,
5680 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
5681 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
5682 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
5683
5684 let mut controls = vec![];
5685 let mut control_bounds = vec![];
5686
5687 let active_positions = [
5688 hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
5689 newest_cursor_position,
5690 ];
5691
5692 for (hunk, _) in display_hunks {
5693 if let DisplayDiffHunk::Unfolded {
5694 display_row_range,
5695 multi_buffer_range,
5696 status,
5697 is_created_file,
5698 ..
5699 } = &hunk
5700 {
5701 if display_row_range.start < row_range.start
5702 || display_row_range.start >= row_range.end
5703 {
5704 continue;
5705 }
5706 if highlighted_rows
5707 .get(&display_row_range.start)
5708 .and_then(|highlight| highlight.type_id)
5709 .is_some_and(|type_id| {
5710 [
5711 TypeId::of::<ConflictsOuter>(),
5712 TypeId::of::<ConflictsOursMarker>(),
5713 TypeId::of::<ConflictsOurs>(),
5714 TypeId::of::<ConflictsTheirs>(),
5715 TypeId::of::<ConflictsTheirsMarker>(),
5716 ]
5717 .contains(&type_id)
5718 })
5719 {
5720 continue;
5721 }
5722 let row_ix = (display_row_range.start - row_range.start).0 as usize;
5723 if row_infos[row_ix].diff_status.is_none() {
5724 continue;
5725 }
5726 if row_infos[row_ix]
5727 .diff_status
5728 .is_some_and(|status| status.is_added())
5729 && !status.is_added()
5730 {
5731 continue;
5732 }
5733
5734 if active_positions
5735 .iter()
5736 .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
5737 {
5738 let y = (display_row_range.start.as_f64()
5739 * ScrollPixelOffset::from(line_height)
5740 + ScrollPixelOffset::from(text_hitbox.bounds.top())
5741 - scroll_pixel_position.y)
5742 .into();
5743
5744 let mut element = render_diff_hunk_controls(
5745 display_row_range.start.0,
5746 status,
5747 multi_buffer_range.clone(),
5748 *is_created_file,
5749 line_height,
5750 &editor,
5751 window,
5752 cx,
5753 );
5754 let size =
5755 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5756
5757 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5758
5759 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5760 control_bounds.push((display_row_range.start, bounds));
5761
5762 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5763 element.prepaint(window, cx)
5764 });
5765 controls.push(element);
5766 }
5767 }
5768 }
5769
5770 (controls, control_bounds)
5771 }
5772
5773 fn layout_signature_help(
5774 &self,
5775 hitbox: &Hitbox,
5776 content_origin: gpui::Point<Pixels>,
5777 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
5778 newest_selection_head: Option<DisplayPoint>,
5779 start_row: DisplayRow,
5780 line_layouts: &[LineWithInvisibles],
5781 line_height: Pixels,
5782 em_width: Pixels,
5783 context_menu_layout: Option<ContextMenuLayout>,
5784 window: &mut Window,
5785 cx: &mut App,
5786 ) {
5787 if !self.editor.focus_handle(cx).is_focused(window) {
5788 return;
5789 }
5790 let Some(newest_selection_head) = newest_selection_head else {
5791 return;
5792 };
5793
5794 let max_size = size(
5795 (120. * em_width) // Default size
5796 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5797 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5798 (16. * line_height) // Default size
5799 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5800 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5801 );
5802
5803 let maybe_element = self.editor.update(cx, |editor, cx| {
5804 if let Some(popover) = editor.signature_help_state.popover_mut() {
5805 let element = popover.render(max_size, window, cx);
5806 Some(element)
5807 } else {
5808 None
5809 }
5810 });
5811 let Some(mut element) = maybe_element else {
5812 return;
5813 };
5814
5815 let selection_row = newest_selection_head.row();
5816 let Some(cursor_row_layout) = (selection_row >= start_row)
5817 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5818 .flatten()
5819 else {
5820 return;
5821 };
5822
5823 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5824 - Pixels::from(scroll_pixel_position.x);
5825 let target_y = Pixels::from(
5826 selection_row.as_f64() * ScrollPixelOffset::from(line_height) - scroll_pixel_position.y,
5827 );
5828 let target_point = content_origin + point(target_x, target_y);
5829
5830 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5831
5832 let (popover_bounds_above, popover_bounds_below) = {
5833 let horizontal_offset = (hitbox.top_right().x
5834 - POPOVER_RIGHT_OFFSET
5835 - (target_point.x + actual_size.width))
5836 .min(Pixels::ZERO);
5837 let initial_x = target_point.x + horizontal_offset;
5838 (
5839 Bounds::new(
5840 point(initial_x, target_point.y - actual_size.height),
5841 actual_size,
5842 ),
5843 Bounds::new(
5844 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5845 actual_size,
5846 ),
5847 )
5848 };
5849
5850 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5851 context_menu_layout
5852 .as_ref()
5853 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5854 };
5855
5856 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5857 && !intersects_menu(popover_bounds_above)
5858 {
5859 // try placing above cursor
5860 popover_bounds_above.origin
5861 } else if popover_bounds_below.is_contained_within(hitbox)
5862 && !intersects_menu(popover_bounds_below)
5863 {
5864 // try placing below cursor
5865 popover_bounds_below.origin
5866 } else {
5867 // try surrounding context menu if exists
5868 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5869 let y_for_horizontal_positioning = if menu.y_flipped {
5870 menu.bounds.bottom() - actual_size.height
5871 } else {
5872 menu.bounds.top()
5873 };
5874 let possible_origins = vec![
5875 // left of context menu
5876 point(
5877 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5878 y_for_horizontal_positioning,
5879 ),
5880 // right of context menu
5881 point(
5882 menu.bounds.right() + HOVER_POPOVER_GAP,
5883 y_for_horizontal_positioning,
5884 ),
5885 // top of context menu
5886 point(
5887 menu.bounds.left(),
5888 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5889 ),
5890 // bottom of context menu
5891 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5892 ];
5893 possible_origins
5894 .into_iter()
5895 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5896 });
5897 origin_surrounding_menu.unwrap_or_else(|| {
5898 // fallback to existing above/below cursor logic
5899 // this might overlap menu or overflow in rare case
5900 if popover_bounds_above.is_contained_within(hitbox) {
5901 popover_bounds_above.origin
5902 } else {
5903 popover_bounds_below.origin
5904 }
5905 })
5906 };
5907
5908 window.defer_draw(element, final_origin, 2);
5909 }
5910
5911 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5912 window.paint_layer(layout.hitbox.bounds, |window| {
5913 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5914 let gutter_bg = cx.theme().colors().editor_gutter_background;
5915 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5916 window.paint_quad(fill(
5917 layout.position_map.text_hitbox.bounds,
5918 self.style.background,
5919 ));
5920
5921 if matches!(
5922 layout.mode,
5923 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5924 ) {
5925 let show_active_line_background = match layout.mode {
5926 EditorMode::Full {
5927 show_active_line_background,
5928 ..
5929 } => show_active_line_background,
5930 EditorMode::Minimap { .. } => true,
5931 _ => false,
5932 };
5933 let mut active_rows = layout.active_rows.iter().peekable();
5934 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5935 let mut end_row = start_row.0;
5936 while active_rows
5937 .peek()
5938 .is_some_and(|(active_row, has_selection)| {
5939 active_row.0 == end_row + 1
5940 && has_selection.selection == contains_non_empty_selection.selection
5941 })
5942 {
5943 active_rows.next().unwrap();
5944 end_row += 1;
5945 }
5946
5947 if show_active_line_background && !contains_non_empty_selection.selection {
5948 let highlight_h_range =
5949 match layout.position_map.snapshot.current_line_highlight {
5950 CurrentLineHighlight::Gutter => Some(Range {
5951 start: layout.hitbox.left(),
5952 end: layout.gutter_hitbox.right(),
5953 }),
5954 CurrentLineHighlight::Line => Some(Range {
5955 start: layout.position_map.text_hitbox.bounds.left(),
5956 end: layout.position_map.text_hitbox.bounds.right(),
5957 }),
5958 CurrentLineHighlight::All => Some(Range {
5959 start: layout.hitbox.left(),
5960 end: layout.hitbox.right(),
5961 }),
5962 CurrentLineHighlight::None => None,
5963 };
5964 if let Some(range) = highlight_h_range {
5965 let active_line_bg = cx.theme().colors().editor_active_line_background;
5966 let bounds = Bounds {
5967 origin: point(
5968 range.start,
5969 layout.hitbox.origin.y
5970 + Pixels::from(
5971 (start_row.as_f64() - scroll_top)
5972 * ScrollPixelOffset::from(
5973 layout.position_map.line_height,
5974 ),
5975 ),
5976 ),
5977 size: size(
5978 range.end - range.start,
5979 layout.position_map.line_height
5980 * (end_row - start_row.0 + 1) as f32,
5981 ),
5982 };
5983 window.paint_quad(fill(bounds, active_line_bg));
5984 }
5985 }
5986 }
5987
5988 let mut paint_highlight = |highlight_row_start: DisplayRow,
5989 highlight_row_end: DisplayRow,
5990 highlight: crate::LineHighlight,
5991 edges| {
5992 let mut origin_x = layout.hitbox.left();
5993 let mut width = layout.hitbox.size.width;
5994 if !highlight.include_gutter {
5995 origin_x += layout.gutter_hitbox.size.width;
5996 width -= layout.gutter_hitbox.size.width;
5997 }
5998
5999 let origin = point(
6000 origin_x,
6001 layout.hitbox.origin.y
6002 + Pixels::from(
6003 (highlight_row_start.as_f64() - scroll_top)
6004 * ScrollPixelOffset::from(layout.position_map.line_height),
6005 ),
6006 );
6007 let size = size(
6008 width,
6009 layout.position_map.line_height
6010 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
6011 );
6012 let mut quad = fill(Bounds { origin, size }, highlight.background);
6013 if let Some(border_color) = highlight.border {
6014 quad.border_color = border_color;
6015 quad.border_widths = edges
6016 }
6017 window.paint_quad(quad);
6018 };
6019
6020 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
6021 None;
6022 for (&new_row, &new_background) in &layout.highlighted_rows {
6023 match &mut current_paint {
6024 &mut Some((current_background, ref mut current_range, mut edges)) => {
6025 let new_range_started = current_background != new_background
6026 || current_range.end.next_row() != new_row;
6027 if new_range_started {
6028 if current_range.end.next_row() == new_row {
6029 edges.bottom = px(0.);
6030 };
6031 paint_highlight(
6032 current_range.start,
6033 current_range.end,
6034 current_background,
6035 edges,
6036 );
6037 let edges = Edges {
6038 top: if current_range.end.next_row() != new_row {
6039 px(1.)
6040 } else {
6041 px(0.)
6042 },
6043 bottom: px(1.),
6044 ..Default::default()
6045 };
6046 current_paint = Some((new_background, new_row..new_row, edges));
6047 continue;
6048 } else {
6049 current_range.end = current_range.end.next_row();
6050 }
6051 }
6052 None => {
6053 let edges = Edges {
6054 top: px(1.),
6055 bottom: px(1.),
6056 ..Default::default()
6057 };
6058 current_paint = Some((new_background, new_row..new_row, edges))
6059 }
6060 };
6061 }
6062 if let Some((color, range, edges)) = current_paint {
6063 paint_highlight(range.start, range.end, color, edges);
6064 }
6065
6066 for (guide_x, active) in layout.wrap_guides.iter() {
6067 let color = if *active {
6068 cx.theme().colors().editor_active_wrap_guide
6069 } else {
6070 cx.theme().colors().editor_wrap_guide
6071 };
6072 window.paint_quad(fill(
6073 Bounds {
6074 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
6075 size: size(px(1.), layout.position_map.text_hitbox.size.height),
6076 },
6077 color,
6078 ));
6079 }
6080 }
6081 })
6082 }
6083
6084 fn paint_indent_guides(
6085 &mut self,
6086 layout: &mut EditorLayout,
6087 window: &mut Window,
6088 cx: &mut App,
6089 ) {
6090 let Some(indent_guides) = &layout.indent_guides else {
6091 return;
6092 };
6093
6094 let faded_color = |color: Hsla, alpha: f32| {
6095 let mut faded = color;
6096 faded.a = alpha;
6097 faded
6098 };
6099
6100 for indent_guide in indent_guides {
6101 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
6102 let settings = &indent_guide.settings;
6103
6104 // TODO fixed for now, expose them through themes later
6105 const INDENT_AWARE_ALPHA: f32 = 0.2;
6106 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
6107 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
6108 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
6109
6110 let line_color = match (settings.coloring, indent_guide.active) {
6111 (IndentGuideColoring::Disabled, _) => None,
6112 (IndentGuideColoring::Fixed, false) => {
6113 Some(cx.theme().colors().editor_indent_guide)
6114 }
6115 (IndentGuideColoring::Fixed, true) => {
6116 Some(cx.theme().colors().editor_indent_guide_active)
6117 }
6118 (IndentGuideColoring::IndentAware, false) => {
6119 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
6120 }
6121 (IndentGuideColoring::IndentAware, true) => {
6122 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
6123 }
6124 };
6125
6126 let background_color = match (settings.background_coloring, indent_guide.active) {
6127 (IndentGuideBackgroundColoring::Disabled, _) => None,
6128 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
6129 indent_accent_colors,
6130 INDENT_AWARE_BACKGROUND_ALPHA,
6131 )),
6132 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
6133 indent_accent_colors,
6134 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
6135 )),
6136 };
6137
6138 let requested_line_width = if indent_guide.active {
6139 settings.active_line_width
6140 } else {
6141 settings.line_width
6142 }
6143 .clamp(1, 10);
6144 let mut line_indicator_width = 0.;
6145 if let Some(color) = line_color {
6146 window.paint_quad(fill(
6147 Bounds {
6148 origin: indent_guide.origin,
6149 size: size(px(requested_line_width as f32), indent_guide.length),
6150 },
6151 color,
6152 ));
6153 line_indicator_width = requested_line_width as f32;
6154 }
6155
6156 if let Some(color) = background_color {
6157 let width = indent_guide.single_indent_width - px(line_indicator_width);
6158 window.paint_quad(fill(
6159 Bounds {
6160 origin: point(
6161 indent_guide.origin.x + px(line_indicator_width),
6162 indent_guide.origin.y,
6163 ),
6164 size: size(width, indent_guide.length),
6165 },
6166 color,
6167 ));
6168 }
6169 }
6170 }
6171
6172 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6173 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
6174
6175 let line_height = layout.position_map.line_height;
6176 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
6177
6178 for line_layout in layout.line_numbers.values() {
6179 for LineNumberSegment {
6180 shaped_line,
6181 hitbox,
6182 } in &line_layout.segments
6183 {
6184 let Some(hitbox) = hitbox else {
6185 continue;
6186 };
6187
6188 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
6189 let color = cx.theme().colors().editor_hover_line_number;
6190
6191 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
6192 line.paint(
6193 hitbox.origin,
6194 line_height,
6195 TextAlign::Left,
6196 None,
6197 window,
6198 cx,
6199 )
6200 .log_err()
6201 } else {
6202 shaped_line
6203 .paint(
6204 hitbox.origin,
6205 line_height,
6206 TextAlign::Left,
6207 None,
6208 window,
6209 cx,
6210 )
6211 .log_err()
6212 }) else {
6213 continue;
6214 };
6215
6216 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
6217 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
6218 if is_singleton {
6219 window.set_cursor_style(CursorStyle::IBeam, hitbox);
6220 } else {
6221 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
6222 }
6223 }
6224 }
6225 }
6226
6227 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6228 if layout.display_hunks.is_empty() {
6229 return;
6230 }
6231
6232 let line_height = layout.position_map.line_height;
6233 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6234 for (hunk, hitbox) in &layout.display_hunks {
6235 let hunk_to_paint = match hunk {
6236 DisplayDiffHunk::Folded { .. } => {
6237 let hunk_bounds = Self::diff_hunk_bounds(
6238 &layout.position_map.snapshot,
6239 line_height,
6240 layout.gutter_hitbox.bounds,
6241 hunk,
6242 );
6243 Some((
6244 hunk_bounds,
6245 cx.theme().colors().version_control_modified,
6246 Corners::all(px(0.)),
6247 DiffHunkStatus::modified_none(),
6248 ))
6249 }
6250 DisplayDiffHunk::Unfolded {
6251 status,
6252 display_row_range,
6253 ..
6254 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
6255 DiffHunkStatusKind::Added => (
6256 hunk_hitbox.bounds,
6257 cx.theme().colors().version_control_added,
6258 Corners::all(px(0.)),
6259 *status,
6260 ),
6261 DiffHunkStatusKind::Modified => (
6262 hunk_hitbox.bounds,
6263 cx.theme().colors().version_control_modified,
6264 Corners::all(px(0.)),
6265 *status,
6266 ),
6267 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
6268 hunk_hitbox.bounds,
6269 cx.theme().colors().version_control_deleted,
6270 Corners::all(px(0.)),
6271 *status,
6272 ),
6273 DiffHunkStatusKind::Deleted => (
6274 Bounds::new(
6275 point(
6276 hunk_hitbox.origin.x - hunk_hitbox.size.width,
6277 hunk_hitbox.origin.y,
6278 ),
6279 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
6280 ),
6281 cx.theme().colors().version_control_deleted,
6282 Corners::all(1. * line_height),
6283 *status,
6284 ),
6285 }),
6286 };
6287
6288 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
6289 // Flatten the background color with the editor color to prevent
6290 // elements below transparent hunks from showing through
6291 let flattened_background_color = cx
6292 .theme()
6293 .colors()
6294 .editor_background
6295 .blend(background_color);
6296
6297 if !Self::diff_hunk_hollow(status, cx) {
6298 window.paint_quad(quad(
6299 hunk_bounds,
6300 corner_radii,
6301 flattened_background_color,
6302 Edges::default(),
6303 transparent_black(),
6304 BorderStyle::default(),
6305 ));
6306 } else {
6307 let flattened_unstaged_background_color = cx
6308 .theme()
6309 .colors()
6310 .editor_background
6311 .blend(background_color.opacity(0.3));
6312
6313 window.paint_quad(quad(
6314 hunk_bounds,
6315 corner_radii,
6316 flattened_unstaged_background_color,
6317 Edges::all(px(1.0)),
6318 flattened_background_color,
6319 BorderStyle::Solid,
6320 ));
6321 }
6322 }
6323 }
6324 });
6325 }
6326
6327 fn gutter_strip_width(line_height: Pixels) -> Pixels {
6328 (0.275 * line_height).floor()
6329 }
6330
6331 fn diff_hunk_bounds(
6332 snapshot: &EditorSnapshot,
6333 line_height: Pixels,
6334 gutter_bounds: Bounds<Pixels>,
6335 hunk: &DisplayDiffHunk,
6336 ) -> Bounds<Pixels> {
6337 let scroll_position = snapshot.scroll_position();
6338 let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
6339 let gutter_strip_width = Self::gutter_strip_width(line_height);
6340
6341 match hunk {
6342 DisplayDiffHunk::Folded { display_row, .. } => {
6343 let start_y = (display_row.as_f64() * ScrollPixelOffset::from(line_height)
6344 - scroll_top)
6345 .into();
6346 let end_y = start_y + line_height;
6347 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6348 let highlight_size = size(gutter_strip_width, end_y - start_y);
6349 Bounds::new(highlight_origin, highlight_size)
6350 }
6351 DisplayDiffHunk::Unfolded {
6352 display_row_range,
6353 status,
6354 ..
6355 } => {
6356 if status.is_deleted() && display_row_range.is_empty() {
6357 let row = display_row_range.start;
6358
6359 let offset = ScrollPixelOffset::from(line_height / 2.);
6360 let start_y =
6361 (row.as_f64() * ScrollPixelOffset::from(line_height) - offset - scroll_top)
6362 .into();
6363 let end_y = start_y + line_height;
6364
6365 let width = (0.35 * line_height).floor();
6366 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6367 let highlight_size = size(width, end_y - start_y);
6368 Bounds::new(highlight_origin, highlight_size)
6369 } else {
6370 let start_row = display_row_range.start;
6371 let end_row = display_row_range.end;
6372 // If we're in a multibuffer, row range span might include an
6373 // excerpt header, so if we were to draw the marker straight away,
6374 // the hunk might include the rows of that header.
6375 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
6376 // Instead, we simply check whether the range we're dealing with includes
6377 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
6378 let end_row_in_current_excerpt = snapshot
6379 .blocks_in_range(start_row..end_row)
6380 .find_map(|(start_row, block)| {
6381 if matches!(
6382 block,
6383 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
6384 ) {
6385 Some(start_row)
6386 } else {
6387 None
6388 }
6389 })
6390 .unwrap_or(end_row);
6391
6392 let start_y = (start_row.as_f64() * ScrollPixelOffset::from(line_height)
6393 - scroll_top)
6394 .into();
6395 let end_y = Pixels::from(
6396 end_row_in_current_excerpt.as_f64() * ScrollPixelOffset::from(line_height)
6397 - scroll_top,
6398 );
6399
6400 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
6401 let highlight_size = size(gutter_strip_width, end_y - start_y);
6402 Bounds::new(highlight_origin, highlight_size)
6403 }
6404 }
6405 }
6406 }
6407
6408 fn paint_gutter_indicators(
6409 &self,
6410 layout: &mut EditorLayout,
6411 window: &mut Window,
6412 cx: &mut App,
6413 ) {
6414 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6415 window.with_element_namespace("crease_toggles", |window| {
6416 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
6417 crease_toggle.paint(window, cx);
6418 }
6419 });
6420
6421 window.with_element_namespace("expand_toggles", |window| {
6422 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
6423 expand_toggle.paint(window, cx);
6424 }
6425 });
6426
6427 for breakpoint in layout.breakpoints.iter_mut() {
6428 breakpoint.paint(window, cx);
6429 }
6430
6431 for test_indicator in layout.test_indicators.iter_mut() {
6432 test_indicator.paint(window, cx);
6433 }
6434 });
6435 }
6436
6437 fn paint_gutter_highlights(
6438 &self,
6439 layout: &mut EditorLayout,
6440 window: &mut Window,
6441 cx: &mut App,
6442 ) {
6443 for (_, hunk_hitbox) in &layout.display_hunks {
6444 if let Some(hunk_hitbox) = hunk_hitbox
6445 && !self
6446 .editor
6447 .read(cx)
6448 .buffer()
6449 .read(cx)
6450 .all_diff_hunks_expanded()
6451 {
6452 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
6453 }
6454 }
6455
6456 let show_git_gutter = layout
6457 .position_map
6458 .snapshot
6459 .show_git_diff_gutter
6460 .unwrap_or_else(|| {
6461 matches!(
6462 ProjectSettings::get_global(cx).git.git_gutter,
6463 GitGutterSetting::TrackedFiles
6464 )
6465 });
6466 if show_git_gutter {
6467 Self::paint_gutter_diff_hunks(layout, window, cx)
6468 }
6469
6470 let highlight_width = 0.275 * layout.position_map.line_height;
6471 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
6472 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6473 for (range, color) in &layout.highlighted_gutter_ranges {
6474 let start_row = if range.start.row() < layout.visible_display_row_range.start {
6475 layout.visible_display_row_range.start - DisplayRow(1)
6476 } else {
6477 range.start.row()
6478 };
6479 let end_row = if range.end.row() > layout.visible_display_row_range.end {
6480 layout.visible_display_row_range.end + DisplayRow(1)
6481 } else {
6482 range.end.row()
6483 };
6484
6485 let start_y = layout.gutter_hitbox.top()
6486 + Pixels::from(
6487 start_row.0 as f64
6488 * ScrollPixelOffset::from(layout.position_map.line_height)
6489 - layout.position_map.scroll_pixel_position.y,
6490 );
6491 let end_y = layout.gutter_hitbox.top()
6492 + Pixels::from(
6493 (end_row.0 + 1) as f64
6494 * ScrollPixelOffset::from(layout.position_map.line_height)
6495 - layout.position_map.scroll_pixel_position.y,
6496 );
6497 let bounds = Bounds::from_corners(
6498 point(layout.gutter_hitbox.left(), start_y),
6499 point(layout.gutter_hitbox.left() + highlight_width, end_y),
6500 );
6501 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
6502 }
6503 });
6504 }
6505
6506 fn paint_blamed_display_rows(
6507 &self,
6508 layout: &mut EditorLayout,
6509 window: &mut Window,
6510 cx: &mut App,
6511 ) {
6512 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
6513 return;
6514 };
6515
6516 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6517 for mut blame_element in blamed_display_rows.into_iter() {
6518 blame_element.paint(window, cx);
6519 }
6520 })
6521 }
6522
6523 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6524 window.with_content_mask(
6525 Some(ContentMask {
6526 bounds: layout.position_map.text_hitbox.bounds,
6527 }),
6528 |window| {
6529 let editor = self.editor.read(cx);
6530 if editor.mouse_cursor_hidden {
6531 window.set_window_cursor_style(CursorStyle::None);
6532 } else if let SelectionDragState::ReadyToDrag {
6533 mouse_down_time, ..
6534 } = &editor.selection_drag_state
6535 {
6536 let drag_and_drop_delay = Duration::from_millis(
6537 EditorSettings::get_global(cx)
6538 .drag_and_drop_selection
6539 .delay
6540 .0,
6541 );
6542 if mouse_down_time.elapsed() >= drag_and_drop_delay {
6543 window.set_cursor_style(
6544 CursorStyle::DragCopy,
6545 &layout.position_map.text_hitbox,
6546 );
6547 }
6548 } else if matches!(
6549 editor.selection_drag_state,
6550 SelectionDragState::Dragging { .. }
6551 ) {
6552 window
6553 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
6554 } else if editor
6555 .hovered_link_state
6556 .as_ref()
6557 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
6558 {
6559 window.set_cursor_style(
6560 CursorStyle::PointingHand,
6561 &layout.position_map.text_hitbox,
6562 );
6563 } else {
6564 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
6565 };
6566
6567 self.paint_lines_background(layout, window, cx);
6568 let invisible_display_ranges = self.paint_highlights(layout, window, cx);
6569 self.paint_document_colors(layout, window);
6570 self.paint_lines(&invisible_display_ranges, layout, window, cx);
6571 self.paint_redactions(layout, window);
6572 self.paint_cursors(layout, window, cx);
6573 self.paint_inline_diagnostics(layout, window, cx);
6574 self.paint_inline_blame(layout, window, cx);
6575 self.paint_inline_code_actions(layout, window, cx);
6576 self.paint_diff_hunk_controls(layout, window, cx);
6577 window.with_element_namespace("crease_trailers", |window| {
6578 for trailer in layout.crease_trailers.iter_mut().flatten() {
6579 trailer.element.paint(window, cx);
6580 }
6581 });
6582 },
6583 )
6584 }
6585
6586 fn paint_highlights(
6587 &mut self,
6588 layout: &mut EditorLayout,
6589 window: &mut Window,
6590 cx: &mut App,
6591 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6592 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6593 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6594 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6595 for (range, color) in &layout.highlighted_ranges {
6596 self.paint_highlighted_range(
6597 range.clone(),
6598 true,
6599 *color,
6600 Pixels::ZERO,
6601 line_end_overshoot,
6602 layout,
6603 window,
6604 );
6605 }
6606
6607 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
6608 0.15 * layout.position_map.line_height
6609 } else {
6610 Pixels::ZERO
6611 };
6612
6613 for (player_color, selections) in &layout.selections {
6614 for selection in selections.iter() {
6615 self.paint_highlighted_range(
6616 selection.range.clone(),
6617 true,
6618 player_color.selection,
6619 corner_radius,
6620 corner_radius * 2.,
6621 layout,
6622 window,
6623 );
6624
6625 if selection.is_local && !selection.range.is_empty() {
6626 invisible_display_ranges.push(selection.range.clone());
6627 }
6628 }
6629 }
6630 invisible_display_ranges
6631 })
6632 }
6633
6634 fn paint_lines(
6635 &mut self,
6636 invisible_display_ranges: &[Range<DisplayPoint>],
6637 layout: &mut EditorLayout,
6638 window: &mut Window,
6639 cx: &mut App,
6640 ) {
6641 let whitespace_setting = self
6642 .editor
6643 .read(cx)
6644 .buffer
6645 .read(cx)
6646 .language_settings(cx)
6647 .show_whitespaces;
6648
6649 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6650 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6651 line_with_invisibles.draw(
6652 layout,
6653 row,
6654 layout.content_origin,
6655 whitespace_setting,
6656 invisible_display_ranges,
6657 window,
6658 cx,
6659 )
6660 }
6661
6662 for line_element in &mut layout.line_elements {
6663 line_element.paint(window, cx);
6664 }
6665 }
6666
6667 fn paint_sticky_headers(
6668 &mut self,
6669 layout: &mut EditorLayout,
6670 window: &mut Window,
6671 cx: &mut App,
6672 ) {
6673 let Some(mut sticky_headers) = layout.sticky_headers.take() else {
6674 return;
6675 };
6676
6677 if sticky_headers.lines.is_empty() {
6678 layout.sticky_headers = Some(sticky_headers);
6679 return;
6680 }
6681
6682 let whitespace_setting = self
6683 .editor
6684 .read(cx)
6685 .buffer
6686 .read(cx)
6687 .language_settings(cx)
6688 .show_whitespaces;
6689 sticky_headers.paint(layout, whitespace_setting, window, cx);
6690
6691 let sticky_header_hitboxes: Vec<Hitbox> = sticky_headers
6692 .lines
6693 .iter()
6694 .map(|line| line.hitbox.clone())
6695 .collect();
6696 let hovered_hitbox = sticky_header_hitboxes
6697 .iter()
6698 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6699
6700 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, _cx| {
6701 if !phase.bubble() {
6702 return;
6703 }
6704
6705 let current_hover = sticky_header_hitboxes
6706 .iter()
6707 .find_map(|hitbox| hitbox.is_hovered(window).then_some(hitbox.id));
6708 if hovered_hitbox != current_hover {
6709 window.refresh();
6710 }
6711 });
6712
6713 for (line_index, line) in sticky_headers.lines.iter().enumerate() {
6714 let editor = self.editor.clone();
6715 let hitbox = line.hitbox.clone();
6716 let target_anchor = line.target_anchor;
6717 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
6718 if !phase.bubble() {
6719 return;
6720 }
6721
6722 if event.button == MouseButton::Left && hitbox.is_hovered(window) {
6723 editor.update(cx, |editor, cx| {
6724 editor.change_selections(
6725 SelectionEffects::scroll(Autoscroll::top_relative(line_index)),
6726 window,
6727 cx,
6728 |selections| selections.select_ranges([target_anchor..target_anchor]),
6729 );
6730 cx.stop_propagation();
6731 });
6732 }
6733 });
6734 }
6735
6736 let text_bounds = layout.position_map.text_hitbox.bounds;
6737 let border_top = text_bounds.top()
6738 + sticky_headers.lines.last().unwrap().offset
6739 + layout.position_map.line_height;
6740 let separator_height = px(1.);
6741 let border_bounds = Bounds::from_corners(
6742 point(layout.gutter_hitbox.bounds.left(), border_top),
6743 point(text_bounds.right(), border_top + separator_height),
6744 );
6745 window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
6746
6747 layout.sticky_headers = Some(sticky_headers);
6748 }
6749
6750 fn paint_lines_background(
6751 &mut self,
6752 layout: &mut EditorLayout,
6753 window: &mut Window,
6754 cx: &mut App,
6755 ) {
6756 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6757 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6758 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6759 }
6760 }
6761
6762 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6763 if layout.redacted_ranges.is_empty() {
6764 return;
6765 }
6766
6767 let line_end_overshoot = layout.line_end_overshoot();
6768
6769 // A softer than perfect black
6770 let redaction_color = gpui::rgb(0x0e1111);
6771
6772 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6773 for range in layout.redacted_ranges.iter() {
6774 self.paint_highlighted_range(
6775 range.clone(),
6776 true,
6777 redaction_color.into(),
6778 Pixels::ZERO,
6779 line_end_overshoot,
6780 layout,
6781 window,
6782 );
6783 }
6784 });
6785 }
6786
6787 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6788 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6789 return;
6790 };
6791 if image_colors.is_empty()
6792 || colors_render_mode == &DocumentColorsRenderMode::None
6793 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6794 {
6795 return;
6796 }
6797
6798 let line_end_overshoot = layout.line_end_overshoot();
6799
6800 for (range, color) in image_colors {
6801 match colors_render_mode {
6802 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6803 DocumentColorsRenderMode::Background => {
6804 self.paint_highlighted_range(
6805 range.clone(),
6806 true,
6807 *color,
6808 Pixels::ZERO,
6809 line_end_overshoot,
6810 layout,
6811 window,
6812 );
6813 }
6814 DocumentColorsRenderMode::Border => {
6815 self.paint_highlighted_range(
6816 range.clone(),
6817 false,
6818 *color,
6819 Pixels::ZERO,
6820 line_end_overshoot,
6821 layout,
6822 window,
6823 );
6824 }
6825 }
6826 }
6827 }
6828
6829 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6830 for cursor in &mut layout.visible_cursors {
6831 cursor.paint(layout.content_origin, window, cx);
6832 }
6833 }
6834
6835 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6836 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6837 return;
6838 };
6839 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6840
6841 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6842 let hitbox = &scrollbar_layout.hitbox;
6843 if scrollbars_layout.visible {
6844 let scrollbar_edges = match axis {
6845 ScrollbarAxis::Horizontal => Edges {
6846 top: Pixels::ZERO,
6847 right: Pixels::ZERO,
6848 bottom: Pixels::ZERO,
6849 left: Pixels::ZERO,
6850 },
6851 ScrollbarAxis::Vertical => Edges {
6852 top: Pixels::ZERO,
6853 right: Pixels::ZERO,
6854 bottom: Pixels::ZERO,
6855 left: ScrollbarLayout::BORDER_WIDTH,
6856 },
6857 };
6858
6859 window.paint_layer(hitbox.bounds, |window| {
6860 window.paint_quad(quad(
6861 hitbox.bounds,
6862 Corners::default(),
6863 cx.theme().colors().scrollbar_track_background,
6864 scrollbar_edges,
6865 cx.theme().colors().scrollbar_track_border,
6866 BorderStyle::Solid,
6867 ));
6868
6869 if axis == ScrollbarAxis::Vertical {
6870 let fast_markers =
6871 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6872 // Refresh slow scrollbar markers in the background. Below, we
6873 // paint whatever markers have already been computed.
6874 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6875
6876 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6877 for marker in markers.iter().chain(&fast_markers) {
6878 let mut marker = marker.clone();
6879 marker.bounds.origin += hitbox.origin;
6880 window.paint_quad(marker);
6881 }
6882 }
6883
6884 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6885 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6886 ScrollbarThumbState::Dragging => {
6887 cx.theme().colors().scrollbar_thumb_active_background
6888 }
6889 ScrollbarThumbState::Hovered => {
6890 cx.theme().colors().scrollbar_thumb_hover_background
6891 }
6892 ScrollbarThumbState::Idle => {
6893 cx.theme().colors().scrollbar_thumb_background
6894 }
6895 };
6896 window.paint_quad(quad(
6897 thumb_bounds,
6898 Corners::default(),
6899 scrollbar_thumb_color,
6900 scrollbar_edges,
6901 cx.theme().colors().scrollbar_thumb_border,
6902 BorderStyle::Solid,
6903 ));
6904
6905 if any_scrollbar_dragged {
6906 window.set_window_cursor_style(CursorStyle::Arrow);
6907 } else {
6908 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6909 }
6910 }
6911 })
6912 }
6913 }
6914
6915 window.on_mouse_event({
6916 let editor = self.editor.clone();
6917 let scrollbars_layout = scrollbars_layout.clone();
6918
6919 let mut mouse_position = window.mouse_position();
6920 move |event: &MouseMoveEvent, phase, window, cx| {
6921 if phase == DispatchPhase::Capture {
6922 return;
6923 }
6924
6925 editor.update(cx, |editor, cx| {
6926 if let Some((scrollbar_layout, axis)) = event
6927 .pressed_button
6928 .filter(|button| *button == MouseButton::Left)
6929 .and(editor.scroll_manager.dragging_scrollbar_axis())
6930 .and_then(|axis| {
6931 scrollbars_layout
6932 .iter_scrollbars()
6933 .find(|(_, a)| *a == axis)
6934 })
6935 {
6936 let ScrollbarLayout {
6937 hitbox,
6938 text_unit_size,
6939 ..
6940 } = scrollbar_layout;
6941
6942 let old_position = mouse_position.along(axis);
6943 let new_position = event.position.along(axis);
6944 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6945 .contains(&old_position)
6946 {
6947 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6948 (p + ScrollOffset::from(
6949 (new_position - old_position) / *text_unit_size,
6950 ))
6951 .max(0.)
6952 });
6953 editor.set_scroll_position(position, window, cx);
6954 }
6955
6956 editor.scroll_manager.show_scrollbars(window, cx);
6957 cx.stop_propagation();
6958 } else if let Some((layout, axis)) = scrollbars_layout
6959 .get_hovered_axis(window)
6960 .filter(|_| !event.dragging())
6961 {
6962 if layout.thumb_hovered(&event.position) {
6963 editor
6964 .scroll_manager
6965 .set_hovered_scroll_thumb_axis(axis, cx);
6966 } else {
6967 editor.scroll_manager.reset_scrollbar_state(cx);
6968 }
6969
6970 editor.scroll_manager.show_scrollbars(window, cx);
6971 } else {
6972 editor.scroll_manager.reset_scrollbar_state(cx);
6973 }
6974
6975 mouse_position = event.position;
6976 })
6977 }
6978 });
6979
6980 if any_scrollbar_dragged {
6981 window.on_mouse_event({
6982 let editor = self.editor.clone();
6983 move |_: &MouseUpEvent, phase, window, cx| {
6984 if phase == DispatchPhase::Capture {
6985 return;
6986 }
6987
6988 editor.update(cx, |editor, cx| {
6989 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6990 editor
6991 .scroll_manager
6992 .set_hovered_scroll_thumb_axis(axis, cx);
6993 } else {
6994 editor.scroll_manager.reset_scrollbar_state(cx);
6995 }
6996 cx.stop_propagation();
6997 });
6998 }
6999 });
7000 } else {
7001 window.on_mouse_event({
7002 let editor = self.editor.clone();
7003
7004 move |event: &MouseDownEvent, phase, window, cx| {
7005 if phase == DispatchPhase::Capture {
7006 return;
7007 }
7008 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
7009 else {
7010 return;
7011 };
7012
7013 let ScrollbarLayout {
7014 hitbox,
7015 visible_range,
7016 text_unit_size,
7017 thumb_bounds,
7018 ..
7019 } = scrollbar_layout;
7020
7021 let Some(thumb_bounds) = thumb_bounds else {
7022 return;
7023 };
7024
7025 editor.update(cx, |editor, cx| {
7026 editor
7027 .scroll_manager
7028 .set_dragged_scroll_thumb_axis(axis, cx);
7029
7030 let event_position = event.position.along(axis);
7031
7032 if event_position < thumb_bounds.origin.along(axis)
7033 || thumb_bounds.bottom_right().along(axis) < event_position
7034 {
7035 let center_position = ((event_position - hitbox.origin.along(axis))
7036 / *text_unit_size)
7037 .round() as u32;
7038 let start_position = center_position.saturating_sub(
7039 (visible_range.end - visible_range.start) as u32 / 2,
7040 );
7041
7042 let position = editor
7043 .scroll_position(cx)
7044 .apply_along(axis, |_| start_position as ScrollOffset);
7045
7046 editor.set_scroll_position(position, window, cx);
7047 } else {
7048 editor.scroll_manager.show_scrollbars(window, cx);
7049 }
7050
7051 cx.stop_propagation();
7052 });
7053 }
7054 });
7055 }
7056 }
7057
7058 fn collect_fast_scrollbar_markers(
7059 &self,
7060 layout: &EditorLayout,
7061 scrollbar_layout: &ScrollbarLayout,
7062 cx: &mut App,
7063 ) -> Vec<PaintQuad> {
7064 const LIMIT: usize = 100;
7065 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
7066 return vec![];
7067 }
7068 let cursor_ranges = layout
7069 .cursors
7070 .iter()
7071 .map(|(point, color)| ColoredRange {
7072 start: point.row(),
7073 end: point.row(),
7074 color: *color,
7075 })
7076 .collect_vec();
7077 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
7078 }
7079
7080 fn refresh_slow_scrollbar_markers(
7081 &self,
7082 layout: &EditorLayout,
7083 scrollbar_layout: &ScrollbarLayout,
7084 window: &mut Window,
7085 cx: &mut App,
7086 ) {
7087 self.editor.update(cx, |editor, cx| {
7088 if editor.buffer_kind(cx) != ItemBufferKind::Singleton
7089 || !editor
7090 .scrollbar_marker_state
7091 .should_refresh(scrollbar_layout.hitbox.size)
7092 {
7093 return;
7094 }
7095
7096 let scrollbar_layout = scrollbar_layout.clone();
7097 let background_highlights = editor.background_highlights.clone();
7098 let snapshot = layout.position_map.snapshot.clone();
7099 let theme = cx.theme().clone();
7100 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
7101
7102 editor.scrollbar_marker_state.dirty = false;
7103 editor.scrollbar_marker_state.pending_refresh =
7104 Some(cx.spawn_in(window, async move |editor, cx| {
7105 let scrollbar_size = scrollbar_layout.hitbox.size;
7106 let scrollbar_markers = cx
7107 .background_spawn(async move {
7108 let max_point = snapshot.display_snapshot.buffer_snapshot().max_point();
7109 let mut marker_quads = Vec::new();
7110 if scrollbar_settings.git_diff {
7111 let marker_row_ranges =
7112 snapshot.buffer_snapshot().diff_hunks().map(|hunk| {
7113 let start_display_row =
7114 MultiBufferPoint::new(hunk.row_range.start.0, 0)
7115 .to_display_point(&snapshot.display_snapshot)
7116 .row();
7117 let mut end_display_row =
7118 MultiBufferPoint::new(hunk.row_range.end.0, 0)
7119 .to_display_point(&snapshot.display_snapshot)
7120 .row();
7121 if end_display_row != start_display_row {
7122 end_display_row.0 -= 1;
7123 }
7124 let color = match &hunk.status().kind {
7125 DiffHunkStatusKind::Added => {
7126 theme.colors().version_control_added
7127 }
7128 DiffHunkStatusKind::Modified => {
7129 theme.colors().version_control_modified
7130 }
7131 DiffHunkStatusKind::Deleted => {
7132 theme.colors().version_control_deleted
7133 }
7134 };
7135 ColoredRange {
7136 start: start_display_row,
7137 end: end_display_row,
7138 color,
7139 }
7140 });
7141
7142 marker_quads.extend(
7143 scrollbar_layout
7144 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
7145 );
7146 }
7147
7148 for (background_highlight_id, (_, background_ranges)) in
7149 background_highlights.iter()
7150 {
7151 let is_search_highlights = *background_highlight_id
7152 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
7153 let is_text_highlights = *background_highlight_id
7154 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
7155 let is_symbol_occurrences = *background_highlight_id
7156 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
7157 || *background_highlight_id
7158 == HighlightKey::Type(
7159 TypeId::of::<DocumentHighlightWrite>(),
7160 );
7161 if (is_search_highlights && scrollbar_settings.search_results)
7162 || (is_text_highlights && scrollbar_settings.selected_text)
7163 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
7164 {
7165 let mut color = theme.status().info;
7166 if is_symbol_occurrences {
7167 color.fade_out(0.5);
7168 }
7169 let marker_row_ranges = background_ranges.iter().map(|range| {
7170 let display_start = range
7171 .start
7172 .to_display_point(&snapshot.display_snapshot);
7173 let display_end =
7174 range.end.to_display_point(&snapshot.display_snapshot);
7175 ColoredRange {
7176 start: display_start.row(),
7177 end: display_end.row(),
7178 color,
7179 }
7180 });
7181 marker_quads.extend(
7182 scrollbar_layout
7183 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
7184 );
7185 }
7186 }
7187
7188 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
7189 let diagnostics = snapshot
7190 .buffer_snapshot()
7191 .diagnostics_in_range::<Point>(Point::zero()..max_point)
7192 // Don't show diagnostics the user doesn't care about
7193 .filter(|diagnostic| {
7194 match (
7195 scrollbar_settings.diagnostics,
7196 diagnostic.diagnostic.severity,
7197 ) {
7198 (ScrollbarDiagnostics::All, _) => true,
7199 (
7200 ScrollbarDiagnostics::Error,
7201 lsp::DiagnosticSeverity::ERROR,
7202 ) => true,
7203 (
7204 ScrollbarDiagnostics::Warning,
7205 lsp::DiagnosticSeverity::ERROR
7206 | lsp::DiagnosticSeverity::WARNING,
7207 ) => true,
7208 (
7209 ScrollbarDiagnostics::Information,
7210 lsp::DiagnosticSeverity::ERROR
7211 | lsp::DiagnosticSeverity::WARNING
7212 | lsp::DiagnosticSeverity::INFORMATION,
7213 ) => true,
7214 (_, _) => false,
7215 }
7216 })
7217 // We want to sort by severity, in order to paint the most severe diagnostics last.
7218 .sorted_by_key(|diagnostic| {
7219 std::cmp::Reverse(diagnostic.diagnostic.severity)
7220 });
7221
7222 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
7223 let start_display = diagnostic
7224 .range
7225 .start
7226 .to_display_point(&snapshot.display_snapshot);
7227 let end_display = diagnostic
7228 .range
7229 .end
7230 .to_display_point(&snapshot.display_snapshot);
7231 let color = match diagnostic.diagnostic.severity {
7232 lsp::DiagnosticSeverity::ERROR => theme.status().error,
7233 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
7234 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
7235 _ => theme.status().hint,
7236 };
7237 ColoredRange {
7238 start: start_display.row(),
7239 end: end_display.row(),
7240 color,
7241 }
7242 });
7243 marker_quads.extend(
7244 scrollbar_layout
7245 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
7246 );
7247 }
7248
7249 Arc::from(marker_quads)
7250 })
7251 .await;
7252
7253 editor.update(cx, |editor, cx| {
7254 editor.scrollbar_marker_state.markers = scrollbar_markers;
7255 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
7256 editor.scrollbar_marker_state.pending_refresh = None;
7257 cx.notify();
7258 })?;
7259
7260 Ok(())
7261 }));
7262 });
7263 }
7264
7265 fn paint_highlighted_range(
7266 &self,
7267 range: Range<DisplayPoint>,
7268 fill: bool,
7269 color: Hsla,
7270 corner_radius: Pixels,
7271 line_end_overshoot: Pixels,
7272 layout: &EditorLayout,
7273 window: &mut Window,
7274 ) {
7275 let start_row = layout.visible_display_row_range.start;
7276 let end_row = layout.visible_display_row_range.end;
7277 if range.start != range.end {
7278 let row_range = if range.end.column() == 0 {
7279 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
7280 } else {
7281 cmp::max(range.start.row(), start_row)
7282 ..cmp::min(range.end.row().next_row(), end_row)
7283 };
7284
7285 let highlighted_range = HighlightedRange {
7286 color,
7287 line_height: layout.position_map.line_height,
7288 corner_radius,
7289 start_y: layout.content_origin.y
7290 + Pixels::from(
7291 (row_range.start.as_f64() - layout.position_map.scroll_position.y)
7292 * ScrollOffset::from(layout.position_map.line_height),
7293 ),
7294 lines: row_range
7295 .iter_rows()
7296 .map(|row| {
7297 let line_layout =
7298 &layout.position_map.line_layouts[row.minus(start_row) as usize];
7299 let alignment_offset =
7300 line_layout.alignment_offset(layout.text_align, layout.content_width);
7301 HighlightedRangeLine {
7302 start_x: if row == range.start.row() {
7303 layout.content_origin.x
7304 + Pixels::from(
7305 ScrollPixelOffset::from(
7306 line_layout.x_for_index(range.start.column() as usize)
7307 + alignment_offset,
7308 ) - layout.position_map.scroll_pixel_position.x,
7309 )
7310 } else {
7311 layout.content_origin.x + alignment_offset
7312 - Pixels::from(layout.position_map.scroll_pixel_position.x)
7313 },
7314 end_x: if row == range.end.row() {
7315 layout.content_origin.x
7316 + Pixels::from(
7317 ScrollPixelOffset::from(
7318 line_layout.x_for_index(range.end.column() as usize)
7319 + alignment_offset,
7320 ) - layout.position_map.scroll_pixel_position.x,
7321 )
7322 } else {
7323 Pixels::from(
7324 ScrollPixelOffset::from(
7325 layout.content_origin.x
7326 + line_layout.width
7327 + alignment_offset
7328 + line_end_overshoot,
7329 ) - layout.position_map.scroll_pixel_position.x,
7330 )
7331 },
7332 }
7333 })
7334 .collect(),
7335 };
7336
7337 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
7338 }
7339 }
7340
7341 fn paint_inline_diagnostics(
7342 &mut self,
7343 layout: &mut EditorLayout,
7344 window: &mut Window,
7345 cx: &mut App,
7346 ) {
7347 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
7348 inline_diagnostic.1.paint(window, cx);
7349 }
7350 }
7351
7352 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7353 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
7354 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
7355 blame_layout.element.paint(window, cx);
7356 })
7357 }
7358 }
7359
7360 fn paint_inline_code_actions(
7361 &mut self,
7362 layout: &mut EditorLayout,
7363 window: &mut Window,
7364 cx: &mut App,
7365 ) {
7366 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
7367 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
7368 inline_code_actions.paint(window, cx);
7369 })
7370 }
7371 }
7372
7373 fn paint_diff_hunk_controls(
7374 &mut self,
7375 layout: &mut EditorLayout,
7376 window: &mut Window,
7377 cx: &mut App,
7378 ) {
7379 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
7380 diff_hunk_control.paint(window, cx);
7381 }
7382 }
7383
7384 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7385 if let Some(mut layout) = layout.minimap.take() {
7386 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
7387 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
7388
7389 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
7390 window.with_element_namespace("minimap", |window| {
7391 layout.minimap.paint(window, cx);
7392 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
7393 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
7394 ScrollbarThumbState::Idle => {
7395 cx.theme().colors().minimap_thumb_background
7396 }
7397 ScrollbarThumbState::Hovered => {
7398 cx.theme().colors().minimap_thumb_hover_background
7399 }
7400 ScrollbarThumbState::Dragging => {
7401 cx.theme().colors().minimap_thumb_active_background
7402 }
7403 };
7404 let minimap_thumb_border = match layout.thumb_border_style {
7405 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
7406 MinimapThumbBorder::LeftOnly => Edges {
7407 left: ScrollbarLayout::BORDER_WIDTH,
7408 ..Default::default()
7409 },
7410 MinimapThumbBorder::LeftOpen => Edges {
7411 right: ScrollbarLayout::BORDER_WIDTH,
7412 top: ScrollbarLayout::BORDER_WIDTH,
7413 bottom: ScrollbarLayout::BORDER_WIDTH,
7414 ..Default::default()
7415 },
7416 MinimapThumbBorder::RightOpen => Edges {
7417 left: ScrollbarLayout::BORDER_WIDTH,
7418 top: ScrollbarLayout::BORDER_WIDTH,
7419 bottom: ScrollbarLayout::BORDER_WIDTH,
7420 ..Default::default()
7421 },
7422 MinimapThumbBorder::None => Default::default(),
7423 };
7424
7425 window.paint_layer(minimap_hitbox.bounds, |window| {
7426 window.paint_quad(quad(
7427 thumb_bounds,
7428 Corners::default(),
7429 minimap_thumb_color,
7430 minimap_thumb_border,
7431 cx.theme().colors().minimap_thumb_border,
7432 BorderStyle::Solid,
7433 ));
7434 });
7435 }
7436 });
7437 });
7438
7439 if dragging_minimap {
7440 window.set_window_cursor_style(CursorStyle::Arrow);
7441 } else {
7442 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
7443 }
7444
7445 let minimap_axis = ScrollbarAxis::Vertical;
7446 let pixels_per_line = Pixels::from(
7447 ScrollPixelOffset::from(minimap_hitbox.size.height) / layout.max_scroll_top,
7448 )
7449 .min(layout.minimap_line_height);
7450
7451 let mut mouse_position = window.mouse_position();
7452
7453 window.on_mouse_event({
7454 let editor = self.editor.clone();
7455
7456 let minimap_hitbox = minimap_hitbox.clone();
7457
7458 move |event: &MouseMoveEvent, phase, window, cx| {
7459 if phase == DispatchPhase::Capture {
7460 return;
7461 }
7462
7463 editor.update(cx, |editor, cx| {
7464 if event.pressed_button == Some(MouseButton::Left)
7465 && editor.scroll_manager.is_dragging_minimap()
7466 {
7467 let old_position = mouse_position.along(minimap_axis);
7468 let new_position = event.position.along(minimap_axis);
7469 if (minimap_hitbox.origin.along(minimap_axis)
7470 ..minimap_hitbox.bottom_right().along(minimap_axis))
7471 .contains(&old_position)
7472 {
7473 let position =
7474 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
7475 (p + ScrollPixelOffset::from(
7476 (new_position - old_position) / pixels_per_line,
7477 ))
7478 .max(0.)
7479 });
7480
7481 editor.set_scroll_position(position, window, cx);
7482 }
7483 cx.stop_propagation();
7484 } else if minimap_hitbox.is_hovered(window) {
7485 editor.scroll_manager.set_is_hovering_minimap_thumb(
7486 !event.dragging()
7487 && layout
7488 .thumb_layout
7489 .thumb_bounds
7490 .is_some_and(|bounds| bounds.contains(&event.position)),
7491 cx,
7492 );
7493
7494 // Stop hover events from propagating to the
7495 // underlying editor if the minimap hitbox is hovered
7496 if !event.dragging() {
7497 cx.stop_propagation();
7498 }
7499 } else {
7500 editor.scroll_manager.hide_minimap_thumb(cx);
7501 }
7502 mouse_position = event.position;
7503 });
7504 }
7505 });
7506
7507 if dragging_minimap {
7508 window.on_mouse_event({
7509 let editor = self.editor.clone();
7510 move |event: &MouseUpEvent, phase, window, cx| {
7511 if phase == DispatchPhase::Capture {
7512 return;
7513 }
7514
7515 editor.update(cx, |editor, cx| {
7516 if minimap_hitbox.is_hovered(window) {
7517 editor.scroll_manager.set_is_hovering_minimap_thumb(
7518 layout
7519 .thumb_layout
7520 .thumb_bounds
7521 .is_some_and(|bounds| bounds.contains(&event.position)),
7522 cx,
7523 );
7524 } else {
7525 editor.scroll_manager.hide_minimap_thumb(cx);
7526 }
7527 cx.stop_propagation();
7528 });
7529 }
7530 });
7531 } else {
7532 window.on_mouse_event({
7533 let editor = self.editor.clone();
7534
7535 move |event: &MouseDownEvent, phase, window, cx| {
7536 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
7537 return;
7538 }
7539
7540 let event_position = event.position;
7541
7542 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
7543 return;
7544 };
7545
7546 editor.update(cx, |editor, cx| {
7547 if !thumb_bounds.contains(&event_position) {
7548 let click_position =
7549 event_position.relative_to(&minimap_hitbox.origin).y;
7550
7551 let top_position = (click_position
7552 - thumb_bounds.size.along(minimap_axis) / 2.0)
7553 .max(Pixels::ZERO);
7554
7555 let scroll_offset = (layout.minimap_scroll_top
7556 + ScrollPixelOffset::from(
7557 top_position / layout.minimap_line_height,
7558 ))
7559 .min(layout.max_scroll_top);
7560
7561 let scroll_position = editor
7562 .scroll_position(cx)
7563 .apply_along(minimap_axis, |_| scroll_offset);
7564 editor.set_scroll_position(scroll_position, window, cx);
7565 }
7566
7567 editor.scroll_manager.set_is_dragging_minimap(cx);
7568 cx.stop_propagation();
7569 });
7570 }
7571 });
7572 }
7573 }
7574 }
7575
7576 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7577 for mut block in layout.blocks.drain(..) {
7578 if block.overlaps_gutter {
7579 block.element.paint(window, cx);
7580 } else {
7581 let mut bounds = layout.hitbox.bounds;
7582 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
7583 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7584 block.element.paint(window, cx);
7585 })
7586 }
7587 }
7588 }
7589
7590 fn paint_edit_prediction_popover(
7591 &mut self,
7592 layout: &mut EditorLayout,
7593 window: &mut Window,
7594 cx: &mut App,
7595 ) {
7596 if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
7597 edit_prediction_popover.paint(window, cx);
7598 }
7599 }
7600
7601 fn paint_mouse_context_menu(
7602 &mut self,
7603 layout: &mut EditorLayout,
7604 window: &mut Window,
7605 cx: &mut App,
7606 ) {
7607 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
7608 mouse_context_menu.paint(window, cx);
7609 }
7610 }
7611
7612 fn paint_scroll_wheel_listener(
7613 &mut self,
7614 layout: &EditorLayout,
7615 window: &mut Window,
7616 cx: &mut App,
7617 ) {
7618 window.on_mouse_event({
7619 let position_map = layout.position_map.clone();
7620 let editor = self.editor.clone();
7621 let hitbox = layout.hitbox.clone();
7622 let mut delta = ScrollDelta::default();
7623
7624 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
7625 // accidentally turn off their scrolling.
7626 let base_scroll_sensitivity =
7627 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
7628
7629 // Use a minimum fast_scroll_sensitivity for same reason above
7630 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
7631 .fast_scroll_sensitivity
7632 .max(0.01);
7633
7634 move |event: &ScrollWheelEvent, phase, window, cx| {
7635 let scroll_sensitivity = {
7636 if event.modifiers.alt {
7637 fast_scroll_sensitivity
7638 } else {
7639 base_scroll_sensitivity
7640 }
7641 };
7642
7643 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
7644 delta = delta.coalesce(event.delta);
7645 editor.update(cx, |editor, cx| {
7646 let position_map: &PositionMap = &position_map;
7647
7648 let line_height = position_map.line_height;
7649 let max_glyph_advance = position_map.em_advance;
7650 let (delta, axis) = match delta {
7651 gpui::ScrollDelta::Pixels(mut pixels) => {
7652 //Trackpad
7653 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7654 (pixels, axis)
7655 }
7656
7657 gpui::ScrollDelta::Lines(lines) => {
7658 //Not trackpad
7659 let pixels =
7660 point(lines.x * max_glyph_advance, lines.y * line_height);
7661 (pixels, None)
7662 }
7663 };
7664
7665 let current_scroll_position = position_map.snapshot.scroll_position();
7666 let x = (current_scroll_position.x
7667 * ScrollPixelOffset::from(max_glyph_advance)
7668 - ScrollPixelOffset::from(delta.x * scroll_sensitivity))
7669 / ScrollPixelOffset::from(max_glyph_advance);
7670 let y = (current_scroll_position.y * ScrollPixelOffset::from(line_height)
7671 - ScrollPixelOffset::from(delta.y * scroll_sensitivity))
7672 / ScrollPixelOffset::from(line_height);
7673 let mut scroll_position =
7674 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7675 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
7676 if forbid_vertical_scroll {
7677 scroll_position.y = current_scroll_position.y;
7678 }
7679
7680 if scroll_position != current_scroll_position {
7681 editor.scroll(scroll_position, axis, window, cx);
7682 cx.stop_propagation();
7683 } else if y < 0. {
7684 // Due to clamping, we may fail to detect cases of overscroll to the top;
7685 // We want the scroll manager to get an update in such cases and detect the change of direction
7686 // on the next frame.
7687 cx.notify();
7688 }
7689 });
7690 }
7691 }
7692 });
7693 }
7694
7695 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7696 if layout.mode.is_minimap() {
7697 return;
7698 }
7699
7700 self.paint_scroll_wheel_listener(layout, window, cx);
7701
7702 window.on_mouse_event({
7703 let position_map = layout.position_map.clone();
7704 let editor = self.editor.clone();
7705 let line_numbers = layout.line_numbers.clone();
7706
7707 move |event: &MouseDownEvent, phase, window, cx| {
7708 if phase == DispatchPhase::Bubble {
7709 match event.button {
7710 MouseButton::Left => editor.update(cx, |editor, cx| {
7711 let pending_mouse_down = editor
7712 .pending_mouse_down
7713 .get_or_insert_with(Default::default)
7714 .clone();
7715
7716 *pending_mouse_down.borrow_mut() = Some(event.clone());
7717
7718 Self::mouse_left_down(
7719 editor,
7720 event,
7721 &position_map,
7722 line_numbers.as_ref(),
7723 window,
7724 cx,
7725 );
7726 }),
7727 MouseButton::Right => editor.update(cx, |editor, cx| {
7728 Self::mouse_right_down(editor, event, &position_map, window, cx);
7729 }),
7730 MouseButton::Middle => editor.update(cx, |editor, cx| {
7731 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7732 }),
7733 _ => {}
7734 };
7735 }
7736 }
7737 });
7738
7739 window.on_mouse_event({
7740 let editor = self.editor.clone();
7741 let position_map = layout.position_map.clone();
7742
7743 move |event: &MouseUpEvent, phase, window, cx| {
7744 if phase == DispatchPhase::Bubble {
7745 editor.update(cx, |editor, cx| {
7746 Self::mouse_up(editor, event, &position_map, window, cx)
7747 });
7748 }
7749 }
7750 });
7751
7752 window.on_mouse_event({
7753 let editor = self.editor.clone();
7754 let position_map = layout.position_map.clone();
7755 let mut captured_mouse_down = None;
7756
7757 move |event: &MouseUpEvent, phase, window, cx| match phase {
7758 // Clear the pending mouse down during the capture phase,
7759 // so that it happens even if another event handler stops
7760 // propagation.
7761 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7762 let pending_mouse_down = editor
7763 .pending_mouse_down
7764 .get_or_insert_with(Default::default)
7765 .clone();
7766
7767 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7768 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7769 captured_mouse_down = pending_mouse_down.take();
7770 window.refresh();
7771 }
7772 }),
7773 // Fire click handlers during the bubble phase.
7774 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7775 if let Some(mouse_down) = captured_mouse_down.take() {
7776 let event = ClickEvent::Mouse(MouseClickEvent {
7777 down: mouse_down,
7778 up: event.clone(),
7779 });
7780 Self::click(editor, &event, &position_map, window, cx);
7781 }
7782 }),
7783 }
7784 });
7785
7786 window.on_mouse_event({
7787 let position_map = layout.position_map.clone();
7788 let editor = self.editor.clone();
7789
7790 move |event: &MousePressureEvent, phase, window, cx| {
7791 if phase == DispatchPhase::Bubble {
7792 editor.update(cx, |editor, cx| {
7793 Self::pressure_click(editor, &event, &position_map, window, cx);
7794 })
7795 }
7796 }
7797 });
7798
7799 window.on_mouse_event({
7800 let position_map = layout.position_map.clone();
7801 let editor = self.editor.clone();
7802
7803 move |event: &MouseMoveEvent, phase, window, cx| {
7804 if phase == DispatchPhase::Bubble {
7805 editor.update(cx, |editor, cx| {
7806 if editor.hover_state.focused(window, cx) {
7807 return;
7808 }
7809 if event.pressed_button == Some(MouseButton::Left)
7810 || event.pressed_button == Some(MouseButton::Middle)
7811 {
7812 Self::mouse_dragged(editor, event, &position_map, window, cx)
7813 }
7814
7815 Self::mouse_moved(editor, event, &position_map, window, cx)
7816 });
7817 }
7818 }
7819 });
7820 }
7821
7822 fn shape_line_number(
7823 &self,
7824 text: SharedString,
7825 color: Hsla,
7826 window: &mut Window,
7827 ) -> ShapedLine {
7828 let run = TextRun {
7829 len: text.len(),
7830 font: self.style.text.font(),
7831 color,
7832 ..Default::default()
7833 };
7834 window.text_system().shape_line(
7835 text,
7836 self.style.text.font_size.to_pixels(window.rem_size()),
7837 &[run],
7838 None,
7839 )
7840 }
7841
7842 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7843 let unstaged = status.has_secondary_hunk();
7844 let unstaged_hollow = matches!(
7845 ProjectSettings::get_global(cx).git.hunk_style,
7846 GitHunkStyleSetting::UnstagedHollow
7847 );
7848
7849 unstaged == unstaged_hollow
7850 }
7851
7852 #[cfg(debug_assertions)]
7853 fn layout_debug_ranges(
7854 selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
7855 anchor_range: Range<Anchor>,
7856 display_snapshot: &DisplaySnapshot,
7857 cx: &App,
7858 ) {
7859 let theme = cx.theme();
7860 text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
7861 if debug_ranges.ranges.is_empty() {
7862 return;
7863 }
7864 let buffer_snapshot = &display_snapshot.buffer_snapshot();
7865 for (buffer, buffer_range, excerpt_id) in
7866 buffer_snapshot.range_to_buffer_ranges(anchor_range)
7867 {
7868 let buffer_range =
7869 buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
7870 selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
7871 let player_color = theme
7872 .players()
7873 .color_for_participant(debug_range.occurrence_index as u32 + 1);
7874 debug_range.ranges.iter().filter_map(move |range| {
7875 if range.start.buffer_id != Some(buffer.remote_id()) {
7876 return None;
7877 }
7878 let clipped_start = range.start.max(&buffer_range.start, buffer);
7879 let clipped_end = range.end.min(&buffer_range.end, buffer);
7880 let range = buffer_snapshot
7881 .anchor_range_in_excerpt(excerpt_id, *clipped_start..*clipped_end)?;
7882 let start = range.start.to_display_point(display_snapshot);
7883 let end = range.end.to_display_point(display_snapshot);
7884 let selection_layout = SelectionLayout {
7885 head: start,
7886 range: start..end,
7887 cursor_shape: CursorShape::Bar,
7888 is_newest: false,
7889 is_local: false,
7890 active_rows: start.row()..end.row(),
7891 user_name: Some(SharedString::new(debug_range.value.clone())),
7892 };
7893 Some((player_color, vec![selection_layout]))
7894 })
7895 }));
7896 }
7897 });
7898 }
7899}
7900
7901pub fn render_breadcrumb_text(
7902 mut segments: Vec<BreadcrumbText>,
7903 prefix: Option<gpui::AnyElement>,
7904 active_item: &dyn ItemHandle,
7905 window: &mut Window,
7906 cx: &App,
7907) -> impl IntoElement {
7908 const MAX_SEGMENTS: usize = 12;
7909
7910 let element = h_flex().id("breadcrumb-container").flex_grow().text_ui(cx);
7911
7912 let prefix_end_ix = cmp::min(segments.len(), MAX_SEGMENTS / 2);
7913 let suffix_start_ix = cmp::max(
7914 prefix_end_ix,
7915 segments.len().saturating_sub(MAX_SEGMENTS / 2),
7916 );
7917
7918 if suffix_start_ix > prefix_end_ix {
7919 segments.splice(
7920 prefix_end_ix..suffix_start_ix,
7921 Some(BreadcrumbText {
7922 text: "β―".into(),
7923 highlights: None,
7924 font: None,
7925 }),
7926 );
7927 }
7928
7929 let highlighted_segments = segments.into_iter().enumerate().map(|(index, segment)| {
7930 let mut text_style = window.text_style();
7931 if let Some(ref font) = segment.font {
7932 text_style.font_family = font.family.clone();
7933 text_style.font_features = font.features.clone();
7934 text_style.font_style = font.style;
7935 text_style.font_weight = font.weight;
7936 }
7937 text_style.color = Color::Muted.color(cx);
7938
7939 if index == 0
7940 && !workspace::TabBarSettings::get_global(cx).show
7941 && active_item.is_dirty(cx)
7942 && let Some(styled_element) = apply_dirty_filename_style(&segment, &text_style, cx)
7943 {
7944 return styled_element;
7945 }
7946
7947 StyledText::new(segment.text.replace('\n', "β"))
7948 .with_default_highlights(&text_style, segment.highlights.unwrap_or_default())
7949 .into_any()
7950 });
7951 let breadcrumbs = Itertools::intersperse_with(highlighted_segments, || {
7952 Label::new("βΊ").color(Color::Placeholder).into_any_element()
7953 });
7954
7955 let breadcrumbs_stack = h_flex().gap_1().children(breadcrumbs);
7956
7957 let breadcrumbs = if let Some(prefix) = prefix {
7958 h_flex().gap_1p5().child(prefix).child(breadcrumbs_stack)
7959 } else {
7960 breadcrumbs_stack
7961 };
7962
7963 match active_item
7964 .downcast::<Editor>()
7965 .map(|editor| editor.downgrade())
7966 {
7967 Some(editor) => element.child(
7968 ButtonLike::new("toggle outline view")
7969 .child(breadcrumbs)
7970 .style(ButtonStyle::Transparent)
7971 .on_click({
7972 let editor = editor.clone();
7973 move |_, window, cx| {
7974 if let Some((editor, callback)) = editor
7975 .upgrade()
7976 .zip(zed_actions::outline::TOGGLE_OUTLINE.get())
7977 {
7978 callback(editor.to_any_view(), window, cx);
7979 }
7980 }
7981 })
7982 .tooltip(move |_window, cx| {
7983 if let Some(editor) = editor.upgrade() {
7984 let focus_handle = editor.read(cx).focus_handle(cx);
7985 Tooltip::for_action_in(
7986 "Show Symbol Outline",
7987 &zed_actions::outline::ToggleOutline,
7988 &focus_handle,
7989 cx,
7990 )
7991 } else {
7992 Tooltip::for_action(
7993 "Show Symbol Outline",
7994 &zed_actions::outline::ToggleOutline,
7995 cx,
7996 )
7997 }
7998 }),
7999 ),
8000 None => element
8001 // Match the height and padding of the `ButtonLike` in the other arm.
8002 .h(rems_from_px(22.))
8003 .pl_1()
8004 .child(breadcrumbs),
8005 }
8006}
8007
8008fn apply_dirty_filename_style(
8009 segment: &BreadcrumbText,
8010 text_style: &gpui::TextStyle,
8011 cx: &App,
8012) -> Option<gpui::AnyElement> {
8013 let text = segment.text.replace('\n', "β");
8014
8015 let filename_position = std::path::Path::new(&segment.text)
8016 .file_name()
8017 .and_then(|f| {
8018 let filename_str = f.to_string_lossy();
8019 segment.text.rfind(filename_str.as_ref())
8020 })?;
8021
8022 let bold_weight = FontWeight::BOLD;
8023 let default_color = Color::Default.color(cx);
8024
8025 if filename_position == 0 {
8026 let mut filename_style = text_style.clone();
8027 filename_style.font_weight = bold_weight;
8028 filename_style.color = default_color;
8029
8030 return Some(
8031 StyledText::new(text)
8032 .with_default_highlights(&filename_style, [])
8033 .into_any(),
8034 );
8035 }
8036
8037 let highlight_style = gpui::HighlightStyle {
8038 font_weight: Some(bold_weight),
8039 color: Some(default_color),
8040 ..Default::default()
8041 };
8042
8043 let highlight = vec![(filename_position..text.len(), highlight_style)];
8044 Some(
8045 StyledText::new(text)
8046 .with_default_highlights(text_style, highlight)
8047 .into_any(),
8048 )
8049}
8050
8051fn file_status_label_color(file_status: Option<FileStatus>) -> Color {
8052 file_status.map_or(Color::Default, |status| {
8053 if status.is_conflicted() {
8054 Color::Conflict
8055 } else if status.is_modified() {
8056 Color::Modified
8057 } else if status.is_deleted() {
8058 Color::Disabled
8059 } else if status.is_created() {
8060 Color::Created
8061 } else {
8062 Color::Default
8063 }
8064 })
8065}
8066
8067fn header_jump_data(
8068 editor_snapshot: &EditorSnapshot,
8069 block_row_start: DisplayRow,
8070 height: u32,
8071 first_excerpt: &ExcerptInfo,
8072 latest_selection_anchors: &HashMap<BufferId, Anchor>,
8073) -> JumpData {
8074 let jump_target = if let Some(anchor) = latest_selection_anchors.get(&first_excerpt.buffer_id)
8075 && let Some(range) = editor_snapshot.context_range_for_excerpt(anchor.excerpt_id)
8076 && let Some(buffer) = editor_snapshot
8077 .buffer_snapshot()
8078 .buffer_for_excerpt(anchor.excerpt_id)
8079 {
8080 JumpTargetInExcerptInput {
8081 id: anchor.excerpt_id,
8082 buffer,
8083 excerpt_start_anchor: range.start,
8084 jump_anchor: anchor.text_anchor,
8085 }
8086 } else {
8087 JumpTargetInExcerptInput {
8088 id: first_excerpt.id,
8089 buffer: &first_excerpt.buffer,
8090 excerpt_start_anchor: first_excerpt.range.context.start,
8091 jump_anchor: first_excerpt.range.primary.start,
8092 }
8093 };
8094 header_jump_data_inner(editor_snapshot, block_row_start, height, &jump_target)
8095}
8096
8097struct JumpTargetInExcerptInput<'a> {
8098 id: ExcerptId,
8099 buffer: &'a language::BufferSnapshot,
8100 excerpt_start_anchor: text::Anchor,
8101 jump_anchor: text::Anchor,
8102}
8103
8104fn header_jump_data_inner(
8105 snapshot: &EditorSnapshot,
8106 block_row_start: DisplayRow,
8107 height: u32,
8108 for_excerpt: &JumpTargetInExcerptInput,
8109) -> JumpData {
8110 let buffer = &for_excerpt.buffer;
8111 let jump_position = language::ToPoint::to_point(&for_excerpt.jump_anchor, buffer);
8112 let excerpt_start = for_excerpt.excerpt_start_anchor;
8113 let rows_from_excerpt_start = if for_excerpt.jump_anchor == excerpt_start {
8114 0
8115 } else {
8116 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
8117 jump_position.row.saturating_sub(excerpt_start_point.row)
8118 };
8119
8120 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
8121 .saturating_sub(
8122 snapshot
8123 .scroll_anchor
8124 .scroll_position(&snapshot.display_snapshot)
8125 .y as u32,
8126 );
8127
8128 JumpData::MultiBufferPoint {
8129 excerpt_id: for_excerpt.id,
8130 anchor: for_excerpt.jump_anchor,
8131 position: jump_position,
8132 line_offset_from_top,
8133 }
8134}
8135
8136pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
8137
8138impl AcceptEditPredictionBinding {
8139 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
8140 if let Some(binding) = self.0.as_ref() {
8141 match &binding.keystrokes() {
8142 [keystroke, ..] => Some(keystroke),
8143 _ => None,
8144 }
8145 } else {
8146 None
8147 }
8148 }
8149}
8150
8151fn prepaint_gutter_button(
8152 button: IconButton,
8153 row: DisplayRow,
8154 line_height: Pixels,
8155 gutter_dimensions: &GutterDimensions,
8156 scroll_position: gpui::Point<ScrollOffset>,
8157 gutter_hitbox: &Hitbox,
8158 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
8159 window: &mut Window,
8160 cx: &mut App,
8161) -> AnyElement {
8162 let mut button = button.into_any_element();
8163
8164 let available_space = size(
8165 AvailableSpace::MinContent,
8166 AvailableSpace::Definite(line_height),
8167 );
8168 let indicator_size = button.layout_as_root(available_space, window, cx);
8169
8170 let blame_width = gutter_dimensions.git_blame_entries_width;
8171 let gutter_width = display_hunks
8172 .binary_search_by(|(hunk, _)| match hunk {
8173 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
8174 DisplayDiffHunk::Unfolded {
8175 display_row_range, ..
8176 } => {
8177 if display_row_range.end <= row {
8178 Ordering::Less
8179 } else if display_row_range.start > row {
8180 Ordering::Greater
8181 } else {
8182 Ordering::Equal
8183 }
8184 }
8185 })
8186 .ok()
8187 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
8188 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
8189
8190 let mut x = left_offset;
8191 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
8192 - indicator_size.width
8193 - left_offset;
8194 x += available_width / 2.;
8195
8196 let mut y =
8197 Pixels::from((row.as_f64() - scroll_position.y) * ScrollPixelOffset::from(line_height));
8198 y += (line_height - indicator_size.height) / 2.;
8199
8200 button.prepaint_as_root(
8201 gutter_hitbox.origin + point(x, y),
8202 available_space,
8203 window,
8204 cx,
8205 );
8206 button
8207}
8208
8209fn render_inline_blame_entry(
8210 blame_entry: BlameEntry,
8211 style: &EditorStyle,
8212 cx: &mut App,
8213) -> Option<AnyElement> {
8214 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8215 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
8216}
8217
8218fn render_blame_entry_popover(
8219 blame_entry: BlameEntry,
8220 scroll_handle: ScrollHandle,
8221 commit_message: Option<ParsedCommitMessage>,
8222 markdown: Entity<Markdown>,
8223 workspace: WeakEntity<Workspace>,
8224 blame: &Entity<GitBlame>,
8225 buffer: BufferId,
8226 window: &mut Window,
8227 cx: &mut App,
8228) -> Option<AnyElement> {
8229 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
8230 let blame = blame.read(cx);
8231 let repository = blame.repository(cx, buffer)?;
8232 renderer.render_blame_entry_popover(
8233 blame_entry,
8234 scroll_handle,
8235 commit_message,
8236 markdown,
8237 repository,
8238 workspace,
8239 window,
8240 cx,
8241 )
8242}
8243
8244fn render_blame_entry(
8245 ix: usize,
8246 blame: &Entity<GitBlame>,
8247 blame_entry: BlameEntry,
8248 style: &EditorStyle,
8249 last_used_color: &mut Option<(Hsla, Oid)>,
8250 editor: Entity<Editor>,
8251 workspace: Entity<Workspace>,
8252 buffer: BufferId,
8253 renderer: &dyn BlameRenderer,
8254 window: &mut Window,
8255 cx: &mut App,
8256) -> Option<AnyElement> {
8257 let index: u32 = blame_entry.sha.into();
8258 let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
8259
8260 // If the last color we used is the same as the one we get for this line, but
8261 // the commit SHAs are different, then we try again to get a different color.
8262 if let Some((color, sha)) = *last_used_color
8263 && sha != blame_entry.sha
8264 && color == sha_color
8265 {
8266 sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
8267 }
8268 last_used_color.replace((sha_color, blame_entry.sha));
8269
8270 let blame = blame.read(cx);
8271 let details = blame.details_for_entry(buffer, &blame_entry);
8272 let repository = blame.repository(cx, buffer)?;
8273 renderer.render_blame_entry(
8274 &style.text,
8275 blame_entry,
8276 details,
8277 repository,
8278 workspace.downgrade(),
8279 editor,
8280 ix,
8281 sha_color,
8282 window,
8283 cx,
8284 )
8285}
8286
8287#[derive(Debug)]
8288pub(crate) struct LineWithInvisibles {
8289 fragments: SmallVec<[LineFragment; 1]>,
8290 invisibles: Vec<Invisible>,
8291 len: usize,
8292 pub(crate) width: Pixels,
8293 font_size: Pixels,
8294}
8295
8296enum LineFragment {
8297 Text(ShapedLine),
8298 Element {
8299 id: ChunkRendererId,
8300 element: Option<AnyElement>,
8301 size: Size<Pixels>,
8302 len: usize,
8303 },
8304}
8305
8306impl fmt::Debug for LineFragment {
8307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8308 match self {
8309 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
8310 LineFragment::Element { size, len, .. } => f
8311 .debug_struct("Element")
8312 .field("size", size)
8313 .field("len", len)
8314 .finish(),
8315 }
8316 }
8317}
8318
8319impl LineWithInvisibles {
8320 fn from_chunks<'a>(
8321 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
8322 editor_style: &EditorStyle,
8323 max_line_len: usize,
8324 max_line_count: usize,
8325 editor_mode: &EditorMode,
8326 text_width: Pixels,
8327 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8328 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
8329 window: &mut Window,
8330 cx: &mut App,
8331 ) -> Vec<Self> {
8332 let text_style = &editor_style.text;
8333 let mut layouts = Vec::with_capacity(max_line_count);
8334 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
8335 let mut line = String::new();
8336 let mut invisibles = Vec::new();
8337 let mut width = Pixels::ZERO;
8338 let mut len = 0;
8339 let mut styles = Vec::new();
8340 let mut non_whitespace_added = false;
8341 let mut row = 0;
8342 let mut line_exceeded_max_len = false;
8343 let font_size = text_style.font_size.to_pixels(window.rem_size());
8344 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
8345
8346 let ellipsis = SharedString::from("β―");
8347
8348 for highlighted_chunk in chunks.chain([HighlightedChunk {
8349 text: "\n",
8350 style: None,
8351 is_tab: false,
8352 is_inlay: false,
8353 replacement: None,
8354 }]) {
8355 if let Some(replacement) = highlighted_chunk.replacement {
8356 if !line.is_empty() {
8357 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8358 let text_runs: &[TextRun] = if segments.is_empty() {
8359 &styles
8360 } else {
8361 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8362 };
8363 let shaped_line = window.text_system().shape_line(
8364 line.clone().into(),
8365 font_size,
8366 text_runs,
8367 None,
8368 );
8369 width += shaped_line.width;
8370 len += shaped_line.len;
8371 fragments.push(LineFragment::Text(shaped_line));
8372 line.clear();
8373 styles.clear();
8374 }
8375
8376 match replacement {
8377 ChunkReplacement::Renderer(renderer) => {
8378 let available_width = if renderer.constrain_width {
8379 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
8380 ellipsis.clone()
8381 } else {
8382 SharedString::from(Arc::from(highlighted_chunk.text))
8383 };
8384 let shaped_line = window.text_system().shape_line(
8385 chunk,
8386 font_size,
8387 &[text_style.to_run(highlighted_chunk.text.len())],
8388 None,
8389 );
8390 AvailableSpace::Definite(shaped_line.width)
8391 } else {
8392 AvailableSpace::MinContent
8393 };
8394
8395 let mut element = (renderer.render)(&mut ChunkRendererContext {
8396 context: cx,
8397 window,
8398 max_width: text_width,
8399 });
8400 let line_height = text_style.line_height_in_pixels(window.rem_size());
8401 let size = element.layout_as_root(
8402 size(available_width, AvailableSpace::Definite(line_height)),
8403 window,
8404 cx,
8405 );
8406
8407 width += size.width;
8408 len += highlighted_chunk.text.len();
8409 fragments.push(LineFragment::Element {
8410 id: renderer.id,
8411 element: Some(element),
8412 size,
8413 len: highlighted_chunk.text.len(),
8414 });
8415 }
8416 ChunkReplacement::Str(x) => {
8417 let text_style = if let Some(style) = highlighted_chunk.style {
8418 Cow::Owned(text_style.clone().highlight(style))
8419 } else {
8420 Cow::Borrowed(text_style)
8421 };
8422
8423 let run = TextRun {
8424 len: x.len(),
8425 font: text_style.font(),
8426 color: text_style.color,
8427 background_color: text_style.background_color,
8428 underline: text_style.underline,
8429 strikethrough: text_style.strikethrough,
8430 };
8431 let line_layout = window
8432 .text_system()
8433 .shape_line(x, font_size, &[run], None)
8434 .with_len(highlighted_chunk.text.len());
8435
8436 width += line_layout.width;
8437 len += highlighted_chunk.text.len();
8438 fragments.push(LineFragment::Text(line_layout))
8439 }
8440 }
8441 } else {
8442 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
8443 if ix > 0 {
8444 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
8445 let text_runs = if segments.is_empty() {
8446 &styles
8447 } else {
8448 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
8449 };
8450 let shaped_line = window.text_system().shape_line(
8451 line.clone().into(),
8452 font_size,
8453 text_runs,
8454 None,
8455 );
8456 width += shaped_line.width;
8457 len += shaped_line.len;
8458 fragments.push(LineFragment::Text(shaped_line));
8459 layouts.push(Self {
8460 width: mem::take(&mut width),
8461 len: mem::take(&mut len),
8462 fragments: mem::take(&mut fragments),
8463 invisibles: std::mem::take(&mut invisibles),
8464 font_size,
8465 });
8466
8467 line.clear();
8468 styles.clear();
8469 row += 1;
8470 line_exceeded_max_len = false;
8471 non_whitespace_added = false;
8472 if row == max_line_count {
8473 return layouts;
8474 }
8475 }
8476
8477 if !line_chunk.is_empty() && !line_exceeded_max_len {
8478 let text_style = if let Some(style) = highlighted_chunk.style {
8479 Cow::Owned(text_style.clone().highlight(style))
8480 } else {
8481 Cow::Borrowed(text_style)
8482 };
8483
8484 if line.len() + line_chunk.len() > max_line_len {
8485 let mut chunk_len = max_line_len - line.len();
8486 while !line_chunk.is_char_boundary(chunk_len) {
8487 chunk_len -= 1;
8488 }
8489 line_chunk = &line_chunk[..chunk_len];
8490 line_exceeded_max_len = true;
8491 }
8492
8493 styles.push(TextRun {
8494 len: line_chunk.len(),
8495 font: text_style.font(),
8496 color: text_style.color,
8497 background_color: text_style.background_color,
8498 underline: text_style.underline,
8499 strikethrough: text_style.strikethrough,
8500 });
8501
8502 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
8503 // Line wrap pads its contents with fake whitespaces,
8504 // avoid printing them
8505 let is_soft_wrapped = is_row_soft_wrapped(row);
8506 if highlighted_chunk.is_tab {
8507 if non_whitespace_added || !is_soft_wrapped {
8508 invisibles.push(Invisible::Tab {
8509 line_start_offset: line.len(),
8510 line_end_offset: line.len() + line_chunk.len(),
8511 });
8512 }
8513 } else {
8514 invisibles.extend(line_chunk.char_indices().filter_map(
8515 |(index, c)| {
8516 let is_whitespace = c.is_whitespace();
8517 non_whitespace_added |= !is_whitespace;
8518 if is_whitespace
8519 && (non_whitespace_added || !is_soft_wrapped)
8520 {
8521 Some(Invisible::Whitespace {
8522 line_offset: line.len() + index,
8523 })
8524 } else {
8525 None
8526 }
8527 },
8528 ))
8529 }
8530 }
8531
8532 line.push_str(line_chunk);
8533 }
8534 }
8535 }
8536 }
8537
8538 layouts
8539 }
8540
8541 /// Takes text runs and non-overlapping left-to-right background ranges with color.
8542 /// Returns new text runs with adjusted contrast as per background ranges.
8543 fn split_runs_by_bg_segments(
8544 text_runs: &[TextRun],
8545 bg_segments: &[(Range<DisplayPoint>, Hsla)],
8546 min_contrast: f32,
8547 start_col_offset: usize,
8548 ) -> Vec<TextRun> {
8549 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
8550 let mut line_col = start_col_offset;
8551 let mut segment_ix = 0usize;
8552
8553 for text_run in text_runs.iter() {
8554 let run_start_col = line_col;
8555 let run_end_col = run_start_col + text_run.len;
8556 while segment_ix < bg_segments.len()
8557 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
8558 {
8559 segment_ix += 1;
8560 }
8561 let mut cursor_col = run_start_col;
8562 let mut local_segment_ix = segment_ix;
8563 while local_segment_ix < bg_segments.len() {
8564 let (range, segment_color) = &bg_segments[local_segment_ix];
8565 let segment_start_col = range.start.column() as usize;
8566 let segment_end_col = range.end.column() as usize;
8567 if segment_start_col >= run_end_col {
8568 break;
8569 }
8570 if segment_start_col > cursor_col {
8571 let span_len = segment_start_col - cursor_col;
8572 output_runs.push(TextRun {
8573 len: span_len,
8574 font: text_run.font.clone(),
8575 color: text_run.color,
8576 background_color: text_run.background_color,
8577 underline: text_run.underline,
8578 strikethrough: text_run.strikethrough,
8579 });
8580 cursor_col = segment_start_col;
8581 }
8582 let segment_slice_end_col = segment_end_col.min(run_end_col);
8583 if segment_slice_end_col > cursor_col {
8584 let new_text_color =
8585 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
8586 output_runs.push(TextRun {
8587 len: segment_slice_end_col - cursor_col,
8588 font: text_run.font.clone(),
8589 color: new_text_color,
8590 background_color: text_run.background_color,
8591 underline: text_run.underline,
8592 strikethrough: text_run.strikethrough,
8593 });
8594 cursor_col = segment_slice_end_col;
8595 }
8596 if segment_end_col >= run_end_col {
8597 break;
8598 }
8599 local_segment_ix += 1;
8600 }
8601 if cursor_col < run_end_col {
8602 output_runs.push(TextRun {
8603 len: run_end_col - cursor_col,
8604 font: text_run.font.clone(),
8605 color: text_run.color,
8606 background_color: text_run.background_color,
8607 underline: text_run.underline,
8608 strikethrough: text_run.strikethrough,
8609 });
8610 }
8611 line_col = run_end_col;
8612 segment_ix = local_segment_ix;
8613 }
8614 output_runs
8615 }
8616
8617 fn prepaint(
8618 &mut self,
8619 line_height: Pixels,
8620 scroll_position: gpui::Point<ScrollOffset>,
8621 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8622 row: DisplayRow,
8623 content_origin: gpui::Point<Pixels>,
8624 line_elements: &mut SmallVec<[AnyElement; 1]>,
8625 window: &mut Window,
8626 cx: &mut App,
8627 ) {
8628 let line_y = f32::from(line_height) * Pixels::from(row.as_f64() - scroll_position.y);
8629 self.prepaint_with_custom_offset(
8630 line_height,
8631 scroll_pixel_position,
8632 content_origin,
8633 line_y,
8634 line_elements,
8635 window,
8636 cx,
8637 );
8638 }
8639
8640 fn prepaint_with_custom_offset(
8641 &mut self,
8642 line_height: Pixels,
8643 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
8644 content_origin: gpui::Point<Pixels>,
8645 line_y: Pixels,
8646 line_elements: &mut SmallVec<[AnyElement; 1]>,
8647 window: &mut Window,
8648 cx: &mut App,
8649 ) {
8650 let mut fragment_origin =
8651 content_origin + gpui::point(Pixels::from(-scroll_pixel_position.x), line_y);
8652 for fragment in &mut self.fragments {
8653 match fragment {
8654 LineFragment::Text(line) => {
8655 fragment_origin.x += line.width;
8656 }
8657 LineFragment::Element { element, size, .. } => {
8658 let mut element = element
8659 .take()
8660 .expect("you can't prepaint LineWithInvisibles twice");
8661
8662 // Center the element vertically within the line.
8663 let mut element_origin = fragment_origin;
8664 element_origin.y += (line_height - size.height) / 2.;
8665 element.prepaint_at(element_origin, window, cx);
8666 line_elements.push(element);
8667
8668 fragment_origin.x += size.width;
8669 }
8670 }
8671 }
8672 }
8673
8674 fn draw(
8675 &self,
8676 layout: &EditorLayout,
8677 row: DisplayRow,
8678 content_origin: gpui::Point<Pixels>,
8679 whitespace_setting: ShowWhitespaceSetting,
8680 selection_ranges: &[Range<DisplayPoint>],
8681 window: &mut Window,
8682 cx: &mut App,
8683 ) {
8684 self.draw_with_custom_offset(
8685 layout,
8686 row,
8687 content_origin,
8688 layout.position_map.line_height
8689 * (row.as_f64() - layout.position_map.scroll_position.y) as f32,
8690 whitespace_setting,
8691 selection_ranges,
8692 window,
8693 cx,
8694 );
8695 }
8696
8697 fn draw_with_custom_offset(
8698 &self,
8699 layout: &EditorLayout,
8700 row: DisplayRow,
8701 content_origin: gpui::Point<Pixels>,
8702 line_y: Pixels,
8703 whitespace_setting: ShowWhitespaceSetting,
8704 selection_ranges: &[Range<DisplayPoint>],
8705 window: &mut Window,
8706 cx: &mut App,
8707 ) {
8708 let line_height = layout.position_map.line_height;
8709 let mut fragment_origin = content_origin
8710 + gpui::point(
8711 Pixels::from(-layout.position_map.scroll_pixel_position.x),
8712 line_y,
8713 );
8714
8715 for fragment in &self.fragments {
8716 match fragment {
8717 LineFragment::Text(line) => {
8718 line.paint(
8719 fragment_origin,
8720 line_height,
8721 layout.text_align,
8722 Some(layout.content_width),
8723 window,
8724 cx,
8725 )
8726 .log_err();
8727 fragment_origin.x += line.width;
8728 }
8729 LineFragment::Element { size, .. } => {
8730 fragment_origin.x += size.width;
8731 }
8732 }
8733 }
8734
8735 self.draw_invisibles(
8736 selection_ranges,
8737 layout,
8738 content_origin,
8739 line_y,
8740 row,
8741 line_height,
8742 whitespace_setting,
8743 window,
8744 cx,
8745 );
8746 }
8747
8748 fn draw_background(
8749 &self,
8750 layout: &EditorLayout,
8751 row: DisplayRow,
8752 content_origin: gpui::Point<Pixels>,
8753 window: &mut Window,
8754 cx: &mut App,
8755 ) {
8756 let line_height = layout.position_map.line_height;
8757 let line_y = line_height * (row.as_f64() - layout.position_map.scroll_position.y) as f32;
8758
8759 let mut fragment_origin = content_origin
8760 + gpui::point(
8761 Pixels::from(-layout.position_map.scroll_pixel_position.x),
8762 line_y,
8763 );
8764
8765 for fragment in &self.fragments {
8766 match fragment {
8767 LineFragment::Text(line) => {
8768 line.paint_background(
8769 fragment_origin,
8770 line_height,
8771 layout.text_align,
8772 Some(layout.content_width),
8773 window,
8774 cx,
8775 )
8776 .log_err();
8777 fragment_origin.x += line.width;
8778 }
8779 LineFragment::Element { size, .. } => {
8780 fragment_origin.x += size.width;
8781 }
8782 }
8783 }
8784 }
8785
8786 fn draw_invisibles(
8787 &self,
8788 selection_ranges: &[Range<DisplayPoint>],
8789 layout: &EditorLayout,
8790 content_origin: gpui::Point<Pixels>,
8791 line_y: Pixels,
8792 row: DisplayRow,
8793 line_height: Pixels,
8794 whitespace_setting: ShowWhitespaceSetting,
8795 window: &mut Window,
8796 cx: &mut App,
8797 ) {
8798 let extract_whitespace_info = |invisible: &Invisible| {
8799 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
8800 Invisible::Tab {
8801 line_start_offset,
8802 line_end_offset,
8803 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
8804 Invisible::Whitespace { line_offset } => {
8805 (*line_offset, line_offset + 1, &layout.space_invisible)
8806 }
8807 };
8808
8809 let x_offset: ScrollPixelOffset = self.x_for_index(token_offset).into();
8810 let invisible_offset: ScrollPixelOffset =
8811 ((layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0)
8812 .into();
8813 let origin = content_origin
8814 + gpui::point(
8815 Pixels::from(
8816 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
8817 ),
8818 line_y,
8819 );
8820
8821 (
8822 [token_offset, token_end_offset],
8823 Box::new(move |window: &mut Window, cx: &mut App| {
8824 invisible_symbol
8825 .paint(origin, line_height, TextAlign::Left, None, window, cx)
8826 .log_err();
8827 }),
8828 )
8829 };
8830
8831 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
8832 match whitespace_setting {
8833 ShowWhitespaceSetting::None => (),
8834 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
8835 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
8836 let invisible_point = DisplayPoint::new(row, start as u32);
8837 if !selection_ranges
8838 .iter()
8839 .any(|region| region.start <= invisible_point && invisible_point < region.end)
8840 {
8841 return;
8842 }
8843
8844 paint(window, cx);
8845 }),
8846
8847 ShowWhitespaceSetting::Trailing => {
8848 let mut previous_start = self.len;
8849 for ([start, end], paint) in invisible_iter.rev() {
8850 if previous_start != end {
8851 break;
8852 }
8853 previous_start = start;
8854 paint(window, cx);
8855 }
8856 }
8857
8858 // For a whitespace to be on a boundary, any of the following conditions need to be met:
8859 // - It is a tab
8860 // - It is adjacent to an edge (start or end)
8861 // - It is adjacent to a whitespace (left or right)
8862 ShowWhitespaceSetting::Boundary => {
8863 // 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
8864 // the above cases.
8865 // Note: We zip in the original `invisibles` to check for tab equality
8866 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
8867 for (([start, end], paint), invisible) in
8868 invisible_iter.zip_eq(self.invisibles.iter())
8869 {
8870 let should_render = match (&last_seen, invisible) {
8871 (_, Invisible::Tab { .. }) => true,
8872 (Some((_, last_end, _)), _) => *last_end == start,
8873 _ => false,
8874 };
8875
8876 if should_render || start == 0 || end == self.len {
8877 paint(window, cx);
8878
8879 // Since we are scanning from the left, we will skip over the first available whitespace that is part
8880 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
8881 if let Some((should_render_last, last_end, paint_last)) = last_seen {
8882 // Note that we need to make sure that the last one is actually adjacent
8883 if !should_render_last && last_end == start {
8884 paint_last(window, cx);
8885 }
8886 }
8887 }
8888
8889 // Manually render anything within a selection
8890 let invisible_point = DisplayPoint::new(row, start as u32);
8891 if selection_ranges.iter().any(|region| {
8892 region.start <= invisible_point && invisible_point < region.end
8893 }) {
8894 paint(window, cx);
8895 }
8896
8897 last_seen = Some((should_render, end, paint));
8898 }
8899 }
8900 }
8901 }
8902
8903 pub fn x_for_index(&self, index: usize) -> Pixels {
8904 let mut fragment_start_x = Pixels::ZERO;
8905 let mut fragment_start_index = 0;
8906
8907 for fragment in &self.fragments {
8908 match fragment {
8909 LineFragment::Text(shaped_line) => {
8910 let fragment_end_index = fragment_start_index + shaped_line.len;
8911 if index < fragment_end_index {
8912 return fragment_start_x
8913 + shaped_line.x_for_index(index - fragment_start_index);
8914 }
8915 fragment_start_x += shaped_line.width;
8916 fragment_start_index = fragment_end_index;
8917 }
8918 LineFragment::Element { len, size, .. } => {
8919 let fragment_end_index = fragment_start_index + len;
8920 if index < fragment_end_index {
8921 return fragment_start_x;
8922 }
8923 fragment_start_x += size.width;
8924 fragment_start_index = fragment_end_index;
8925 }
8926 }
8927 }
8928
8929 fragment_start_x
8930 }
8931
8932 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
8933 let mut fragment_start_x = Pixels::ZERO;
8934 let mut fragment_start_index = 0;
8935
8936 for fragment in &self.fragments {
8937 match fragment {
8938 LineFragment::Text(shaped_line) => {
8939 let fragment_end_x = fragment_start_x + shaped_line.width;
8940 if x < fragment_end_x {
8941 return Some(
8942 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
8943 );
8944 }
8945 fragment_start_x = fragment_end_x;
8946 fragment_start_index += shaped_line.len;
8947 }
8948 LineFragment::Element { len, size, .. } => {
8949 let fragment_end_x = fragment_start_x + size.width;
8950 if x < fragment_end_x {
8951 return Some(fragment_start_index);
8952 }
8953 fragment_start_index += len;
8954 fragment_start_x = fragment_end_x;
8955 }
8956 }
8957 }
8958
8959 None
8960 }
8961
8962 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
8963 let mut fragment_start_index = 0;
8964
8965 for fragment in &self.fragments {
8966 match fragment {
8967 LineFragment::Text(shaped_line) => {
8968 let fragment_end_index = fragment_start_index + shaped_line.len;
8969 if index < fragment_end_index {
8970 return shaped_line.font_id_for_index(index - fragment_start_index);
8971 }
8972 fragment_start_index = fragment_end_index;
8973 }
8974 LineFragment::Element { len, .. } => {
8975 let fragment_end_index = fragment_start_index + len;
8976 if index < fragment_end_index {
8977 return None;
8978 }
8979 fragment_start_index = fragment_end_index;
8980 }
8981 }
8982 }
8983
8984 None
8985 }
8986
8987 pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
8988 let line_width = self.width;
8989 match text_align {
8990 TextAlign::Left => px(0.0),
8991 TextAlign::Center => (content_width - line_width) / 2.0,
8992 TextAlign::Right => content_width - line_width,
8993 }
8994 }
8995}
8996
8997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8998enum Invisible {
8999 /// A tab character
9000 ///
9001 /// A tab character is internally represented by spaces (configured by the user's tab width)
9002 /// aligned to the nearest column, so it's necessary to store the start and end offset for
9003 /// adjacency checks.
9004 Tab {
9005 line_start_offset: usize,
9006 line_end_offset: usize,
9007 },
9008 Whitespace {
9009 line_offset: usize,
9010 },
9011}
9012
9013impl EditorElement {
9014 /// Returns the rem size to use when rendering the [`EditorElement`].
9015 ///
9016 /// This allows UI elements to scale based on the `buffer_font_size`.
9017 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
9018 match self.editor.read(cx).mode {
9019 EditorMode::Full {
9020 scale_ui_elements_with_buffer_font_size: true,
9021 ..
9022 }
9023 | EditorMode::Minimap { .. } => {
9024 let buffer_font_size = self.style.text.font_size;
9025 match buffer_font_size {
9026 AbsoluteLength::Pixels(pixels) => {
9027 let rem_size_scale = {
9028 // Our default UI font size is 14px on a 16px base scale.
9029 // This means the default UI font size is 0.875rems.
9030 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
9031
9032 // We then determine the delta between a single rem and the default font
9033 // size scale.
9034 let default_font_size_delta = 1. - default_font_size_scale;
9035
9036 // Finally, we add this delta to 1rem to get the scale factor that
9037 // should be used to scale up the UI.
9038 1. + default_font_size_delta
9039 };
9040
9041 Some(pixels * rem_size_scale)
9042 }
9043 AbsoluteLength::Rems(rems) => {
9044 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
9045 }
9046 }
9047 }
9048 // We currently use single-line and auto-height editors in UI contexts,
9049 // so we don't want to scale everything with the buffer font size, as it
9050 // ends up looking off.
9051 _ => None,
9052 }
9053 }
9054
9055 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
9056 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
9057 parent.upgrade()
9058 } else {
9059 Some(self.editor.clone())
9060 }
9061 }
9062}
9063
9064#[derive(Default)]
9065pub struct EditorRequestLayoutState {
9066 // We use prepaint depth to limit the number of times prepaint is
9067 // called recursively. We need this so that we can update stale
9068 // data for e.g. block heights in block map.
9069 prepaint_depth: Rc<Cell<usize>>,
9070}
9071
9072impl EditorRequestLayoutState {
9073 // In ideal conditions we only need one more subsequent prepaint call for resize to take effect.
9074 // i.e. MAX_PREPAINT_DEPTH = 2, but since moving blocks inline (place_near), more lines from
9075 // below get exposed, and we end up querying blocks for those lines too in subsequent renders.
9076 // Setting MAX_PREPAINT_DEPTH = 3, passes all tests. Just to be on the safe side we set it to 5, so
9077 // that subsequent shrinking does not lead to incorrect block placing.
9078 const MAX_PREPAINT_DEPTH: usize = 5;
9079
9080 fn increment_prepaint_depth(&self) -> EditorPrepaintGuard {
9081 let depth = self.prepaint_depth.get();
9082 self.prepaint_depth.set(depth + 1);
9083 EditorPrepaintGuard {
9084 prepaint_depth: self.prepaint_depth.clone(),
9085 }
9086 }
9087
9088 fn can_prepaint(&self) -> bool {
9089 self.prepaint_depth.get() < Self::MAX_PREPAINT_DEPTH
9090 }
9091}
9092
9093struct EditorPrepaintGuard {
9094 prepaint_depth: Rc<Cell<usize>>,
9095}
9096
9097impl Drop for EditorPrepaintGuard {
9098 fn drop(&mut self) {
9099 let depth = self.prepaint_depth.get();
9100 self.prepaint_depth.set(depth.saturating_sub(1));
9101 }
9102}
9103
9104impl Element for EditorElement {
9105 type RequestLayoutState = EditorRequestLayoutState;
9106 type PrepaintState = EditorLayout;
9107
9108 fn id(&self) -> Option<ElementId> {
9109 None
9110 }
9111
9112 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
9113 None
9114 }
9115
9116 fn request_layout(
9117 &mut self,
9118 _: Option<&GlobalElementId>,
9119 _inspector_id: Option<&gpui::InspectorElementId>,
9120 window: &mut Window,
9121 cx: &mut App,
9122 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
9123 let rem_size = self.rem_size(cx);
9124 window.with_rem_size(rem_size, |window| {
9125 self.editor.update(cx, |editor, cx| {
9126 editor.set_style(self.style.clone(), window, cx);
9127
9128 let layout_id = match editor.mode {
9129 EditorMode::SingleLine => {
9130 let rem_size = window.rem_size();
9131 let height = self.style.text.line_height_in_pixels(rem_size);
9132 let mut style = Style::default();
9133 style.size.height = height.into();
9134 style.size.width = relative(1.).into();
9135 window.request_layout(style, None, cx)
9136 }
9137 EditorMode::AutoHeight {
9138 min_lines,
9139 max_lines,
9140 } => {
9141 let editor_handle = cx.entity();
9142 window.request_measured_layout(
9143 Style::default(),
9144 move |known_dimensions, available_space, window, cx| {
9145 editor_handle
9146 .update(cx, |editor, cx| {
9147 compute_auto_height_layout(
9148 editor,
9149 min_lines,
9150 max_lines,
9151 known_dimensions,
9152 available_space.width,
9153 window,
9154 cx,
9155 )
9156 })
9157 .unwrap_or_default()
9158 },
9159 )
9160 }
9161 EditorMode::Minimap { .. } => {
9162 let mut style = Style::default();
9163 style.size.width = relative(1.).into();
9164 style.size.height = relative(1.).into();
9165 window.request_layout(style, None, cx)
9166 }
9167 EditorMode::Full {
9168 sizing_behavior, ..
9169 } => {
9170 let mut style = Style::default();
9171 style.size.width = relative(1.).into();
9172 if sizing_behavior == SizingBehavior::SizeByContent {
9173 let snapshot = editor.snapshot(window, cx);
9174 let line_height =
9175 self.style.text.line_height_in_pixels(window.rem_size());
9176 let scroll_height =
9177 (snapshot.max_point().row().next_row().0 as f32) * line_height;
9178 style.size.height = scroll_height.into();
9179 } else {
9180 style.size.height = relative(1.).into();
9181 }
9182 window.request_layout(style, None, cx)
9183 }
9184 };
9185
9186 (layout_id, EditorRequestLayoutState::default())
9187 })
9188 })
9189 }
9190
9191 fn prepaint(
9192 &mut self,
9193 _: Option<&GlobalElementId>,
9194 _inspector_id: Option<&gpui::InspectorElementId>,
9195 bounds: Bounds<Pixels>,
9196 request_layout: &mut Self::RequestLayoutState,
9197 window: &mut Window,
9198 cx: &mut App,
9199 ) -> Self::PrepaintState {
9200 let _prepaint_depth_guard = request_layout.increment_prepaint_depth();
9201 let text_style = TextStyleRefinement {
9202 font_size: Some(self.style.text.font_size),
9203 line_height: Some(self.style.text.line_height),
9204 ..Default::default()
9205 };
9206
9207 let is_minimap = self.editor.read(cx).mode.is_minimap();
9208 let is_singleton = self.editor.read(cx).buffer_kind(cx) == ItemBufferKind::Singleton;
9209
9210 if !is_minimap {
9211 let focus_handle = self.editor.focus_handle(cx);
9212 window.set_view_id(self.editor.entity_id());
9213 window.set_focus_handle(&focus_handle, cx);
9214 }
9215
9216 let rem_size = self.rem_size(cx);
9217 window.with_rem_size(rem_size, |window| {
9218 window.with_text_style(Some(text_style), |window| {
9219 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9220 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
9221 (editor.snapshot(window, cx), editor.read_only(cx))
9222 });
9223 let style = &self.style;
9224
9225 let rem_size = window.rem_size();
9226 let font_id = window.text_system().resolve_font(&style.text.font());
9227 let font_size = style.text.font_size.to_pixels(rem_size);
9228 let line_height = style.text.line_height_in_pixels(rem_size);
9229 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
9230 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
9231 let glyph_grid_cell = size(em_advance, line_height);
9232
9233 let gutter_dimensions = snapshot
9234 .gutter_dimensions(
9235 font_id,
9236 font_size,
9237 style,
9238 window,
9239 cx,
9240 );
9241 let text_width = bounds.size.width - gutter_dimensions.width;
9242
9243 let settings = EditorSettings::get_global(cx);
9244 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
9245 let vertical_scrollbar_width = (scrollbars_shown
9246 && settings.scrollbar.axes.vertical
9247 && self.editor.read(cx).show_scrollbars.vertical)
9248 .then_some(style.scrollbar_width)
9249 .unwrap_or_default();
9250 let minimap_width = self
9251 .get_minimap_width(
9252 &settings.minimap,
9253 scrollbars_shown,
9254 text_width,
9255 em_width,
9256 font_size,
9257 rem_size,
9258 cx,
9259 )
9260 .unwrap_or_default();
9261
9262 let right_margin = minimap_width + vertical_scrollbar_width;
9263
9264 let editor_width =
9265 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
9266 let editor_margins = EditorMargins {
9267 gutter: gutter_dimensions,
9268 right: right_margin,
9269 };
9270
9271 snapshot = self.editor.update(cx, |editor, cx| {
9272 editor.last_bounds = Some(bounds);
9273 editor.gutter_dimensions = gutter_dimensions;
9274 editor.set_visible_line_count(
9275 (bounds.size.height / line_height) as f64,
9276 window,
9277 cx,
9278 );
9279 editor.set_visible_column_count(f64::from(editor_width / em_advance));
9280
9281 if matches!(
9282 editor.mode,
9283 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
9284 ) {
9285 snapshot
9286 } else {
9287 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
9288 let wrap_width = match editor.soft_wrap_mode(cx) {
9289 SoftWrap::GitDiff => None,
9290 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
9291 SoftWrap::EditorWidth => Some(editor_width),
9292 SoftWrap::Column(column) => Some(wrap_width_for(column)),
9293 SoftWrap::Bounded(column) => {
9294 Some(editor_width.min(wrap_width_for(column)))
9295 }
9296 };
9297
9298 if editor.set_wrap_width(wrap_width, cx) {
9299 editor.snapshot(window, cx)
9300 } else {
9301 snapshot
9302 }
9303 }
9304 });
9305
9306 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
9307 let gutter_hitbox = window.insert_hitbox(
9308 gutter_bounds(bounds, gutter_dimensions),
9309 HitboxBehavior::Normal,
9310 );
9311 let text_hitbox = window.insert_hitbox(
9312 Bounds {
9313 origin: gutter_hitbox.top_right(),
9314 size: size(text_width, bounds.size.height),
9315 },
9316 HitboxBehavior::Normal,
9317 );
9318
9319 // Offset the content_bounds from the text_bounds by the gutter margin (which
9320 // is roughly half a character wide) to make hit testing work more like how we want.
9321 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
9322 let content_origin = text_hitbox.origin + content_offset;
9323
9324 let height_in_lines = f64::from(bounds.size.height / line_height);
9325 let max_row = snapshot.max_point().row().as_f64();
9326
9327 // Calculate how much of the editor is clipped by parent containers (e.g., List).
9328 // This allows us to only render lines that are actually visible, which is
9329 // critical for performance when large AutoHeight editors are inside Lists.
9330 let visible_bounds = window.content_mask().bounds;
9331 let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
9332 let clipped_top_in_lines = f64::from(clipped_top / line_height);
9333 let visible_height_in_lines =
9334 f64::from(visible_bounds.size.height / line_height);
9335
9336 // The max scroll position for the top of the window
9337 let max_scroll_top = if matches!(
9338 snapshot.mode,
9339 EditorMode::SingleLine
9340 | EditorMode::AutoHeight { .. }
9341 | EditorMode::Full {
9342 sizing_behavior: SizingBehavior::ExcludeOverscrollMargin
9343 | SizingBehavior::SizeByContent,
9344 ..
9345 }
9346 ) {
9347 (max_row - height_in_lines + 1.).max(0.)
9348 } else {
9349 let settings = EditorSettings::get_global(cx);
9350 match settings.scroll_beyond_last_line {
9351 ScrollBeyondLastLine::OnePage => max_row,
9352 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
9353 ScrollBeyondLastLine::VerticalScrollMargin => {
9354 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
9355 .max(0.)
9356 }
9357 }
9358 };
9359
9360 let (
9361 autoscroll_request,
9362 autoscroll_containing_element,
9363 needs_horizontal_autoscroll,
9364 ) = self.editor.update(cx, |editor, cx| {
9365 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
9366
9367 let autoscroll_containing_element =
9368 autoscroll_request.is_some() || editor.has_pending_selection();
9369
9370 let (needs_horizontal_autoscroll, was_scrolled) = editor
9371 .autoscroll_vertically(
9372 bounds,
9373 line_height,
9374 max_scroll_top,
9375 autoscroll_request,
9376 window,
9377 cx,
9378 );
9379 if was_scrolled.0 {
9380 snapshot = editor.snapshot(window, cx);
9381 }
9382 (
9383 autoscroll_request,
9384 autoscroll_containing_element,
9385 needs_horizontal_autoscroll,
9386 )
9387 });
9388
9389 let mut scroll_position = snapshot.scroll_position();
9390 // The scroll position is a fractional point, the whole number of which represents
9391 // the top of the window in terms of display rows.
9392 // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
9393 // but we don't modify scroll_position itself since the parent handles positioning.
9394 let max_row = snapshot.max_point().row();
9395 let start_row = cmp::min(
9396 DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
9397 max_row,
9398 );
9399 let end_row = cmp::min(
9400 (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
9401 as u32,
9402 max_row.next_row().0,
9403 );
9404 let end_row = DisplayRow(end_row);
9405
9406 let row_infos = snapshot // note we only get the visual range
9407 .row_infos(start_row)
9408 .take((start_row..end_row).len())
9409 .collect::<Vec<RowInfo>>();
9410 let is_row_soft_wrapped = |row: usize| {
9411 row_infos
9412 .get(row)
9413 .is_none_or(|info| info.buffer_row.is_none())
9414 };
9415
9416 let start_anchor = if start_row == Default::default() {
9417 Anchor::min()
9418 } else {
9419 snapshot.buffer_snapshot().anchor_before(
9420 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
9421 )
9422 };
9423 let end_anchor = if end_row > max_row {
9424 Anchor::max()
9425 } else {
9426 snapshot.buffer_snapshot().anchor_before(
9427 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
9428 )
9429 };
9430
9431 let mut highlighted_rows = self
9432 .editor
9433 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
9434
9435 let is_light = cx.theme().appearance().is_light();
9436
9437 let mut highlighted_ranges = self
9438 .editor_with_selections(cx)
9439 .map(|editor| {
9440 editor.read(cx).background_highlights_in_range(
9441 start_anchor..end_anchor,
9442 &snapshot.display_snapshot,
9443 cx.theme(),
9444 )
9445 })
9446 .unwrap_or_default();
9447
9448 for (ix, row_info) in row_infos.iter().enumerate() {
9449 let Some(diff_status) = row_info.diff_status else {
9450 continue;
9451 };
9452
9453 let background_color = match diff_status.kind {
9454 DiffHunkStatusKind::Added =>
9455 cx.theme().colors().version_control_added,
9456 DiffHunkStatusKind::Deleted =>
9457 cx.theme().colors().version_control_deleted,
9458 DiffHunkStatusKind::Modified => {
9459 debug_panic!("modified diff status for row info");
9460 continue;
9461 }
9462 };
9463
9464 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
9465
9466 let hollow_highlight = LineHighlight {
9467 background: (background_color.opacity(if is_light {
9468 0.08
9469 } else {
9470 0.06
9471 }))
9472 .into(),
9473 border: Some(if is_light {
9474 background_color.opacity(0.48)
9475 } else {
9476 background_color.opacity(0.36)
9477 }),
9478 include_gutter: true,
9479 type_id: None,
9480 };
9481
9482 let filled_highlight = LineHighlight {
9483 background: solid_background(background_color.opacity(hunk_opacity)),
9484 border: None,
9485 include_gutter: true,
9486 type_id: None,
9487 };
9488
9489 let background = if Self::diff_hunk_hollow(diff_status, cx) {
9490 hollow_highlight
9491 } else {
9492 filled_highlight
9493 };
9494
9495 let base_display_point =
9496 DisplayPoint::new(start_row + DisplayRow(ix as u32), 0);
9497
9498 highlighted_rows
9499 .entry(base_display_point.row())
9500 .or_insert(background);
9501 }
9502
9503 let highlighted_gutter_ranges =
9504 self.editor.read(cx).gutter_highlights_in_range(
9505 start_anchor..end_anchor,
9506 &snapshot.display_snapshot,
9507 cx,
9508 );
9509
9510 let document_colors = self
9511 .editor
9512 .read(cx)
9513 .colors
9514 .as_ref()
9515 .map(|colors| colors.editor_display_highlights(&snapshot));
9516 let redacted_ranges = self.editor.read(cx).redacted_ranges(
9517 start_anchor..end_anchor,
9518 &snapshot.display_snapshot,
9519 cx,
9520 );
9521
9522 let (local_selections, selected_buffer_ids, latest_selection_anchors): (
9523 Vec<Selection<Point>>,
9524 Vec<BufferId>,
9525 HashMap<BufferId, Anchor>,
9526 ) = self
9527 .editor_with_selections(cx)
9528 .map(|editor| {
9529 editor.update(cx, |editor, cx| {
9530 let all_selections =
9531 editor.selections.all::<Point>(&snapshot.display_snapshot);
9532 let all_anchor_selections =
9533 editor.selections.all_anchors(&snapshot.display_snapshot);
9534 let selected_buffer_ids =
9535 if editor.buffer_kind(cx) == ItemBufferKind::Singleton {
9536 Vec::new()
9537 } else {
9538 let mut selected_buffer_ids =
9539 Vec::with_capacity(all_selections.len());
9540
9541 for selection in all_selections {
9542 for buffer_id in snapshot
9543 .buffer_snapshot()
9544 .buffer_ids_for_range(selection.range())
9545 {
9546 if selected_buffer_ids.last() != Some(&buffer_id) {
9547 selected_buffer_ids.push(buffer_id);
9548 }
9549 }
9550 }
9551
9552 selected_buffer_ids
9553 };
9554
9555 let mut selections = editor.selections.disjoint_in_range(
9556 start_anchor..end_anchor,
9557 &snapshot.display_snapshot,
9558 );
9559 selections
9560 .extend(editor.selections.pending(&snapshot.display_snapshot));
9561
9562 let mut anchors_by_buffer: HashMap<BufferId, (usize, Anchor)> =
9563 HashMap::default();
9564 for selection in all_anchor_selections.iter() {
9565 let head = selection.head();
9566 if let Some(buffer_id) = head.text_anchor.buffer_id {
9567 anchors_by_buffer
9568 .entry(buffer_id)
9569 .and_modify(|(latest_id, latest_anchor)| {
9570 if selection.id > *latest_id {
9571 *latest_id = selection.id;
9572 *latest_anchor = head;
9573 }
9574 })
9575 .or_insert((selection.id, head));
9576 }
9577 }
9578 let latest_selection_anchors = anchors_by_buffer
9579 .into_iter()
9580 .map(|(buffer_id, (_, anchor))| (buffer_id, anchor))
9581 .collect();
9582
9583 (selections, selected_buffer_ids, latest_selection_anchors)
9584 })
9585 })
9586 .unwrap_or_else(|| (Vec::new(), Vec::new(), HashMap::default()));
9587
9588 let (selections, mut active_rows, newest_selection_head) = self
9589 .layout_selections(
9590 start_anchor,
9591 end_anchor,
9592 &local_selections,
9593 &snapshot,
9594 start_row,
9595 end_row,
9596 window,
9597 cx,
9598 );
9599
9600 // relative rows are based on newest selection, even outside the visible area
9601 let relative_row_base = self.editor.update(cx, |editor, cx| {
9602 if editor.selections.count()==0 {
9603 return None;
9604 }
9605 let newest = editor
9606 .selections
9607 .newest::<Point>(&editor.display_snapshot(cx));
9608 Some(SelectionLayout::new(
9609 newest,
9610 editor.selections.line_mode(),
9611 editor.cursor_offset_on_selection,
9612 editor.cursor_shape,
9613 &snapshot.display_snapshot,
9614 true,
9615 true,
9616 None,
9617 )
9618 .head.row())
9619 });
9620
9621 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
9622 editor.active_breakpoints(start_row..end_row, window, cx)
9623 });
9624 for (display_row, (_, bp, state)) in &breakpoint_rows {
9625 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
9626 active_rows.entry(*display_row).or_default().breakpoint = true;
9627 }
9628 }
9629
9630 let line_numbers = self.layout_line_numbers(
9631 Some(&gutter_hitbox),
9632 gutter_dimensions,
9633 line_height,
9634 scroll_position,
9635 start_row..end_row,
9636 &row_infos,
9637 &active_rows,
9638 relative_row_base,
9639 &snapshot,
9640 window,
9641 cx,
9642 );
9643
9644 // We add the gutter breakpoint indicator to breakpoint_rows after painting
9645 // line numbers so we don't paint a line number debug accent color if a user
9646 // has their mouse over that line when a breakpoint isn't there
9647 self.editor.update(cx, |editor, _| {
9648 if let Some(phantom_breakpoint) = &mut editor
9649 .gutter_breakpoint_indicator
9650 .0
9651 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
9652 {
9653 // Is there a non-phantom breakpoint on this line?
9654 phantom_breakpoint.collides_with_existing_breakpoint = true;
9655 breakpoint_rows
9656 .entry(phantom_breakpoint.display_row)
9657 .or_insert_with(|| {
9658 let position = snapshot.display_point_to_anchor(
9659 DisplayPoint::new(phantom_breakpoint.display_row, 0),
9660 Bias::Right,
9661 );
9662 let breakpoint = Breakpoint::new_standard();
9663 phantom_breakpoint.collides_with_existing_breakpoint = false;
9664 (position, breakpoint, None)
9665 });
9666 }
9667 });
9668
9669 let mut expand_toggles =
9670 window.with_element_namespace("expand_toggles", |window| {
9671 self.layout_expand_toggles(
9672 &gutter_hitbox,
9673 gutter_dimensions,
9674 em_width,
9675 line_height,
9676 scroll_position,
9677 &row_infos,
9678 window,
9679 cx,
9680 )
9681 });
9682
9683 let mut crease_toggles =
9684 window.with_element_namespace("crease_toggles", |window| {
9685 self.layout_crease_toggles(
9686 start_row..end_row,
9687 &row_infos,
9688 &active_rows,
9689 &snapshot,
9690 window,
9691 cx,
9692 )
9693 });
9694 let crease_trailers =
9695 window.with_element_namespace("crease_trailers", |window| {
9696 self.layout_crease_trailers(
9697 row_infos.iter().cloned(),
9698 &snapshot,
9699 window,
9700 cx,
9701 )
9702 });
9703
9704 let display_hunks = self.layout_gutter_diff_hunks(
9705 line_height,
9706 &gutter_hitbox,
9707 start_row..end_row,
9708 &snapshot,
9709 window,
9710 cx,
9711 );
9712
9713 Self::layout_word_diff_highlights(
9714 &display_hunks,
9715 &row_infos,
9716 start_row,
9717 &snapshot,
9718 &mut highlighted_ranges,
9719 cx,
9720 );
9721
9722 let merged_highlighted_ranges =
9723 if let Some((_, colors)) = document_colors.as_ref() {
9724 &highlighted_ranges
9725 .clone()
9726 .into_iter()
9727 .chain(colors.clone())
9728 .collect()
9729 } else {
9730 &highlighted_ranges
9731 };
9732 let bg_segments_per_row = Self::bg_segments_per_row(
9733 start_row..end_row,
9734 &selections,
9735 &merged_highlighted_ranges,
9736 self.style.background,
9737 );
9738
9739 let mut line_layouts = Self::layout_lines(
9740 start_row..end_row,
9741 &snapshot,
9742 &self.style,
9743 editor_width,
9744 is_row_soft_wrapped,
9745 &bg_segments_per_row,
9746 window,
9747 cx,
9748 );
9749 let new_renderer_widths = (!is_minimap).then(|| {
9750 line_layouts
9751 .iter()
9752 .flat_map(|layout| &layout.fragments)
9753 .filter_map(|fragment| {
9754 if let LineFragment::Element { id, size, .. } = fragment {
9755 Some((*id, size.width))
9756 } else {
9757 None
9758 }
9759 })
9760 });
9761 if new_renderer_widths.is_some_and(|new_renderer_widths| {
9762 self.editor.update(cx, |editor, cx| {
9763 editor.update_renderer_widths(new_renderer_widths, cx)
9764 })
9765 }) {
9766 // If the fold widths have changed, we need to prepaint
9767 // the element again to account for any changes in
9768 // wrapping.
9769 if request_layout.can_prepaint() {
9770 return self.prepaint(
9771 None,
9772 _inspector_id,
9773 bounds,
9774 request_layout,
9775 window,
9776 cx,
9777 );
9778 } else {
9779 debug_panic!(
9780 "skipping recursive prepaint at max depth. renderer widths may be stale."
9781 );
9782 }
9783 }
9784
9785 let longest_line_blame_width = self
9786 .editor
9787 .update(cx, |editor, cx| {
9788 if !editor.show_git_blame_inline {
9789 return None;
9790 }
9791 let blame = editor.blame.as_ref()?;
9792 let (_, blame_entry) = blame
9793 .update(cx, |blame, cx| {
9794 let row_infos =
9795 snapshot.row_infos(snapshot.longest_row()).next()?;
9796 blame.blame_for_rows(&[row_infos], cx).next()
9797 })
9798 .flatten()?;
9799 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
9800 let inline_blame_padding =
9801 ProjectSettings::get_global(cx).git.inline_blame.padding as f32
9802 * em_advance;
9803 Some(
9804 element
9805 .layout_as_root(AvailableSpace::min_size(), window, cx)
9806 .width
9807 + inline_blame_padding,
9808 )
9809 })
9810 .unwrap_or(Pixels::ZERO);
9811
9812 let longest_line_width = layout_line(
9813 snapshot.longest_row(),
9814 &snapshot,
9815 style,
9816 editor_width,
9817 is_row_soft_wrapped,
9818 window,
9819 cx,
9820 )
9821 .width;
9822
9823 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
9824 text_hitbox.bounds,
9825 glyph_grid_cell,
9826 size(
9827 longest_line_width,
9828 Pixels::from(max_row.as_f64() * f64::from(line_height)),
9829 ),
9830 longest_line_blame_width,
9831 EditorSettings::get_global(cx),
9832 );
9833
9834 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
9835
9836 let sticky_header_excerpt = if snapshot.buffer_snapshot().show_headers() {
9837 snapshot.sticky_header_excerpt(scroll_position.y)
9838 } else {
9839 None
9840 };
9841 let sticky_header_excerpt_id =
9842 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
9843
9844 let blocks = (!is_minimap)
9845 .then(|| {
9846 window.with_element_namespace("blocks", |window| {
9847 self.render_blocks(
9848 start_row..end_row,
9849 &snapshot,
9850 &hitbox,
9851 &text_hitbox,
9852 editor_width,
9853 &mut scroll_width,
9854 &editor_margins,
9855 em_width,
9856 gutter_dimensions.full_width(),
9857 line_height,
9858 &mut line_layouts,
9859 &local_selections,
9860 &selected_buffer_ids,
9861 &latest_selection_anchors,
9862 is_row_soft_wrapped,
9863 sticky_header_excerpt_id,
9864 window,
9865 cx,
9866 )
9867 })
9868 })
9869 .unwrap_or_default();
9870 let RenderBlocksOutput {
9871 mut blocks,
9872 row_block_types,
9873 resized_blocks,
9874 } = blocks;
9875 if let Some(resized_blocks) = resized_blocks {
9876 self.editor.update(cx, |editor, cx| {
9877 editor.resize_blocks(
9878 resized_blocks,
9879 autoscroll_request.map(|(autoscroll, _)| autoscroll),
9880 cx,
9881 )
9882 });
9883 if request_layout.can_prepaint() {
9884 return self.prepaint(
9885 None,
9886 _inspector_id,
9887 bounds,
9888 request_layout,
9889 window,
9890 cx,
9891 );
9892 } else {
9893 debug_panic!(
9894 "skipping recursive prepaint at max depth. block layout may be stale."
9895 );
9896 }
9897 }
9898
9899 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
9900 window.with_element_namespace("blocks", |window| {
9901 self.layout_sticky_buffer_header(
9902 sticky_header_excerpt,
9903 scroll_position,
9904 line_height,
9905 right_margin,
9906 &snapshot,
9907 &hitbox,
9908 &selected_buffer_ids,
9909 &blocks,
9910 &latest_selection_anchors,
9911 window,
9912 cx,
9913 )
9914 })
9915 });
9916
9917 let start_buffer_row =
9918 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot()).row);
9919 let end_buffer_row =
9920 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot()).row);
9921
9922 let scroll_max: gpui::Point<ScrollPixelOffset> = point(
9923 ScrollPixelOffset::from(
9924 ((scroll_width - editor_width) / em_advance).max(0.0),
9925 ),
9926 max_scroll_top,
9927 );
9928
9929 self.editor.update(cx, |editor, cx| {
9930 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
9931 scroll_position.x = scroll_position.x.min(scroll_max.x);
9932 }
9933
9934 if needs_horizontal_autoscroll.0
9935 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
9936 start_row,
9937 editor_width,
9938 scroll_width,
9939 em_advance,
9940 &line_layouts,
9941 autoscroll_request,
9942 window,
9943 cx,
9944 )
9945 {
9946 scroll_position = new_scroll_position;
9947 }
9948 });
9949
9950 let scroll_pixel_position = point(
9951 scroll_position.x * f64::from(em_advance),
9952 scroll_position.y * f64::from(line_height),
9953 );
9954 let sticky_headers = if !is_minimap
9955 && is_singleton
9956 && EditorSettings::get_global(cx).sticky_scroll.enabled
9957 {
9958 let relative = self.editor.read(cx).relative_line_numbers(cx);
9959 self.layout_sticky_headers(
9960 &snapshot,
9961 editor_width,
9962 is_row_soft_wrapped,
9963 line_height,
9964 scroll_pixel_position,
9965 content_origin,
9966 &gutter_dimensions,
9967 &gutter_hitbox,
9968 &text_hitbox,
9969 &style,
9970 relative,
9971 relative_row_base,
9972 window,
9973 cx,
9974 )
9975 } else {
9976 None
9977 };
9978 let indent_guides = self.layout_indent_guides(
9979 content_origin,
9980 text_hitbox.origin,
9981 start_buffer_row..end_buffer_row,
9982 scroll_pixel_position,
9983 line_height,
9984 &snapshot,
9985 window,
9986 cx,
9987 );
9988
9989 let crease_trailers =
9990 window.with_element_namespace("crease_trailers", |window| {
9991 self.prepaint_crease_trailers(
9992 crease_trailers,
9993 &line_layouts,
9994 line_height,
9995 content_origin,
9996 scroll_pixel_position,
9997 em_width,
9998 window,
9999 cx,
10000 )
10001 });
10002
10003 let (edit_prediction_popover, edit_prediction_popover_origin) = self
10004 .editor
10005 .update(cx, |editor, cx| {
10006 editor.render_edit_prediction_popover(
10007 &text_hitbox.bounds,
10008 content_origin,
10009 right_margin,
10010 &snapshot,
10011 start_row..end_row,
10012 scroll_position.y,
10013 scroll_position.y + height_in_lines,
10014 &line_layouts,
10015 line_height,
10016 scroll_position,
10017 scroll_pixel_position,
10018 newest_selection_head,
10019 editor_width,
10020 style,
10021 window,
10022 cx,
10023 )
10024 })
10025 .unzip();
10026
10027 let mut inline_diagnostics = self.layout_inline_diagnostics(
10028 &line_layouts,
10029 &crease_trailers,
10030 &row_block_types,
10031 content_origin,
10032 scroll_position,
10033 scroll_pixel_position,
10034 edit_prediction_popover_origin,
10035 start_row,
10036 end_row,
10037 line_height,
10038 em_width,
10039 style,
10040 window,
10041 cx,
10042 );
10043
10044 let mut inline_blame_layout = None;
10045 let mut inline_code_actions = None;
10046 if let Some(newest_selection_head) = newest_selection_head {
10047 let display_row = newest_selection_head.row();
10048 if (start_row..end_row).contains(&display_row)
10049 && !row_block_types.contains_key(&display_row)
10050 {
10051 inline_code_actions = self.layout_inline_code_actions(
10052 newest_selection_head,
10053 content_origin,
10054 scroll_position,
10055 scroll_pixel_position,
10056 line_height,
10057 &snapshot,
10058 window,
10059 cx,
10060 );
10061
10062 let line_ix = display_row.minus(start_row) as usize;
10063 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
10064 row_infos.get(line_ix),
10065 line_layouts.get(line_ix),
10066 crease_trailers.get(line_ix),
10067 ) {
10068 let crease_trailer_layout = crease_trailer.as_ref();
10069 if let Some(layout) = self.layout_inline_blame(
10070 display_row,
10071 row_info,
10072 line_layout,
10073 crease_trailer_layout,
10074 em_width,
10075 content_origin,
10076 scroll_position,
10077 scroll_pixel_position,
10078 line_height,
10079 window,
10080 cx,
10081 ) {
10082 inline_blame_layout = Some(layout);
10083 // Blame overrides inline diagnostics
10084 inline_diagnostics.remove(&display_row);
10085 }
10086 } else {
10087 log::error!(
10088 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
10089 line_layouts.len(): {}, \
10090 crease_trailers.len(): {}",
10091 line_ix,
10092 row_infos.len(),
10093 line_layouts.len(),
10094 crease_trailers.len(),
10095 );
10096 }
10097 }
10098 }
10099
10100 let blamed_display_rows = self.layout_blame_entries(
10101 &row_infos,
10102 em_width,
10103 scroll_position,
10104 line_height,
10105 &gutter_hitbox,
10106 gutter_dimensions.git_blame_entries_width,
10107 window,
10108 cx,
10109 );
10110
10111 let line_elements = self.prepaint_lines(
10112 start_row,
10113 &mut line_layouts,
10114 line_height,
10115 scroll_position,
10116 scroll_pixel_position,
10117 content_origin,
10118 window,
10119 cx,
10120 );
10121
10122 window.with_element_namespace("blocks", |window| {
10123 self.layout_blocks(
10124 &mut blocks,
10125 &hitbox,
10126 line_height,
10127 scroll_position,
10128 scroll_pixel_position,
10129 window,
10130 cx,
10131 );
10132 });
10133
10134 let cursors = self.collect_cursors(&snapshot, cx);
10135 let visible_row_range = start_row..end_row;
10136 let non_visible_cursors = cursors
10137 .iter()
10138 .any(|c| !visible_row_range.contains(&c.0.row()));
10139
10140 let visible_cursors = self.layout_visible_cursors(
10141 &snapshot,
10142 &selections,
10143 &row_block_types,
10144 start_row..end_row,
10145 &line_layouts,
10146 &text_hitbox,
10147 content_origin,
10148 scroll_position,
10149 scroll_pixel_position,
10150 line_height,
10151 em_width,
10152 em_advance,
10153 autoscroll_containing_element,
10154 window,
10155 cx,
10156 );
10157
10158 let scrollbars_layout = self.layout_scrollbars(
10159 &snapshot,
10160 &scrollbar_layout_information,
10161 content_offset,
10162 scroll_position,
10163 non_visible_cursors,
10164 right_margin,
10165 editor_width,
10166 window,
10167 cx,
10168 );
10169
10170 let gutter_settings = EditorSettings::get_global(cx).gutter;
10171
10172 let context_menu_layout =
10173 if let Some(newest_selection_head) = newest_selection_head {
10174 let newest_selection_point =
10175 newest_selection_head.to_point(&snapshot.display_snapshot);
10176 if (start_row..end_row).contains(&newest_selection_head.row()) {
10177 self.layout_cursor_popovers(
10178 line_height,
10179 &text_hitbox,
10180 content_origin,
10181 right_margin,
10182 start_row,
10183 scroll_pixel_position,
10184 &line_layouts,
10185 newest_selection_head,
10186 newest_selection_point,
10187 style,
10188 window,
10189 cx,
10190 )
10191 } else {
10192 None
10193 }
10194 } else {
10195 None
10196 };
10197
10198 self.layout_gutter_menu(
10199 line_height,
10200 &text_hitbox,
10201 content_origin,
10202 right_margin,
10203 scroll_pixel_position,
10204 gutter_dimensions.width - gutter_dimensions.left_padding,
10205 window,
10206 cx,
10207 );
10208
10209 let test_indicators = if gutter_settings.runnables {
10210 self.layout_run_indicators(
10211 line_height,
10212 start_row..end_row,
10213 &row_infos,
10214 scroll_position,
10215 &gutter_dimensions,
10216 &gutter_hitbox,
10217 &display_hunks,
10218 &snapshot,
10219 &mut breakpoint_rows,
10220 window,
10221 cx,
10222 )
10223 } else {
10224 Vec::new()
10225 };
10226
10227 let show_breakpoints = snapshot
10228 .show_breakpoints
10229 .unwrap_or(gutter_settings.breakpoints);
10230 let breakpoints = if show_breakpoints {
10231 self.layout_breakpoints(
10232 line_height,
10233 start_row..end_row,
10234 scroll_position,
10235 &gutter_dimensions,
10236 &gutter_hitbox,
10237 &display_hunks,
10238 &snapshot,
10239 breakpoint_rows,
10240 &row_infos,
10241 window,
10242 cx,
10243 )
10244 } else {
10245 Vec::new()
10246 };
10247
10248 self.layout_signature_help(
10249 &hitbox,
10250 content_origin,
10251 scroll_pixel_position,
10252 newest_selection_head,
10253 start_row,
10254 &line_layouts,
10255 line_height,
10256 em_width,
10257 context_menu_layout,
10258 window,
10259 cx,
10260 );
10261
10262 if !cx.has_active_drag() {
10263 self.layout_hover_popovers(
10264 &snapshot,
10265 &hitbox,
10266 start_row..end_row,
10267 content_origin,
10268 scroll_pixel_position,
10269 &line_layouts,
10270 line_height,
10271 em_width,
10272 context_menu_layout,
10273 window,
10274 cx,
10275 );
10276
10277 self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
10278 }
10279
10280 let mouse_context_menu = self.layout_mouse_context_menu(
10281 &snapshot,
10282 start_row..end_row,
10283 content_origin,
10284 window,
10285 cx,
10286 );
10287
10288 window.with_element_namespace("crease_toggles", |window| {
10289 self.prepaint_crease_toggles(
10290 &mut crease_toggles,
10291 line_height,
10292 &gutter_dimensions,
10293 gutter_settings,
10294 scroll_pixel_position,
10295 &gutter_hitbox,
10296 window,
10297 cx,
10298 )
10299 });
10300
10301 window.with_element_namespace("expand_toggles", |window| {
10302 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
10303 });
10304
10305 let wrap_guides = self.layout_wrap_guides(
10306 em_advance,
10307 scroll_position,
10308 content_origin,
10309 scrollbars_layout.as_ref(),
10310 vertical_scrollbar_width,
10311 &hitbox,
10312 window,
10313 cx,
10314 );
10315
10316 let minimap = window.with_element_namespace("minimap", |window| {
10317 self.layout_minimap(
10318 &snapshot,
10319 minimap_width,
10320 scroll_position,
10321 &scrollbar_layout_information,
10322 scrollbars_layout.as_ref(),
10323 window,
10324 cx,
10325 )
10326 });
10327
10328 let invisible_symbol_font_size = font_size / 2.;
10329 let whitespace_map = &self
10330 .editor
10331 .read(cx)
10332 .buffer
10333 .read(cx)
10334 .language_settings(cx)
10335 .whitespace_map;
10336
10337 let tab_char = whitespace_map.tab.clone();
10338 let tab_len = tab_char.len();
10339 let tab_invisible = window.text_system().shape_line(
10340 tab_char,
10341 invisible_symbol_font_size,
10342 &[TextRun {
10343 len: tab_len,
10344 font: self.style.text.font(),
10345 color: cx.theme().colors().editor_invisible,
10346 ..Default::default()
10347 }],
10348 None,
10349 );
10350
10351 let space_char = whitespace_map.space.clone();
10352 let space_len = space_char.len();
10353 let space_invisible = window.text_system().shape_line(
10354 space_char,
10355 invisible_symbol_font_size,
10356 &[TextRun {
10357 len: space_len,
10358 font: self.style.text.font(),
10359 color: cx.theme().colors().editor_invisible,
10360 ..Default::default()
10361 }],
10362 None,
10363 );
10364
10365 let mode = snapshot.mode.clone();
10366
10367 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
10368 (vec![], vec![])
10369 } else {
10370 self.layout_diff_hunk_controls(
10371 start_row..end_row,
10372 &row_infos,
10373 &text_hitbox,
10374 newest_selection_head,
10375 line_height,
10376 right_margin,
10377 scroll_pixel_position,
10378 &display_hunks,
10379 &highlighted_rows,
10380 self.editor.clone(),
10381 window,
10382 cx,
10383 )
10384 };
10385
10386 let position_map = Rc::new(PositionMap {
10387 size: bounds.size,
10388 visible_row_range,
10389 scroll_position,
10390 scroll_pixel_position,
10391 scroll_max,
10392 line_layouts,
10393 line_height,
10394 em_width,
10395 em_advance,
10396 snapshot,
10397 text_align: self.style.text.text_align,
10398 content_width: text_hitbox.size.width,
10399 gutter_hitbox: gutter_hitbox.clone(),
10400 text_hitbox: text_hitbox.clone(),
10401 inline_blame_bounds: inline_blame_layout
10402 .as_ref()
10403 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
10404 display_hunks: display_hunks.clone(),
10405 diff_hunk_control_bounds,
10406 });
10407
10408 self.editor.update(cx, |editor, _| {
10409 editor.last_position_map = Some(position_map.clone())
10410 });
10411
10412 EditorLayout {
10413 mode,
10414 position_map,
10415 visible_display_row_range: start_row..end_row,
10416 wrap_guides,
10417 indent_guides,
10418 hitbox,
10419 gutter_hitbox,
10420 display_hunks,
10421 content_origin,
10422 scrollbars_layout,
10423 minimap,
10424 active_rows,
10425 highlighted_rows,
10426 highlighted_ranges,
10427 highlighted_gutter_ranges,
10428 redacted_ranges,
10429 document_colors,
10430 line_elements,
10431 line_numbers,
10432 blamed_display_rows,
10433 inline_diagnostics,
10434 inline_blame_layout,
10435 inline_code_actions,
10436 blocks,
10437 cursors,
10438 visible_cursors,
10439 selections,
10440 edit_prediction_popover,
10441 diff_hunk_controls,
10442 mouse_context_menu,
10443 test_indicators,
10444 breakpoints,
10445 crease_toggles,
10446 crease_trailers,
10447 tab_invisible,
10448 space_invisible,
10449 sticky_buffer_header,
10450 sticky_headers,
10451 expand_toggles,
10452 text_align: self.style.text.text_align,
10453 content_width: text_hitbox.size.width,
10454 }
10455 })
10456 })
10457 })
10458 }
10459
10460 fn paint(
10461 &mut self,
10462 _: Option<&GlobalElementId>,
10463 _inspector_id: Option<&gpui::InspectorElementId>,
10464 bounds: Bounds<gpui::Pixels>,
10465 _: &mut Self::RequestLayoutState,
10466 layout: &mut Self::PrepaintState,
10467 window: &mut Window,
10468 cx: &mut App,
10469 ) {
10470 if !layout.mode.is_minimap() {
10471 let focus_handle = self.editor.focus_handle(cx);
10472 let key_context = self
10473 .editor
10474 .update(cx, |editor, cx| editor.key_context(window, cx));
10475
10476 window.set_key_context(key_context);
10477 window.handle_input(
10478 &focus_handle,
10479 ElementInputHandler::new(bounds, self.editor.clone()),
10480 cx,
10481 );
10482 self.register_actions(window, cx);
10483 self.register_key_listeners(window, cx, layout);
10484 }
10485
10486 let text_style = TextStyleRefinement {
10487 font_size: Some(self.style.text.font_size),
10488 line_height: Some(self.style.text.line_height),
10489 ..Default::default()
10490 };
10491 let rem_size = self.rem_size(cx);
10492 window.with_rem_size(rem_size, |window| {
10493 window.with_text_style(Some(text_style), |window| {
10494 window.with_content_mask(Some(ContentMask { bounds }), |window| {
10495 self.paint_mouse_listeners(layout, window, cx);
10496 self.paint_background(layout, window, cx);
10497 self.paint_indent_guides(layout, window, cx);
10498
10499 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10500 self.paint_blamed_display_rows(layout, window, cx);
10501 self.paint_line_numbers(layout, window, cx);
10502 }
10503
10504 self.paint_text(layout, window, cx);
10505
10506 if layout.gutter_hitbox.size.width > Pixels::ZERO {
10507 self.paint_gutter_highlights(layout, window, cx);
10508 self.paint_gutter_indicators(layout, window, cx);
10509 }
10510
10511 if !layout.blocks.is_empty() {
10512 window.with_element_namespace("blocks", |window| {
10513 self.paint_blocks(layout, window, cx);
10514 });
10515 }
10516
10517 window.with_element_namespace("blocks", |window| {
10518 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
10519 sticky_header.paint(window, cx)
10520 }
10521 });
10522
10523 self.paint_sticky_headers(layout, window, cx);
10524 self.paint_minimap(layout, window, cx);
10525 self.paint_scrollbars(layout, window, cx);
10526 self.paint_edit_prediction_popover(layout, window, cx);
10527 self.paint_mouse_context_menu(layout, window, cx);
10528 });
10529 })
10530 })
10531 }
10532}
10533
10534pub(super) fn gutter_bounds(
10535 editor_bounds: Bounds<Pixels>,
10536 gutter_dimensions: GutterDimensions,
10537) -> Bounds<Pixels> {
10538 Bounds {
10539 origin: editor_bounds.origin,
10540 size: size(gutter_dimensions.width, editor_bounds.size.height),
10541 }
10542}
10543
10544#[derive(Clone, Copy)]
10545struct ContextMenuLayout {
10546 y_flipped: bool,
10547 bounds: Bounds<Pixels>,
10548}
10549
10550/// Holds information required for layouting the editor scrollbars.
10551struct ScrollbarLayoutInformation {
10552 /// The bounds of the editor area (excluding the content offset).
10553 editor_bounds: Bounds<Pixels>,
10554 /// The available range to scroll within the document.
10555 scroll_range: Size<Pixels>,
10556 /// The space available for one glyph in the editor.
10557 glyph_grid_cell: Size<Pixels>,
10558}
10559
10560impl ScrollbarLayoutInformation {
10561 pub fn new(
10562 editor_bounds: Bounds<Pixels>,
10563 glyph_grid_cell: Size<Pixels>,
10564 document_size: Size<Pixels>,
10565 longest_line_blame_width: Pixels,
10566 settings: &EditorSettings,
10567 ) -> Self {
10568 let vertical_overscroll = match settings.scroll_beyond_last_line {
10569 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
10570 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
10571 ScrollBeyondLastLine::VerticalScrollMargin => {
10572 (1.0 + settings.vertical_scroll_margin) as f32 * glyph_grid_cell.height
10573 }
10574 };
10575
10576 let overscroll = size(longest_line_blame_width, vertical_overscroll);
10577
10578 ScrollbarLayoutInformation {
10579 editor_bounds,
10580 scroll_range: document_size + overscroll,
10581 glyph_grid_cell,
10582 }
10583 }
10584}
10585
10586impl IntoElement for EditorElement {
10587 type Element = Self;
10588
10589 fn into_element(self) -> Self::Element {
10590 self
10591 }
10592}
10593
10594pub struct EditorLayout {
10595 position_map: Rc<PositionMap>,
10596 hitbox: Hitbox,
10597 gutter_hitbox: Hitbox,
10598 content_origin: gpui::Point<Pixels>,
10599 scrollbars_layout: Option<EditorScrollbars>,
10600 minimap: Option<MinimapLayout>,
10601 mode: EditorMode,
10602 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
10603 indent_guides: Option<Vec<IndentGuideLayout>>,
10604 visible_display_row_range: Range<DisplayRow>,
10605 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
10606 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
10607 line_elements: SmallVec<[AnyElement; 1]>,
10608 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
10609 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10610 blamed_display_rows: Option<Vec<AnyElement>>,
10611 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
10612 inline_blame_layout: Option<InlineBlameLayout>,
10613 inline_code_actions: Option<AnyElement>,
10614 blocks: Vec<BlockLayout>,
10615 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10616 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
10617 redacted_ranges: Vec<Range<DisplayPoint>>,
10618 cursors: Vec<(DisplayPoint, Hsla)>,
10619 visible_cursors: Vec<CursorLayout>,
10620 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
10621 test_indicators: Vec<AnyElement>,
10622 breakpoints: Vec<AnyElement>,
10623 crease_toggles: Vec<Option<AnyElement>>,
10624 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
10625 diff_hunk_controls: Vec<AnyElement>,
10626 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
10627 edit_prediction_popover: Option<AnyElement>,
10628 mouse_context_menu: Option<AnyElement>,
10629 tab_invisible: ShapedLine,
10630 space_invisible: ShapedLine,
10631 sticky_buffer_header: Option<AnyElement>,
10632 sticky_headers: Option<StickyHeaders>,
10633 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
10634 text_align: TextAlign,
10635 content_width: Pixels,
10636}
10637
10638struct StickyHeaders {
10639 lines: Vec<StickyHeaderLine>,
10640 gutter_background: Hsla,
10641 content_background: Hsla,
10642 gutter_right_padding: Pixels,
10643}
10644
10645struct StickyHeaderLine {
10646 row: DisplayRow,
10647 offset: Pixels,
10648 line: LineWithInvisibles,
10649 line_number: Option<ShapedLine>,
10650 elements: SmallVec<[AnyElement; 1]>,
10651 available_text_width: Pixels,
10652 target_anchor: Anchor,
10653 hitbox: Hitbox,
10654}
10655
10656impl EditorLayout {
10657 fn line_end_overshoot(&self) -> Pixels {
10658 0.15 * self.position_map.line_height
10659 }
10660}
10661
10662impl StickyHeaders {
10663 fn paint(
10664 &mut self,
10665 layout: &mut EditorLayout,
10666 whitespace_setting: ShowWhitespaceSetting,
10667 window: &mut Window,
10668 cx: &mut App,
10669 ) {
10670 let line_height = layout.position_map.line_height;
10671
10672 for line in self.lines.iter_mut().rev() {
10673 window.paint_layer(
10674 Bounds::new(
10675 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10676 size(line.hitbox.size.width, line_height),
10677 ),
10678 |window| {
10679 let gutter_bounds = Bounds::new(
10680 layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
10681 size(layout.gutter_hitbox.size.width, line_height),
10682 );
10683 window.paint_quad(fill(gutter_bounds, self.gutter_background));
10684
10685 let text_bounds = Bounds::new(
10686 layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
10687 size(line.available_text_width, line_height),
10688 );
10689 window.paint_quad(fill(text_bounds, self.content_background));
10690
10691 if line.hitbox.is_hovered(window) {
10692 let hover_overlay = cx.theme().colors().panel_overlay_hover;
10693 window.paint_quad(fill(gutter_bounds, hover_overlay));
10694 window.paint_quad(fill(text_bounds, hover_overlay));
10695 }
10696
10697 line.paint(
10698 layout,
10699 self.gutter_right_padding,
10700 line.available_text_width,
10701 layout.content_origin,
10702 line_height,
10703 whitespace_setting,
10704 window,
10705 cx,
10706 );
10707 },
10708 );
10709
10710 window.set_cursor_style(CursorStyle::PointingHand, &line.hitbox);
10711 }
10712 }
10713}
10714
10715impl StickyHeaderLine {
10716 fn new(
10717 row: DisplayRow,
10718 offset: Pixels,
10719 mut line: LineWithInvisibles,
10720 line_number: Option<ShapedLine>,
10721 target_anchor: Anchor,
10722 line_height: Pixels,
10723 scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
10724 content_origin: gpui::Point<Pixels>,
10725 gutter_hitbox: &Hitbox,
10726 text_hitbox: &Hitbox,
10727 window: &mut Window,
10728 cx: &mut App,
10729 ) -> Self {
10730 let mut elements = SmallVec::<[AnyElement; 1]>::new();
10731 line.prepaint_with_custom_offset(
10732 line_height,
10733 scroll_pixel_position,
10734 content_origin,
10735 offset,
10736 &mut elements,
10737 window,
10738 cx,
10739 );
10740
10741 let hitbox_bounds = Bounds::new(
10742 gutter_hitbox.origin + point(Pixels::ZERO, offset),
10743 size(text_hitbox.right() - gutter_hitbox.left(), line_height),
10744 );
10745 let available_text_width =
10746 (hitbox_bounds.size.width - gutter_hitbox.size.width).max(Pixels::ZERO);
10747
10748 Self {
10749 row,
10750 offset,
10751 line,
10752 line_number,
10753 elements,
10754 available_text_width,
10755 target_anchor,
10756 hitbox: window.insert_hitbox(hitbox_bounds, HitboxBehavior::BlockMouseExceptScroll),
10757 }
10758 }
10759
10760 fn paint(
10761 &mut self,
10762 layout: &EditorLayout,
10763 gutter_right_padding: Pixels,
10764 available_text_width: Pixels,
10765 content_origin: gpui::Point<Pixels>,
10766 line_height: Pixels,
10767 whitespace_setting: ShowWhitespaceSetting,
10768 window: &mut Window,
10769 cx: &mut App,
10770 ) {
10771 window.with_content_mask(
10772 Some(ContentMask {
10773 bounds: Bounds::new(
10774 layout.position_map.text_hitbox.bounds.origin
10775 + point(Pixels::ZERO, self.offset),
10776 size(available_text_width, line_height),
10777 ),
10778 }),
10779 |window| {
10780 self.line.draw_with_custom_offset(
10781 layout,
10782 self.row,
10783 content_origin,
10784 self.offset,
10785 whitespace_setting,
10786 &[],
10787 window,
10788 cx,
10789 );
10790 for element in &mut self.elements {
10791 element.paint(window, cx);
10792 }
10793 },
10794 );
10795
10796 if let Some(line_number) = &self.line_number {
10797 let gutter_origin = layout.gutter_hitbox.origin + point(Pixels::ZERO, self.offset);
10798 let gutter_width = layout.gutter_hitbox.size.width;
10799 let origin = point(
10800 gutter_origin.x + gutter_width - gutter_right_padding - line_number.width,
10801 gutter_origin.y,
10802 );
10803 line_number
10804 .paint(origin, line_height, TextAlign::Left, None, window, cx)
10805 .log_err();
10806 }
10807 }
10808}
10809
10810#[derive(Debug)]
10811struct LineNumberSegment {
10812 shaped_line: ShapedLine,
10813 hitbox: Option<Hitbox>,
10814}
10815
10816#[derive(Debug)]
10817struct LineNumberLayout {
10818 segments: SmallVec<[LineNumberSegment; 1]>,
10819}
10820
10821struct ColoredRange<T> {
10822 start: T,
10823 end: T,
10824 color: Hsla,
10825}
10826
10827impl Along for ScrollbarAxes {
10828 type Unit = bool;
10829
10830 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
10831 match axis {
10832 ScrollbarAxis::Horizontal => self.horizontal,
10833 ScrollbarAxis::Vertical => self.vertical,
10834 }
10835 }
10836
10837 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
10838 match axis {
10839 ScrollbarAxis::Horizontal => ScrollbarAxes {
10840 horizontal: f(self.horizontal),
10841 vertical: self.vertical,
10842 },
10843 ScrollbarAxis::Vertical => ScrollbarAxes {
10844 horizontal: self.horizontal,
10845 vertical: f(self.vertical),
10846 },
10847 }
10848 }
10849}
10850
10851#[derive(Clone)]
10852struct EditorScrollbars {
10853 pub vertical: Option<ScrollbarLayout>,
10854 pub horizontal: Option<ScrollbarLayout>,
10855 pub visible: bool,
10856}
10857
10858impl EditorScrollbars {
10859 pub fn from_scrollbar_axes(
10860 show_scrollbar: ScrollbarAxes,
10861 layout_information: &ScrollbarLayoutInformation,
10862 content_offset: gpui::Point<Pixels>,
10863 scroll_position: gpui::Point<f64>,
10864 scrollbar_width: Pixels,
10865 right_margin: Pixels,
10866 editor_width: Pixels,
10867 show_scrollbars: bool,
10868 scrollbar_state: Option<&ActiveScrollbarState>,
10869 window: &mut Window,
10870 ) -> Self {
10871 let ScrollbarLayoutInformation {
10872 editor_bounds,
10873 scroll_range,
10874 glyph_grid_cell,
10875 } = layout_information;
10876
10877 let viewport_size = size(editor_width, editor_bounds.size.height);
10878
10879 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
10880 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
10881 Corner::BottomLeft,
10882 editor_bounds.bottom_left(),
10883 size(
10884 // The horizontal viewport size differs from the space available for the
10885 // horizontal scrollbar, so we have to manually stitch it together here.
10886 editor_bounds.size.width - right_margin,
10887 scrollbar_width,
10888 ),
10889 ),
10890 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
10891 Corner::TopRight,
10892 editor_bounds.top_right(),
10893 size(scrollbar_width, viewport_size.height),
10894 ),
10895 };
10896
10897 let mut create_scrollbar_layout = |axis| {
10898 let viewport_size = viewport_size.along(axis);
10899 let scroll_range = scroll_range.along(axis);
10900
10901 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
10902 (show_scrollbar.along(axis)
10903 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
10904 .then(|| {
10905 ScrollbarLayout::new(
10906 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
10907 viewport_size,
10908 scroll_range,
10909 glyph_grid_cell.along(axis),
10910 content_offset.along(axis),
10911 scroll_position.along(axis),
10912 show_scrollbars,
10913 axis,
10914 )
10915 .with_thumb_state(
10916 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
10917 )
10918 })
10919 };
10920
10921 Self {
10922 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
10923 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
10924 visible: show_scrollbars,
10925 }
10926 }
10927
10928 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
10929 [
10930 (&self.vertical, ScrollbarAxis::Vertical),
10931 (&self.horizontal, ScrollbarAxis::Horizontal),
10932 ]
10933 .into_iter()
10934 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
10935 }
10936
10937 /// Returns the currently hovered scrollbar axis, if any.
10938 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
10939 self.iter_scrollbars()
10940 .find(|s| s.0.hitbox.is_hovered(window))
10941 }
10942}
10943
10944#[derive(Clone)]
10945struct ScrollbarLayout {
10946 hitbox: Hitbox,
10947 visible_range: Range<ScrollOffset>,
10948 text_unit_size: Pixels,
10949 thumb_bounds: Option<Bounds<Pixels>>,
10950 thumb_state: ScrollbarThumbState,
10951}
10952
10953impl ScrollbarLayout {
10954 const BORDER_WIDTH: Pixels = px(1.0);
10955 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
10956 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
10957 const MIN_THUMB_SIZE: Pixels = px(25.0);
10958
10959 fn new(
10960 scrollbar_track_hitbox: Hitbox,
10961 viewport_size: Pixels,
10962 scroll_range: Pixels,
10963 glyph_space: Pixels,
10964 content_offset: Pixels,
10965 scroll_position: ScrollOffset,
10966 show_thumb: bool,
10967 axis: ScrollbarAxis,
10968 ) -> Self {
10969 let track_bounds = scrollbar_track_hitbox.bounds;
10970 // The length of the track available to the scrollbar thumb. We deliberately
10971 // exclude the content size here so that the thumb aligns with the content.
10972 let track_length = track_bounds.size.along(axis) - content_offset;
10973
10974 Self::new_with_hitbox_and_track_length(
10975 scrollbar_track_hitbox,
10976 track_length,
10977 viewport_size,
10978 scroll_range.into(),
10979 glyph_space,
10980 content_offset.into(),
10981 scroll_position,
10982 show_thumb,
10983 axis,
10984 )
10985 }
10986
10987 fn for_minimap(
10988 minimap_track_hitbox: Hitbox,
10989 visible_lines: f64,
10990 total_editor_lines: f64,
10991 minimap_line_height: Pixels,
10992 scroll_position: ScrollOffset,
10993 minimap_scroll_top: ScrollOffset,
10994 show_thumb: bool,
10995 ) -> Self {
10996 // The scrollbar thumb size is calculated as
10997 // (visible_content/total_content) Γ scrollbar_track_length.
10998 //
10999 // For the minimap's thumb layout, we leverage this by setting the
11000 // scrollbar track length to the entire document size (using minimap line
11001 // height). This creates a thumb that exactly represents the editor
11002 // viewport scaled to minimap proportions.
11003 //
11004 // We adjust the thumb position relative to `minimap_scroll_top` to
11005 // accommodate for the deliberately oversized track.
11006 //
11007 // This approach ensures that the minimap thumb accurately reflects the
11008 // editor's current scroll position whilst nicely synchronizing the minimap
11009 // thumb and scrollbar thumb.
11010 let scroll_range = total_editor_lines * f64::from(minimap_line_height);
11011 let viewport_size = visible_lines * f64::from(minimap_line_height);
11012
11013 let track_top_offset = -minimap_scroll_top * f64::from(minimap_line_height);
11014
11015 Self::new_with_hitbox_and_track_length(
11016 minimap_track_hitbox,
11017 Pixels::from(scroll_range),
11018 Pixels::from(viewport_size),
11019 scroll_range,
11020 minimap_line_height,
11021 track_top_offset,
11022 scroll_position,
11023 show_thumb,
11024 ScrollbarAxis::Vertical,
11025 )
11026 }
11027
11028 fn new_with_hitbox_and_track_length(
11029 scrollbar_track_hitbox: Hitbox,
11030 track_length: Pixels,
11031 viewport_size: Pixels,
11032 scroll_range: f64,
11033 glyph_space: Pixels,
11034 content_offset: ScrollOffset,
11035 scroll_position: ScrollOffset,
11036 show_thumb: bool,
11037 axis: ScrollbarAxis,
11038 ) -> Self {
11039 let text_units_per_page = viewport_size.to_f64() / glyph_space.to_f64();
11040 let visible_range = scroll_position..scroll_position + text_units_per_page;
11041 let total_text_units = scroll_range / glyph_space.to_f64();
11042
11043 let thumb_percentage = text_units_per_page / total_text_units;
11044 let thumb_size = Pixels::from(ScrollOffset::from(track_length) * thumb_percentage)
11045 .max(ScrollbarLayout::MIN_THUMB_SIZE)
11046 .min(track_length);
11047
11048 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
11049
11050 let content_larger_than_viewport = text_unit_divisor > 0.;
11051
11052 let text_unit_size = if content_larger_than_viewport {
11053 Pixels::from(ScrollOffset::from(track_length - thumb_size) / text_unit_divisor)
11054 } else {
11055 glyph_space
11056 };
11057
11058 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
11059 Self::thumb_bounds(
11060 &scrollbar_track_hitbox,
11061 content_offset,
11062 visible_range.start,
11063 text_unit_size,
11064 thumb_size,
11065 axis,
11066 )
11067 });
11068
11069 ScrollbarLayout {
11070 hitbox: scrollbar_track_hitbox,
11071 visible_range,
11072 text_unit_size,
11073 thumb_bounds,
11074 thumb_state: Default::default(),
11075 }
11076 }
11077
11078 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
11079 if let Some(thumb_state) = thumb_state {
11080 Self {
11081 thumb_state,
11082 ..self
11083 }
11084 } else {
11085 self
11086 }
11087 }
11088
11089 fn thumb_bounds(
11090 scrollbar_track: &Hitbox,
11091 content_offset: f64,
11092 visible_range_start: f64,
11093 text_unit_size: Pixels,
11094 thumb_size: Pixels,
11095 axis: ScrollbarAxis,
11096 ) -> Bounds<Pixels> {
11097 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
11098 origin
11099 + Pixels::from(
11100 content_offset + visible_range_start * ScrollOffset::from(text_unit_size),
11101 )
11102 });
11103 Bounds::new(
11104 thumb_origin,
11105 scrollbar_track.size.apply_along(axis, |_| thumb_size),
11106 )
11107 }
11108
11109 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
11110 self.thumb_bounds
11111 .is_some_and(|bounds| bounds.contains(position))
11112 }
11113
11114 fn marker_quads_for_ranges(
11115 &self,
11116 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
11117 column: Option<usize>,
11118 ) -> Vec<PaintQuad> {
11119 struct MinMax {
11120 min: Pixels,
11121 max: Pixels,
11122 }
11123 let (x_range, height_limit) = if let Some(column) = column {
11124 let column_width = ((self.hitbox.size.width - Self::BORDER_WIDTH) / 3.0).floor();
11125 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
11126 let end = start + column_width;
11127 (
11128 Range { start, end },
11129 MinMax {
11130 min: Self::MIN_MARKER_HEIGHT,
11131 max: px(f32::MAX),
11132 },
11133 )
11134 } else {
11135 (
11136 Range {
11137 start: Self::BORDER_WIDTH,
11138 end: self.hitbox.size.width,
11139 },
11140 MinMax {
11141 min: Self::LINE_MARKER_HEIGHT,
11142 max: Self::LINE_MARKER_HEIGHT,
11143 },
11144 )
11145 };
11146
11147 let row_to_y = |row: DisplayRow| row.as_f64() as f32 * self.text_unit_size;
11148 let mut pixel_ranges = row_ranges
11149 .into_iter()
11150 .map(|range| {
11151 let start_y = row_to_y(range.start);
11152 let end_y = row_to_y(range.end)
11153 + self
11154 .text_unit_size
11155 .max(height_limit.min)
11156 .min(height_limit.max);
11157 ColoredRange {
11158 start: start_y,
11159 end: end_y,
11160 color: range.color,
11161 }
11162 })
11163 .peekable();
11164
11165 let mut quads = Vec::new();
11166 while let Some(mut pixel_range) = pixel_ranges.next() {
11167 while let Some(next_pixel_range) = pixel_ranges.peek() {
11168 if pixel_range.end >= next_pixel_range.start - px(1.0)
11169 && pixel_range.color == next_pixel_range.color
11170 {
11171 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
11172 pixel_ranges.next();
11173 } else {
11174 break;
11175 }
11176 }
11177
11178 let bounds = Bounds::from_corners(
11179 point(x_range.start, pixel_range.start),
11180 point(x_range.end, pixel_range.end),
11181 );
11182 quads.push(quad(
11183 bounds,
11184 Corners::default(),
11185 pixel_range.color,
11186 Edges::default(),
11187 Hsla::transparent_black(),
11188 BorderStyle::default(),
11189 ));
11190 }
11191
11192 quads
11193 }
11194}
11195
11196struct MinimapLayout {
11197 pub minimap: AnyElement,
11198 pub thumb_layout: ScrollbarLayout,
11199 pub minimap_scroll_top: ScrollOffset,
11200 pub minimap_line_height: Pixels,
11201 pub thumb_border_style: MinimapThumbBorder,
11202 pub max_scroll_top: ScrollOffset,
11203}
11204
11205impl MinimapLayout {
11206 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
11207 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
11208 /// The minimap width as a percentage of the editor width.
11209 const MINIMAP_WIDTH_PCT: f32 = 0.15;
11210 /// Calculates the scroll top offset the minimap editor has to have based on the
11211 /// current scroll progress.
11212 fn calculate_minimap_top_offset(
11213 document_lines: f64,
11214 visible_editor_lines: f64,
11215 visible_minimap_lines: f64,
11216 scroll_position: f64,
11217 ) -> ScrollOffset {
11218 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
11219 if non_visible_document_lines == 0. {
11220 0.
11221 } else {
11222 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
11223 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
11224 }
11225 }
11226}
11227
11228struct CreaseTrailerLayout {
11229 element: AnyElement,
11230 bounds: Bounds<Pixels>,
11231}
11232
11233pub(crate) struct PositionMap {
11234 pub size: Size<Pixels>,
11235 pub line_height: Pixels,
11236 pub scroll_position: gpui::Point<ScrollOffset>,
11237 pub scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
11238 pub scroll_max: gpui::Point<ScrollOffset>,
11239 pub em_width: Pixels,
11240 pub em_advance: Pixels,
11241 pub visible_row_range: Range<DisplayRow>,
11242 pub line_layouts: Vec<LineWithInvisibles>,
11243 pub snapshot: EditorSnapshot,
11244 pub text_align: TextAlign,
11245 pub content_width: Pixels,
11246 pub text_hitbox: Hitbox,
11247 pub gutter_hitbox: Hitbox,
11248 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
11249 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
11250 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
11251}
11252
11253#[derive(Debug, Copy, Clone)]
11254pub struct PointForPosition {
11255 pub previous_valid: DisplayPoint,
11256 pub next_valid: DisplayPoint,
11257 pub exact_unclipped: DisplayPoint,
11258 pub column_overshoot_after_line_end: u32,
11259}
11260
11261impl PointForPosition {
11262 pub fn as_valid(&self) -> Option<DisplayPoint> {
11263 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
11264 Some(self.previous_valid)
11265 } else {
11266 None
11267 }
11268 }
11269
11270 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
11271 let Some(valid_point) = self.as_valid() else {
11272 return false;
11273 };
11274 let range = selection.range();
11275
11276 let candidate_row = valid_point.row();
11277 let candidate_col = valid_point.column();
11278
11279 let start_row = range.start.row();
11280 let start_col = range.start.column();
11281 let end_row = range.end.row();
11282 let end_col = range.end.column();
11283
11284 if candidate_row < start_row || candidate_row > end_row {
11285 false
11286 } else if start_row == end_row {
11287 candidate_col >= start_col && candidate_col < end_col
11288 } else if candidate_row == start_row {
11289 candidate_col >= start_col
11290 } else if candidate_row == end_row {
11291 candidate_col < end_col
11292 } else {
11293 true
11294 }
11295 }
11296}
11297
11298impl PositionMap {
11299 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
11300 let text_bounds = self.text_hitbox.bounds;
11301 let scroll_position = self.snapshot.scroll_position();
11302 let position = position - text_bounds.origin;
11303 let y = position.y.max(px(0.)).min(self.size.height);
11304 let x = position.x + (scroll_position.x as f32 * self.em_advance);
11305 let row = ((y / self.line_height) as f64 + scroll_position.y) as u32;
11306
11307 let (column, x_overshoot_after_line_end) = if let Some(line) = self
11308 .line_layouts
11309 .get(row as usize - scroll_position.y as usize)
11310 {
11311 let alignment_offset = line.alignment_offset(self.text_align, self.content_width);
11312 let x_relative_to_text = x - alignment_offset;
11313 if let Some(ix) = line.index_for_x(x_relative_to_text) {
11314 (ix as u32, px(0.))
11315 } else {
11316 (line.len as u32, px(0.).max(x_relative_to_text - line.width))
11317 }
11318 } else {
11319 (0, x)
11320 };
11321
11322 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
11323 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
11324 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
11325
11326 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
11327 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
11328 PointForPosition {
11329 previous_valid,
11330 next_valid,
11331 exact_unclipped,
11332 column_overshoot_after_line_end,
11333 }
11334 }
11335}
11336
11337struct BlockLayout {
11338 id: BlockId,
11339 x_offset: Pixels,
11340 row: Option<DisplayRow>,
11341 element: AnyElement,
11342 available_space: Size<AvailableSpace>,
11343 style: BlockStyle,
11344 overlaps_gutter: bool,
11345 is_buffer_header: bool,
11346}
11347
11348pub fn layout_line(
11349 row: DisplayRow,
11350 snapshot: &EditorSnapshot,
11351 style: &EditorStyle,
11352 text_width: Pixels,
11353 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
11354 window: &mut Window,
11355 cx: &mut App,
11356) -> LineWithInvisibles {
11357 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
11358 LineWithInvisibles::from_chunks(
11359 chunks,
11360 style,
11361 MAX_LINE_LEN,
11362 1,
11363 &snapshot.mode,
11364 text_width,
11365 is_row_soft_wrapped,
11366 &[],
11367 window,
11368 cx,
11369 )
11370 .pop()
11371 .unwrap()
11372}
11373
11374#[derive(Debug)]
11375pub struct IndentGuideLayout {
11376 origin: gpui::Point<Pixels>,
11377 length: Pixels,
11378 single_indent_width: Pixels,
11379 depth: u32,
11380 active: bool,
11381 settings: IndentGuideSettings,
11382}
11383
11384pub struct CursorLayout {
11385 origin: gpui::Point<Pixels>,
11386 block_width: Pixels,
11387 line_height: Pixels,
11388 color: Hsla,
11389 shape: CursorShape,
11390 block_text: Option<ShapedLine>,
11391 cursor_name: Option<AnyElement>,
11392}
11393
11394#[derive(Debug)]
11395pub struct CursorName {
11396 string: SharedString,
11397 color: Hsla,
11398 is_top_row: bool,
11399}
11400
11401impl CursorLayout {
11402 pub fn new(
11403 origin: gpui::Point<Pixels>,
11404 block_width: Pixels,
11405 line_height: Pixels,
11406 color: Hsla,
11407 shape: CursorShape,
11408 block_text: Option<ShapedLine>,
11409 ) -> CursorLayout {
11410 CursorLayout {
11411 origin,
11412 block_width,
11413 line_height,
11414 color,
11415 shape,
11416 block_text,
11417 cursor_name: None,
11418 }
11419 }
11420
11421 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11422 Bounds {
11423 origin: self.origin + origin,
11424 size: size(self.block_width, self.line_height),
11425 }
11426 }
11427
11428 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
11429 match self.shape {
11430 CursorShape::Bar => Bounds {
11431 origin: self.origin + origin,
11432 size: size(px(2.0), self.line_height),
11433 },
11434 CursorShape::Block | CursorShape::Hollow => Bounds {
11435 origin: self.origin + origin,
11436 size: size(self.block_width, self.line_height),
11437 },
11438 CursorShape::Underline => Bounds {
11439 origin: self.origin
11440 + origin
11441 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
11442 size: size(self.block_width, px(2.0)),
11443 },
11444 }
11445 }
11446
11447 pub fn layout(
11448 &mut self,
11449 origin: gpui::Point<Pixels>,
11450 cursor_name: Option<CursorName>,
11451 window: &mut Window,
11452 cx: &mut App,
11453 ) {
11454 if let Some(cursor_name) = cursor_name {
11455 let bounds = self.bounds(origin);
11456 let text_size = self.line_height / 1.5;
11457
11458 let name_origin = if cursor_name.is_top_row {
11459 point(bounds.right() - px(1.), bounds.top())
11460 } else {
11461 match self.shape {
11462 CursorShape::Bar => point(
11463 bounds.right() - px(2.),
11464 bounds.top() - text_size / 2. - px(1.),
11465 ),
11466 _ => point(
11467 bounds.right() - px(1.),
11468 bounds.top() - text_size / 2. - px(1.),
11469 ),
11470 }
11471 };
11472 let mut name_element = div()
11473 .bg(self.color)
11474 .text_size(text_size)
11475 .px_0p5()
11476 .line_height(text_size + px(2.))
11477 .text_color(cursor_name.color)
11478 .child(cursor_name.string)
11479 .into_any_element();
11480
11481 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
11482
11483 self.cursor_name = Some(name_element);
11484 }
11485 }
11486
11487 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
11488 let bounds = self.bounds(origin);
11489
11490 //Draw background or border quad
11491 let cursor = if matches!(self.shape, CursorShape::Hollow) {
11492 outline(bounds, self.color, BorderStyle::Solid)
11493 } else {
11494 fill(bounds, self.color)
11495 };
11496
11497 if let Some(name) = &mut self.cursor_name {
11498 name.paint(window, cx);
11499 }
11500
11501 window.paint_quad(cursor);
11502
11503 if let Some(block_text) = &self.block_text {
11504 block_text
11505 .paint(
11506 self.origin + origin,
11507 self.line_height,
11508 TextAlign::Left,
11509 None,
11510 window,
11511 cx,
11512 )
11513 .log_err();
11514 }
11515 }
11516
11517 pub fn shape(&self) -> CursorShape {
11518 self.shape
11519 }
11520}
11521
11522#[derive(Debug)]
11523pub struct HighlightedRange {
11524 pub start_y: Pixels,
11525 pub line_height: Pixels,
11526 pub lines: Vec<HighlightedRangeLine>,
11527 pub color: Hsla,
11528 pub corner_radius: Pixels,
11529}
11530
11531#[derive(Debug)]
11532pub struct HighlightedRangeLine {
11533 pub start_x: Pixels,
11534 pub end_x: Pixels,
11535}
11536
11537impl HighlightedRange {
11538 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
11539 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
11540 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
11541 self.paint_lines(
11542 self.start_y + self.line_height,
11543 &self.lines[1..],
11544 fill,
11545 bounds,
11546 window,
11547 );
11548 } else {
11549 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
11550 }
11551 }
11552
11553 fn paint_lines(
11554 &self,
11555 start_y: Pixels,
11556 lines: &[HighlightedRangeLine],
11557 fill: bool,
11558 _bounds: Bounds<Pixels>,
11559 window: &mut Window,
11560 ) {
11561 if lines.is_empty() {
11562 return;
11563 }
11564
11565 let first_line = lines.first().unwrap();
11566 let last_line = lines.last().unwrap();
11567
11568 let first_top_left = point(first_line.start_x, start_y);
11569 let first_top_right = point(first_line.end_x, start_y);
11570
11571 let curve_height = point(Pixels::ZERO, self.corner_radius);
11572 let curve_width = |start_x: Pixels, end_x: Pixels| {
11573 let max = (end_x - start_x) / 2.;
11574 let width = if max < self.corner_radius {
11575 max
11576 } else {
11577 self.corner_radius
11578 };
11579
11580 point(width, Pixels::ZERO)
11581 };
11582
11583 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
11584 let mut builder = if fill {
11585 gpui::PathBuilder::fill()
11586 } else {
11587 gpui::PathBuilder::stroke(px(1.))
11588 };
11589 builder.move_to(first_top_right - top_curve_width);
11590 builder.curve_to(first_top_right + curve_height, first_top_right);
11591
11592 let mut iter = lines.iter().enumerate().peekable();
11593 while let Some((ix, line)) = iter.next() {
11594 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
11595
11596 if let Some((_, next_line)) = iter.peek() {
11597 let next_top_right = point(next_line.end_x, bottom_right.y);
11598
11599 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
11600 Ordering::Equal => {
11601 builder.line_to(bottom_right);
11602 }
11603 Ordering::Less => {
11604 let curve_width = curve_width(next_top_right.x, bottom_right.x);
11605 builder.line_to(bottom_right - curve_height);
11606 if self.corner_radius > Pixels::ZERO {
11607 builder.curve_to(bottom_right - curve_width, bottom_right);
11608 }
11609 builder.line_to(next_top_right + curve_width);
11610 if self.corner_radius > Pixels::ZERO {
11611 builder.curve_to(next_top_right + curve_height, next_top_right);
11612 }
11613 }
11614 Ordering::Greater => {
11615 let curve_width = curve_width(bottom_right.x, next_top_right.x);
11616 builder.line_to(bottom_right - curve_height);
11617 if self.corner_radius > Pixels::ZERO {
11618 builder.curve_to(bottom_right + curve_width, bottom_right);
11619 }
11620 builder.line_to(next_top_right - curve_width);
11621 if self.corner_radius > Pixels::ZERO {
11622 builder.curve_to(next_top_right + curve_height, next_top_right);
11623 }
11624 }
11625 }
11626 } else {
11627 let curve_width = curve_width(line.start_x, line.end_x);
11628 builder.line_to(bottom_right - curve_height);
11629 if self.corner_radius > Pixels::ZERO {
11630 builder.curve_to(bottom_right - curve_width, bottom_right);
11631 }
11632
11633 let bottom_left = point(line.start_x, bottom_right.y);
11634 builder.line_to(bottom_left + curve_width);
11635 if self.corner_radius > Pixels::ZERO {
11636 builder.curve_to(bottom_left - curve_height, bottom_left);
11637 }
11638 }
11639 }
11640
11641 if first_line.start_x > last_line.start_x {
11642 let curve_width = curve_width(last_line.start_x, first_line.start_x);
11643 let second_top_left = point(last_line.start_x, start_y + self.line_height);
11644 builder.line_to(second_top_left + curve_height);
11645 if self.corner_radius > Pixels::ZERO {
11646 builder.curve_to(second_top_left + curve_width, second_top_left);
11647 }
11648 let first_bottom_left = point(first_line.start_x, second_top_left.y);
11649 builder.line_to(first_bottom_left - curve_width);
11650 if self.corner_radius > Pixels::ZERO {
11651 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
11652 }
11653 }
11654
11655 builder.line_to(first_top_left + curve_height);
11656 if self.corner_radius > Pixels::ZERO {
11657 builder.curve_to(first_top_left + top_curve_width, first_top_left);
11658 }
11659 builder.line_to(first_top_right - top_curve_width);
11660
11661 if let Ok(path) = builder.build() {
11662 window.paint_path(path, self.color);
11663 }
11664 }
11665}
11666
11667pub(crate) struct StickyHeader {
11668 pub item: language::OutlineItem<Anchor>,
11669 pub sticky_row: DisplayRow,
11670 pub start_point: Point,
11671 pub offset: ScrollOffset,
11672}
11673
11674enum CursorPopoverType {
11675 CodeContextMenu,
11676 EditPrediction,
11677}
11678
11679pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11680 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
11681}
11682
11683fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
11684 (delta.pow(1.2) / 300.0).into()
11685}
11686
11687pub fn register_action<T: Action>(
11688 editor: &Entity<Editor>,
11689 window: &mut Window,
11690 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
11691) {
11692 let editor = editor.clone();
11693 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
11694 let action = action.downcast_ref().unwrap();
11695 if phase == DispatchPhase::Bubble {
11696 editor.update(cx, |editor, cx| {
11697 listener(editor, action, window, cx);
11698 })
11699 }
11700 })
11701}
11702
11703fn compute_auto_height_layout(
11704 editor: &mut Editor,
11705 min_lines: usize,
11706 max_lines: Option<usize>,
11707 known_dimensions: Size<Option<Pixels>>,
11708 available_width: AvailableSpace,
11709 window: &mut Window,
11710 cx: &mut Context<Editor>,
11711) -> Option<Size<Pixels>> {
11712 let width = known_dimensions.width.or({
11713 if let AvailableSpace::Definite(available_width) = available_width {
11714 Some(available_width)
11715 } else {
11716 None
11717 }
11718 })?;
11719 if let Some(height) = known_dimensions.height {
11720 return Some(size(width, height));
11721 }
11722
11723 let style = editor.style.as_ref().unwrap();
11724 let font_id = window.text_system().resolve_font(&style.text.font());
11725 let font_size = style.text.font_size.to_pixels(window.rem_size());
11726 let line_height = style.text.line_height_in_pixels(window.rem_size());
11727 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
11728
11729 let mut snapshot = editor.snapshot(window, cx);
11730 let gutter_dimensions = snapshot.gutter_dimensions(font_id, font_size, style, window, cx);
11731
11732 editor.gutter_dimensions = gutter_dimensions;
11733 let text_width = width - gutter_dimensions.width;
11734 let overscroll = size(em_width, px(0.));
11735
11736 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
11737 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
11738 && editor.set_wrap_width(Some(editor_width), cx)
11739 {
11740 snapshot = editor.snapshot(window, cx);
11741 }
11742
11743 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
11744
11745 let min_height = line_height * min_lines as f32;
11746 let content_height = scroll_height.max(min_height);
11747
11748 let final_height = if let Some(max_lines) = max_lines {
11749 let max_height = line_height * max_lines as f32;
11750 content_height.min(max_height)
11751 } else {
11752 content_height
11753 };
11754
11755 Some(size(width, final_height))
11756}
11757
11758#[cfg(test)]
11759mod tests {
11760 use super::*;
11761 use crate::{
11762 Editor, MultiBuffer, SelectionEffects,
11763 display_map::{BlockPlacement, BlockProperties},
11764 editor_tests::{init_test, update_test_language_settings},
11765 };
11766 use gpui::{TestAppContext, VisualTestContext};
11767 use language::language_settings;
11768 use log::info;
11769 use std::num::NonZeroU32;
11770 use util::test::sample_text;
11771
11772 #[gpui::test]
11773 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
11774 init_test(cx, |_| {});
11775
11776 let window = cx.add_window(|window, cx| {
11777 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11778 let mut editor = Editor::new(
11779 EditorMode::AutoHeight {
11780 min_lines: 1,
11781 max_lines: None,
11782 },
11783 buffer,
11784 None,
11785 window,
11786 cx,
11787 );
11788 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11789 editor
11790 });
11791 let cx = &mut VisualTestContext::from_window(*window, cx);
11792 let editor = window.root(cx).unwrap();
11793 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11794
11795 for x in 1..=100 {
11796 let (_, state) = cx.draw(
11797 Default::default(),
11798 size(px(200. + 0.13 * x as f32), px(500.)),
11799 |_, _| EditorElement::new(&editor, style.clone()),
11800 );
11801
11802 assert!(
11803 state.position_map.scroll_max.x == 0.,
11804 "Soft wrapped editor should have no horizontal scrolling!"
11805 );
11806 }
11807 }
11808
11809 #[gpui::test]
11810 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
11811 init_test(cx, |_| {});
11812
11813 let window = cx.add_window(|window, cx| {
11814 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
11815 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
11816 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11817 editor
11818 });
11819 let cx = &mut VisualTestContext::from_window(*window, cx);
11820 let editor = window.root(cx).unwrap();
11821 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
11822
11823 for x in 1..=100 {
11824 let (_, state) = cx.draw(
11825 Default::default(),
11826 size(px(200. + 0.13 * x as f32), px(500.)),
11827 |_, _| EditorElement::new(&editor, style.clone()),
11828 );
11829
11830 assert!(
11831 state.position_map.scroll_max.x == 0.,
11832 "Soft wrapped editor should have no horizontal scrolling!"
11833 );
11834 }
11835 }
11836
11837 #[gpui::test]
11838 fn test_layout_line_numbers(cx: &mut TestAppContext) {
11839 init_test(cx, |_| {});
11840 let window = cx.add_window(|window, cx| {
11841 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
11842 Editor::new(EditorMode::full(), buffer, None, window, cx)
11843 });
11844
11845 let editor = window.root(cx).unwrap();
11846 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
11847 let line_height = window
11848 .update(cx, |_, window, _| {
11849 style.text.line_height_in_pixels(window.rem_size())
11850 })
11851 .unwrap();
11852 let element = EditorElement::new(&editor, style);
11853 let snapshot = window
11854 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
11855 .unwrap();
11856
11857 let layouts = cx
11858 .update_window(*window, |_, window, cx| {
11859 element.layout_line_numbers(
11860 None,
11861 GutterDimensions {
11862 left_padding: Pixels::ZERO,
11863 right_padding: Pixels::ZERO,
11864 width: px(30.0),
11865 margin: Pixels::ZERO,
11866 git_blame_entries_width: None,
11867 },
11868 line_height,
11869 gpui::Point::default(),
11870 DisplayRow(0)..DisplayRow(6),
11871 &(0..6)
11872 .map(|row| RowInfo {
11873 buffer_row: Some(row),
11874 ..Default::default()
11875 })
11876 .collect::<Vec<_>>(),
11877 &BTreeMap::default(),
11878 Some(DisplayRow(0)),
11879 &snapshot,
11880 window,
11881 cx,
11882 )
11883 })
11884 .unwrap();
11885 assert_eq!(layouts.len(), 6);
11886
11887 let relative_rows = window
11888 .update(cx, |editor, window, cx| {
11889 let snapshot = editor.snapshot(window, cx);
11890 snapshot.calculate_relative_line_numbers(
11891 &(DisplayRow(0)..DisplayRow(6)),
11892 DisplayRow(3),
11893 false,
11894 )
11895 })
11896 .unwrap();
11897 assert_eq!(relative_rows[&DisplayRow(0)], 3);
11898 assert_eq!(relative_rows[&DisplayRow(1)], 2);
11899 assert_eq!(relative_rows[&DisplayRow(2)], 1);
11900 // current line has no relative number
11901 assert_eq!(relative_rows[&DisplayRow(4)], 1);
11902 assert_eq!(relative_rows[&DisplayRow(5)], 2);
11903
11904 // works if cursor is before screen
11905 let relative_rows = window
11906 .update(cx, |editor, window, cx| {
11907 let snapshot = editor.snapshot(window, cx);
11908 snapshot.calculate_relative_line_numbers(
11909 &(DisplayRow(3)..DisplayRow(6)),
11910 DisplayRow(1),
11911 false,
11912 )
11913 })
11914 .unwrap();
11915 assert_eq!(relative_rows.len(), 3);
11916 assert_eq!(relative_rows[&DisplayRow(3)], 2);
11917 assert_eq!(relative_rows[&DisplayRow(4)], 3);
11918 assert_eq!(relative_rows[&DisplayRow(5)], 4);
11919
11920 // works if cursor is after screen
11921 let relative_rows = window
11922 .update(cx, |editor, window, cx| {
11923 let snapshot = editor.snapshot(window, cx);
11924 snapshot.calculate_relative_line_numbers(
11925 &(DisplayRow(0)..DisplayRow(3)),
11926 DisplayRow(6),
11927 false,
11928 )
11929 })
11930 .unwrap();
11931 assert_eq!(relative_rows.len(), 3);
11932 assert_eq!(relative_rows[&DisplayRow(0)], 5);
11933 assert_eq!(relative_rows[&DisplayRow(1)], 4);
11934 assert_eq!(relative_rows[&DisplayRow(2)], 3);
11935
11936 const DELETED_LINE: u32 = 3;
11937 let layouts = cx
11938 .update_window(*window, |_, window, cx| {
11939 element.layout_line_numbers(
11940 None,
11941 GutterDimensions {
11942 left_padding: Pixels::ZERO,
11943 right_padding: Pixels::ZERO,
11944 width: px(30.0),
11945 margin: Pixels::ZERO,
11946 git_blame_entries_width: None,
11947 },
11948 line_height,
11949 gpui::Point::default(),
11950 DisplayRow(0)..DisplayRow(6),
11951 &(0..6)
11952 .map(|row| RowInfo {
11953 buffer_row: Some(row),
11954 diff_status: (row == DELETED_LINE).then(|| {
11955 DiffHunkStatus::deleted(
11956 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
11957 )
11958 }),
11959 ..Default::default()
11960 })
11961 .collect::<Vec<_>>(),
11962 &BTreeMap::default(),
11963 Some(DisplayRow(0)),
11964 &snapshot,
11965 window,
11966 cx,
11967 )
11968 })
11969 .unwrap();
11970 assert_eq!(layouts.len(), 5,);
11971 assert!(
11972 layouts.get(&MultiBufferRow(DELETED_LINE)).is_none(),
11973 "Deleted line should not have a line number"
11974 );
11975 }
11976
11977 #[gpui::test]
11978 fn test_layout_line_numbers_wrapping(cx: &mut TestAppContext) {
11979 init_test(cx, |_| {});
11980 let window = cx.add_window(|window, cx| {
11981 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
11982 Editor::new(EditorMode::full(), buffer, None, window, cx)
11983 });
11984
11985 update_test_language_settings(cx, |s| {
11986 s.defaults.preferred_line_length = Some(5_u32);
11987 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
11988 });
11989
11990 let editor = window.root(cx).unwrap();
11991 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
11992 let line_height = window
11993 .update(cx, |_, window, _| {
11994 style.text.line_height_in_pixels(window.rem_size())
11995 })
11996 .unwrap();
11997 let element = EditorElement::new(&editor, style);
11998 let snapshot = window
11999 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
12000 .unwrap();
12001
12002 let layouts = cx
12003 .update_window(*window, |_, window, cx| {
12004 element.layout_line_numbers(
12005 None,
12006 GutterDimensions {
12007 left_padding: Pixels::ZERO,
12008 right_padding: Pixels::ZERO,
12009 width: px(30.0),
12010 margin: Pixels::ZERO,
12011 git_blame_entries_width: None,
12012 },
12013 line_height,
12014 gpui::Point::default(),
12015 DisplayRow(0)..DisplayRow(6),
12016 &(0..6)
12017 .map(|row| RowInfo {
12018 buffer_row: Some(row),
12019 ..Default::default()
12020 })
12021 .collect::<Vec<_>>(),
12022 &BTreeMap::default(),
12023 Some(DisplayRow(0)),
12024 &snapshot,
12025 window,
12026 cx,
12027 )
12028 })
12029 .unwrap();
12030 assert_eq!(layouts.len(), 3);
12031
12032 let relative_rows = window
12033 .update(cx, |editor, window, cx| {
12034 let snapshot = editor.snapshot(window, cx);
12035 snapshot.calculate_relative_line_numbers(
12036 &(DisplayRow(0)..DisplayRow(6)),
12037 DisplayRow(3),
12038 true,
12039 )
12040 })
12041 .unwrap();
12042
12043 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12044 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12045 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12046 // current line has no relative number
12047 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12048 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12049
12050 let layouts = cx
12051 .update_window(*window, |_, window, cx| {
12052 element.layout_line_numbers(
12053 None,
12054 GutterDimensions {
12055 left_padding: Pixels::ZERO,
12056 right_padding: Pixels::ZERO,
12057 width: px(30.0),
12058 margin: Pixels::ZERO,
12059 git_blame_entries_width: None,
12060 },
12061 line_height,
12062 gpui::Point::default(),
12063 DisplayRow(0)..DisplayRow(6),
12064 &(0..6)
12065 .map(|row| RowInfo {
12066 buffer_row: Some(row),
12067 diff_status: Some(DiffHunkStatus::deleted(
12068 buffer_diff::DiffHunkSecondaryStatus::NoSecondaryHunk,
12069 )),
12070 ..Default::default()
12071 })
12072 .collect::<Vec<_>>(),
12073 &BTreeMap::from_iter([(DisplayRow(0), LineHighlightSpec::default())]),
12074 Some(DisplayRow(0)),
12075 &snapshot,
12076 window,
12077 cx,
12078 )
12079 })
12080 .unwrap();
12081 assert!(
12082 layouts.is_empty(),
12083 "Deleted lines should have no line number"
12084 );
12085
12086 let relative_rows = window
12087 .update(cx, |editor, window, cx| {
12088 let snapshot = editor.snapshot(window, cx);
12089 snapshot.calculate_relative_line_numbers(
12090 &(DisplayRow(0)..DisplayRow(6)),
12091 DisplayRow(3),
12092 true,
12093 )
12094 })
12095 .unwrap();
12096
12097 // Deleted lines should still have relative numbers
12098 assert_eq!(relative_rows[&DisplayRow(0)], 3);
12099 assert_eq!(relative_rows[&DisplayRow(1)], 2);
12100 assert_eq!(relative_rows[&DisplayRow(2)], 1);
12101 // current line, even if deleted, has no relative number
12102 assert_eq!(relative_rows[&DisplayRow(4)], 1);
12103 assert_eq!(relative_rows[&DisplayRow(5)], 2);
12104 }
12105
12106 #[gpui::test]
12107 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
12108 init_test(cx, |_| {});
12109
12110 let window = cx.add_window(|window, cx| {
12111 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
12112 Editor::new(EditorMode::full(), buffer, None, window, cx)
12113 });
12114 let cx = &mut VisualTestContext::from_window(*window, cx);
12115 let editor = window.root(cx).unwrap();
12116 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12117
12118 window
12119 .update(cx, |editor, window, cx| {
12120 editor.cursor_offset_on_selection = true;
12121 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
12122 s.select_ranges([
12123 Point::new(0, 0)..Point::new(1, 0),
12124 Point::new(3, 2)..Point::new(3, 3),
12125 Point::new(5, 6)..Point::new(6, 0),
12126 ]);
12127 });
12128 })
12129 .unwrap();
12130
12131 let (_, state) = cx.draw(
12132 point(px(500.), px(500.)),
12133 size(px(500.), px(500.)),
12134 |_, _| EditorElement::new(&editor, style),
12135 );
12136
12137 assert_eq!(state.selections.len(), 1);
12138 let local_selections = &state.selections[0].1;
12139 assert_eq!(local_selections.len(), 3);
12140 // moves cursor back one line
12141 assert_eq!(
12142 local_selections[0].head,
12143 DisplayPoint::new(DisplayRow(0), 6)
12144 );
12145 assert_eq!(
12146 local_selections[0].range,
12147 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
12148 );
12149
12150 // moves cursor back one column
12151 assert_eq!(
12152 local_selections[1].range,
12153 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
12154 );
12155 assert_eq!(
12156 local_selections[1].head,
12157 DisplayPoint::new(DisplayRow(3), 2)
12158 );
12159
12160 // leaves cursor on the max point
12161 assert_eq!(
12162 local_selections[2].range,
12163 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
12164 );
12165 assert_eq!(
12166 local_selections[2].head,
12167 DisplayPoint::new(DisplayRow(6), 0)
12168 );
12169
12170 // active lines does not include 1 (even though the range of the selection does)
12171 assert_eq!(
12172 state.active_rows.keys().cloned().collect::<Vec<_>>(),
12173 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
12174 );
12175 }
12176
12177 #[gpui::test]
12178 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
12179 init_test(cx, |_| {});
12180
12181 let window = cx.add_window(|window, cx| {
12182 let buffer = MultiBuffer::build_simple("", cx);
12183 Editor::new(EditorMode::full(), buffer, None, window, cx)
12184 });
12185 let cx = &mut VisualTestContext::from_window(*window, cx);
12186 let editor = window.root(cx).unwrap();
12187 let style = cx.update(|_, cx| editor.update(cx, |editor, cx| editor.style(cx).clone()));
12188 window
12189 .update(cx, |editor, window, cx| {
12190 editor.set_placeholder_text("hello", window, cx);
12191 editor.insert_blocks(
12192 [BlockProperties {
12193 style: BlockStyle::Fixed,
12194 placement: BlockPlacement::Above(Anchor::min()),
12195 height: Some(3),
12196 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
12197 priority: 0,
12198 }],
12199 None,
12200 cx,
12201 );
12202
12203 // Blur the editor so that it displays placeholder text.
12204 window.blur();
12205 })
12206 .unwrap();
12207
12208 let (_, state) = cx.draw(
12209 point(px(500.), px(500.)),
12210 size(px(500.), px(500.)),
12211 |_, _| EditorElement::new(&editor, style),
12212 );
12213 assert_eq!(state.position_map.line_layouts.len(), 4);
12214 assert_eq!(state.line_numbers.len(), 1);
12215 assert_eq!(
12216 state
12217 .line_numbers
12218 .get(&MultiBufferRow(0))
12219 .map(|line_number| line_number
12220 .segments
12221 .first()
12222 .unwrap()
12223 .shaped_line
12224 .text
12225 .as_ref()),
12226 Some("1")
12227 );
12228 }
12229
12230 #[gpui::test]
12231 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
12232 const TAB_SIZE: u32 = 4;
12233
12234 let input_text = "\t \t|\t| a b";
12235 let expected_invisibles = vec![
12236 Invisible::Tab {
12237 line_start_offset: 0,
12238 line_end_offset: TAB_SIZE as usize,
12239 },
12240 Invisible::Whitespace {
12241 line_offset: TAB_SIZE as usize,
12242 },
12243 Invisible::Tab {
12244 line_start_offset: TAB_SIZE as usize + 1,
12245 line_end_offset: TAB_SIZE as usize * 2,
12246 },
12247 Invisible::Tab {
12248 line_start_offset: TAB_SIZE as usize * 2 + 1,
12249 line_end_offset: TAB_SIZE as usize * 3,
12250 },
12251 Invisible::Whitespace {
12252 line_offset: TAB_SIZE as usize * 3 + 1,
12253 },
12254 Invisible::Whitespace {
12255 line_offset: TAB_SIZE as usize * 3 + 3,
12256 },
12257 ];
12258 assert_eq!(
12259 expected_invisibles.len(),
12260 input_text
12261 .chars()
12262 .filter(|initial_char| initial_char.is_whitespace())
12263 .count(),
12264 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12265 );
12266
12267 for show_line_numbers in [true, false] {
12268 init_test(cx, |s| {
12269 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12270 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
12271 });
12272
12273 let actual_invisibles = collect_invisibles_from_new_editor(
12274 cx,
12275 EditorMode::full(),
12276 input_text,
12277 px(500.0),
12278 show_line_numbers,
12279 );
12280
12281 assert_eq!(expected_invisibles, actual_invisibles);
12282 }
12283 }
12284
12285 #[gpui::test]
12286 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
12287 init_test(cx, |s| {
12288 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12289 s.defaults.tab_size = NonZeroU32::new(4);
12290 });
12291
12292 for editor_mode_without_invisibles in [
12293 EditorMode::SingleLine,
12294 EditorMode::AutoHeight {
12295 min_lines: 1,
12296 max_lines: Some(100),
12297 },
12298 ] {
12299 for show_line_numbers in [true, false] {
12300 let invisibles = collect_invisibles_from_new_editor(
12301 cx,
12302 editor_mode_without_invisibles.clone(),
12303 "\t\t\t| | a b",
12304 px(500.0),
12305 show_line_numbers,
12306 );
12307 assert!(
12308 invisibles.is_empty(),
12309 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
12310 );
12311 }
12312 }
12313 }
12314
12315 #[gpui::test]
12316 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
12317 let tab_size = 4;
12318 let input_text = "a\tbcd ".repeat(9);
12319 let repeated_invisibles = [
12320 Invisible::Tab {
12321 line_start_offset: 1,
12322 line_end_offset: tab_size as usize,
12323 },
12324 Invisible::Whitespace {
12325 line_offset: tab_size as usize + 3,
12326 },
12327 Invisible::Whitespace {
12328 line_offset: tab_size as usize + 4,
12329 },
12330 Invisible::Whitespace {
12331 line_offset: tab_size as usize + 5,
12332 },
12333 Invisible::Whitespace {
12334 line_offset: tab_size as usize + 6,
12335 },
12336 Invisible::Whitespace {
12337 line_offset: tab_size as usize + 7,
12338 },
12339 ];
12340 let expected_invisibles = std::iter::once(repeated_invisibles)
12341 .cycle()
12342 .take(9)
12343 .flatten()
12344 .collect::<Vec<_>>();
12345 assert_eq!(
12346 expected_invisibles.len(),
12347 input_text
12348 .chars()
12349 .filter(|initial_char| initial_char.is_whitespace())
12350 .count(),
12351 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
12352 );
12353 info!("Expected invisibles: {expected_invisibles:?}");
12354
12355 init_test(cx, |_| {});
12356
12357 // Put the same string with repeating whitespace pattern into editors of various size,
12358 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
12359 let resize_step = 10.0;
12360 let mut editor_width = 200.0;
12361 while editor_width <= 1000.0 {
12362 for show_line_numbers in [true, false] {
12363 update_test_language_settings(cx, |s| {
12364 s.defaults.tab_size = NonZeroU32::new(tab_size);
12365 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
12366 s.defaults.preferred_line_length = Some(editor_width as u32);
12367 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
12368 });
12369
12370 let actual_invisibles = collect_invisibles_from_new_editor(
12371 cx,
12372 EditorMode::full(),
12373 &input_text,
12374 px(editor_width),
12375 show_line_numbers,
12376 );
12377
12378 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
12379 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
12380 let mut i = 0;
12381 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
12382 i = actual_index;
12383 match expected_invisibles.get(i) {
12384 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
12385 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
12386 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
12387 _ => {
12388 panic!(
12389 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
12390 )
12391 }
12392 },
12393 None => {
12394 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
12395 }
12396 }
12397 }
12398 let missing_expected_invisibles = &expected_invisibles[i + 1..];
12399 assert!(
12400 missing_expected_invisibles.is_empty(),
12401 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
12402 );
12403
12404 editor_width += resize_step;
12405 }
12406 }
12407 }
12408
12409 fn collect_invisibles_from_new_editor(
12410 cx: &mut TestAppContext,
12411 editor_mode: EditorMode,
12412 input_text: &str,
12413 editor_width: Pixels,
12414 show_line_numbers: bool,
12415 ) -> Vec<Invisible> {
12416 info!(
12417 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
12418 f32::from(editor_width)
12419 );
12420 let window = cx.add_window(|window, cx| {
12421 let buffer = MultiBuffer::build_simple(input_text, cx);
12422 Editor::new(editor_mode, buffer, None, window, cx)
12423 });
12424 let cx = &mut VisualTestContext::from_window(*window, cx);
12425 let editor = window.root(cx).unwrap();
12426
12427 let style = editor.update(cx, |editor, cx| editor.style(cx).clone());
12428 window
12429 .update(cx, |editor, _, cx| {
12430 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
12431 editor.set_wrap_width(Some(editor_width), cx);
12432 editor.set_show_line_numbers(show_line_numbers, cx);
12433 })
12434 .unwrap();
12435 let (_, state) = cx.draw(
12436 point(px(500.), px(500.)),
12437 size(px(500.), px(500.)),
12438 |_, _| EditorElement::new(&editor, style),
12439 );
12440 state
12441 .position_map
12442 .line_layouts
12443 .iter()
12444 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
12445 .cloned()
12446 .collect()
12447 }
12448
12449 #[gpui::test]
12450 fn test_merge_overlapping_ranges() {
12451 let base_bg = Hsla::white();
12452 let color1 = Hsla {
12453 h: 0.0,
12454 s: 0.5,
12455 l: 0.5,
12456 a: 0.5,
12457 };
12458 let color2 = Hsla {
12459 h: 120.0,
12460 s: 0.5,
12461 l: 0.5,
12462 a: 0.5,
12463 };
12464
12465 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
12466 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
12467 v.iter()
12468 .map(|(r, _)| (r.start.column(), r.end.column()))
12469 .collect()
12470 };
12471
12472 // Test overlapping ranges blend colors
12473 let overlapping = vec![
12474 (display_point(5)..display_point(15), color1),
12475 (display_point(10)..display_point(20), color2),
12476 ];
12477 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
12478 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12479
12480 // Test middle segment should have blended color
12481 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
12482 assert_eq!(result[1].1, blended);
12483
12484 // Test adjacent same-color ranges merge
12485 let adjacent_same = vec![
12486 (display_point(5)..display_point(10), color1),
12487 (display_point(10)..display_point(15), color1),
12488 ];
12489 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
12490 assert_eq!(cols(&result), vec![(5, 15)]);
12491
12492 // Test contained range splits
12493 let contained = vec![
12494 (display_point(5)..display_point(20), color1),
12495 (display_point(10)..display_point(15), color2),
12496 ];
12497 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
12498 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
12499
12500 // Test multiple overlaps split at every boundary
12501 let color3 = Hsla {
12502 h: 240.0,
12503 s: 0.5,
12504 l: 0.5,
12505 a: 0.5,
12506 };
12507 let complex = vec![
12508 (display_point(5)..display_point(12), color1),
12509 (display_point(8)..display_point(16), color2),
12510 (display_point(10)..display_point(14), color3),
12511 ];
12512 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
12513 assert_eq!(
12514 cols(&result),
12515 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
12516 );
12517 }
12518
12519 #[gpui::test]
12520 fn test_bg_segments_per_row() {
12521 let base_bg = Hsla::white();
12522
12523 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
12524 {
12525 let selection_color = Hsla {
12526 h: 200.0,
12527 s: 0.5,
12528 l: 0.5,
12529 a: 0.5,
12530 };
12531 let player_color = PlayerColor {
12532 cursor: selection_color,
12533 background: selection_color,
12534 selection: selection_color,
12535 };
12536
12537 let spanning_selection = SelectionLayout {
12538 head: DisplayPoint::new(DisplayRow(3), 7),
12539 cursor_shape: CursorShape::Bar,
12540 is_newest: true,
12541 is_local: true,
12542 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
12543 active_rows: DisplayRow(1)..DisplayRow(4),
12544 user_name: None,
12545 };
12546
12547 let selections = vec![(player_color, vec![spanning_selection])];
12548 let result = EditorElement::bg_segments_per_row(
12549 DisplayRow(0)..DisplayRow(5),
12550 &selections,
12551 &[],
12552 base_bg,
12553 );
12554
12555 assert_eq!(result.len(), 5);
12556 assert!(result[0].is_empty());
12557 assert_eq!(result[1].len(), 1);
12558 assert_eq!(result[2].len(), 1);
12559 assert_eq!(result[3].len(), 1);
12560 assert!(result[4].is_empty());
12561
12562 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12563 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12564 assert_eq!(result[1][0].0.end.column(), u32::MAX);
12565 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12566 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12567 assert_eq!(result[2][0].0.end.column(), u32::MAX);
12568 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
12569 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
12570 }
12571
12572 // Case B: selection ends exactly at the start of row 3, excluding row 3
12573 {
12574 let selection_color = Hsla {
12575 h: 120.0,
12576 s: 0.5,
12577 l: 0.5,
12578 a: 0.5,
12579 };
12580 let player_color = PlayerColor {
12581 cursor: selection_color,
12582 background: selection_color,
12583 selection: selection_color,
12584 };
12585
12586 let selection = SelectionLayout {
12587 head: DisplayPoint::new(DisplayRow(2), 0),
12588 cursor_shape: CursorShape::Bar,
12589 is_newest: true,
12590 is_local: true,
12591 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
12592 active_rows: DisplayRow(1)..DisplayRow(3),
12593 user_name: None,
12594 };
12595
12596 let selections = vec![(player_color, vec![selection])];
12597 let result = EditorElement::bg_segments_per_row(
12598 DisplayRow(0)..DisplayRow(4),
12599 &selections,
12600 &[],
12601 base_bg,
12602 );
12603
12604 assert_eq!(result.len(), 4);
12605 assert!(result[0].is_empty());
12606 assert_eq!(result[1].len(), 1);
12607 assert_eq!(result[2].len(), 1);
12608 assert!(result[3].is_empty());
12609
12610 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
12611 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
12612 assert_eq!(result[1][0].0.end.column(), u32::MAX);
12613 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
12614 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
12615 assert_eq!(result[2][0].0.end.column(), u32::MAX);
12616 }
12617 }
12618
12619 #[cfg(test)]
12620 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
12621 TextRun {
12622 len,
12623 color,
12624 ..Default::default()
12625 }
12626 }
12627
12628 #[gpui::test]
12629 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
12630 init_test(cx, |_| {});
12631
12632 let dx = |start: u32, end: u32| {
12633 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
12634 };
12635
12636 let text_color = Hsla {
12637 h: 210.0,
12638 s: 0.1,
12639 l: 0.4,
12640 a: 1.0,
12641 };
12642 let bg_1 = Hsla {
12643 h: 30.0,
12644 s: 0.6,
12645 l: 0.8,
12646 a: 1.0,
12647 };
12648 let bg_2 = Hsla {
12649 h: 200.0,
12650 s: 0.6,
12651 l: 0.2,
12652 a: 1.0,
12653 };
12654 let min_contrast = 45.0;
12655 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
12656 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
12657
12658 // Case A: single run; disjoint segments inside the run
12659 {
12660 let runs = vec![generate_test_run(20, text_color)];
12661 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
12662 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12663 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
12664 assert_eq!(
12665 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12666 vec![5, 5, 2, 4, 4]
12667 );
12668 assert_eq!(out[0].color, text_color);
12669 assert_eq!(out[1].color, adjusted_bg1);
12670 assert_eq!(out[2].color, text_color);
12671 assert_eq!(out[3].color, adjusted_bg2);
12672 assert_eq!(out[4].color, text_color);
12673 }
12674
12675 // Case B: multiple runs; segment extends to end of line (u32::MAX)
12676 {
12677 let runs = vec![
12678 generate_test_run(8, text_color),
12679 generate_test_run(7, text_color),
12680 ];
12681 let segs = vec![(dx(6, u32::MAX), bg_1)];
12682 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12683 // Expected slices across runs: [0,6) [6,8) | [0,7)
12684 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
12685 assert_eq!(out[0].color, text_color);
12686 assert_eq!(out[1].color, adjusted_bg1);
12687 assert_eq!(out[2].color, adjusted_bg1);
12688 }
12689
12690 // Case C: multi-byte characters
12691 {
12692 // for text: "Hello π δΈη!"
12693 let runs = vec![
12694 generate_test_run(5, text_color), // "Hello"
12695 generate_test_run(6, text_color), // " π "
12696 generate_test_run(6, text_color), // "δΈη"
12697 generate_test_run(1, text_color), // "!"
12698 ];
12699 // selecting "π δΈ"
12700 let segs = vec![(dx(6, 14), bg_1)];
12701 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12702 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
12703 assert_eq!(
12704 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12705 vec![5, 1, 5, 3, 3, 1]
12706 );
12707 assert_eq!(out[0].color, text_color); // "Hello"
12708 assert_eq!(out[2].color, adjusted_bg1); // "π "
12709 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
12710 assert_eq!(out[4].color, text_color); // "η"
12711 assert_eq!(out[5].color, text_color); // "!"
12712 }
12713
12714 // Case D: split multiple consecutive text runs with segments
12715 {
12716 let segs = vec![
12717 (dx(2, 4), bg_1), // selecting "cd"
12718 (dx(4, 8), bg_2), // selecting "efgh"
12719 (dx(9, 11), bg_1), // selecting "jk"
12720 (dx(12, 16), bg_2), // selecting "mnop"
12721 (dx(18, 19), bg_1), // selecting "s"
12722 ];
12723
12724 // for text: "abcdef"
12725 let runs = vec![
12726 generate_test_run(2, text_color), // ab
12727 generate_test_run(4, text_color), // cdef
12728 ];
12729 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
12730 // new splits "ab", "cd", "ef"
12731 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
12732 assert_eq!(out[0].color, text_color);
12733 assert_eq!(out[1].color, adjusted_bg1);
12734 assert_eq!(out[2].color, adjusted_bg2);
12735
12736 // for text: "ghijklmn"
12737 let runs = vec![
12738 generate_test_run(3, text_color), // ghi
12739 generate_test_run(2, text_color), // jk
12740 generate_test_run(3, text_color), // lmn
12741 ];
12742 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
12743 // new splits "gh", "i", "jk", "l", "mn"
12744 assert_eq!(
12745 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12746 vec![2, 1, 2, 1, 2]
12747 );
12748 assert_eq!(out[0].color, adjusted_bg2);
12749 assert_eq!(out[1].color, text_color);
12750 assert_eq!(out[2].color, adjusted_bg1);
12751 assert_eq!(out[3].color, text_color);
12752 assert_eq!(out[4].color, adjusted_bg2);
12753
12754 // for text: "opqrs"
12755 let runs = vec![
12756 generate_test_run(1, text_color), // o
12757 generate_test_run(4, text_color), // pqrs
12758 ];
12759 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
12760 // new splits "o", "p", "qr", "s"
12761 assert_eq!(
12762 out.iter().map(|r| r.len).collect::<Vec<_>>(),
12763 vec![1, 1, 2, 1]
12764 );
12765 assert_eq!(out[0].color, adjusted_bg2);
12766 assert_eq!(out[1].color, adjusted_bg2);
12767 assert_eq!(out[2].color, text_color);
12768 assert_eq!(out[3].color, adjusted_bg1);
12769 }
12770 }
12771}