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