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