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