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