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 editor_margins: &EditorMargins,
2886 line_height: Pixels,
2887 em_width: Pixels,
2888 text_hitbox: &Hitbox,
2889 editor_width: Pixels,
2890 scroll_width: &mut Pixels,
2891 resized_blocks: &mut HashMap<CustomBlockId, u32>,
2892 row_block_types: &mut HashMap<DisplayRow, bool>,
2893 selections: &[Selection<Point>],
2894 selected_buffer_ids: &Vec<BufferId>,
2895 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2896 sticky_header_excerpt_id: Option<ExcerptId>,
2897 window: &mut Window,
2898 cx: &mut App,
2899 ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
2900 let mut x_position = None;
2901 let mut element = match block {
2902 Block::Custom(custom) => {
2903 let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
2904 let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
2905 if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
2906 return None;
2907 }
2908 let align_to = block_start.to_display_point(snapshot);
2909 let x_and_width = |layout: &LineWithInvisibles| {
2910 Some((
2911 text_x + layout.x_for_index(align_to.column() as usize),
2912 text_x + layout.width,
2913 ))
2914 };
2915 let line_ix = align_to.row().0.checked_sub(rows.start.0);
2916 x_position =
2917 if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
2918 x_and_width(&layout)
2919 } else {
2920 x_and_width(&layout_line(
2921 align_to.row(),
2922 snapshot,
2923 &self.style,
2924 editor_width,
2925 is_row_soft_wrapped,
2926 window,
2927 cx,
2928 ))
2929 };
2930
2931 let anchor_x = x_position.unwrap().0;
2932
2933 let selected = selections
2934 .binary_search_by(|selection| {
2935 if selection.end <= block_start {
2936 Ordering::Less
2937 } else if selection.start >= block_end {
2938 Ordering::Greater
2939 } else {
2940 Ordering::Equal
2941 }
2942 })
2943 .is_ok();
2944
2945 div()
2946 .size_full()
2947 .children(
2948 (!snapshot.mode.is_minimap() || custom.render_in_minimap).then(|| {
2949 custom.render(&mut BlockContext {
2950 window,
2951 app: cx,
2952 anchor_x,
2953 margins: editor_margins,
2954 line_height,
2955 em_width,
2956 block_id,
2957 selected,
2958 max_width: text_hitbox.size.width.max(*scroll_width),
2959 editor_style: &self.style,
2960 })
2961 }),
2962 )
2963 .into_any()
2964 }
2965
2966 Block::FoldedBuffer {
2967 first_excerpt,
2968 height,
2969 ..
2970 } => {
2971 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
2972 let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
2973
2974 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
2975 result
2976 .child(self.render_buffer_header(
2977 first_excerpt,
2978 true,
2979 selected,
2980 false,
2981 jump_data,
2982 window,
2983 cx,
2984 ))
2985 .into_any_element()
2986 }
2987
2988 Block::ExcerptBoundary {
2989 excerpt,
2990 height,
2991 starts_new_buffer,
2992 ..
2993 } => {
2994 let color = cx.theme().colors().clone();
2995 let mut result = v_flex().id(block_id).w_full();
2996
2997 let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
2998
2999 if *starts_new_buffer {
3000 if sticky_header_excerpt_id != Some(excerpt.id) {
3001 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3002
3003 result = result.child(div().pr(editor_margins.right).child(
3004 self.render_buffer_header(
3005 excerpt, false, selected, false, jump_data, window, cx,
3006 ),
3007 ));
3008 } else {
3009 result =
3010 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3011 }
3012 } else {
3013 result = result.child(
3014 h_flex().relative().child(
3015 div()
3016 .top(line_height / 2.)
3017 .absolute()
3018 .w_full()
3019 .h_px()
3020 .bg(color.border_variant),
3021 ),
3022 );
3023 };
3024
3025 result.into_any()
3026 }
3027 };
3028
3029 // Discover the element's content height, then round up to the nearest multiple of line height.
3030 let preliminary_size = element.layout_as_root(
3031 size(available_width, AvailableSpace::MinContent),
3032 window,
3033 cx,
3034 );
3035 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
3036 let final_size = if preliminary_size.height == quantized_height {
3037 preliminary_size
3038 } else {
3039 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
3040 };
3041 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
3042
3043 let mut row = block_row_start;
3044 let mut x_offset = px(0.);
3045 let mut is_block = true;
3046
3047 if let BlockId::Custom(custom_block_id) = block_id {
3048 if block.has_height() {
3049 if block.place_near() {
3050 if let Some((x_target, line_width)) = x_position {
3051 let margin = em_width * 2;
3052 if line_width + final_size.width + margin
3053 < editor_width + editor_margins.gutter.full_width()
3054 && !row_block_types.contains_key(&(row - 1))
3055 && element_height_in_lines == 1
3056 {
3057 x_offset = line_width + margin;
3058 row = row - 1;
3059 is_block = false;
3060 element_height_in_lines = 0;
3061 row_block_types.insert(row, is_block);
3062 } else {
3063 let max_offset = editor_width + editor_margins.gutter.full_width()
3064 - final_size.width;
3065 let min_offset = (x_target + em_width - final_size.width)
3066 .max(editor_margins.gutter.full_width());
3067 x_offset = x_target.min(max_offset).max(min_offset);
3068 }
3069 }
3070 };
3071 if element_height_in_lines != block.height() {
3072 resized_blocks.insert(custom_block_id, element_height_in_lines);
3073 }
3074 }
3075 }
3076 for i in 0..element_height_in_lines {
3077 row_block_types.insert(row + i, is_block);
3078 }
3079
3080 Some((element, final_size, row, x_offset))
3081 }
3082
3083 fn render_buffer_header(
3084 &self,
3085 for_excerpt: &ExcerptInfo,
3086 is_folded: bool,
3087 is_selected: bool,
3088 is_sticky: bool,
3089 jump_data: JumpData,
3090 window: &mut Window,
3091 cx: &mut App,
3092 ) -> Div {
3093 let editor = self.editor.read(cx);
3094 let file_status = editor
3095 .buffer
3096 .read(cx)
3097 .all_diff_hunks_expanded()
3098 .then(|| {
3099 editor
3100 .project
3101 .as_ref()?
3102 .read(cx)
3103 .status_for_buffer_id(for_excerpt.buffer_id, cx)
3104 })
3105 .flatten();
3106
3107 let include_root = editor
3108 .project
3109 .as_ref()
3110 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
3111 .unwrap_or_default();
3112 let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
3113 let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
3114 let filename = path
3115 .as_ref()
3116 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
3117 let parent_path = path.as_ref().and_then(|path| {
3118 Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
3119 });
3120 let focus_handle = editor.focus_handle(cx);
3121 let colors = cx.theme().colors();
3122
3123 div()
3124 .p_1()
3125 .w_full()
3126 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3127 .child(
3128 h_flex()
3129 .size_full()
3130 .gap_2()
3131 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3132 .pl_0p5()
3133 .pr_5()
3134 .rounded_sm()
3135 .when(is_sticky, |el| el.shadow_md())
3136 .border_1()
3137 .map(|div| {
3138 let border_color = if is_selected
3139 && is_folded
3140 && focus_handle.contains_focused(window, cx)
3141 {
3142 colors.border_focused
3143 } else {
3144 colors.border
3145 };
3146 div.border_color(border_color)
3147 })
3148 .bg(colors.editor_subheader_background)
3149 .hover(|style| style.bg(colors.element_hover))
3150 .map(|header| {
3151 let editor = self.editor.clone();
3152 let buffer_id = for_excerpt.buffer_id;
3153 let toggle_chevron_icon =
3154 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3155 header.child(
3156 div()
3157 .hover(|style| style.bg(colors.element_selected))
3158 .rounded_xs()
3159 .child(
3160 ButtonLike::new("toggle-buffer-fold")
3161 .style(ui::ButtonStyle::Transparent)
3162 .height(px(28.).into())
3163 .width(px(28.).into())
3164 .children(toggle_chevron_icon)
3165 .tooltip({
3166 let focus_handle = focus_handle.clone();
3167 move |window, cx| {
3168 Tooltip::for_action_in(
3169 "Toggle Excerpt Fold",
3170 &ToggleFold,
3171 &focus_handle,
3172 window,
3173 cx,
3174 )
3175 }
3176 })
3177 .on_click(move |_, _, cx| {
3178 if is_folded {
3179 editor.update(cx, |editor, cx| {
3180 editor.unfold_buffer(buffer_id, cx);
3181 });
3182 } else {
3183 editor.update(cx, |editor, cx| {
3184 editor.fold_buffer(buffer_id, cx);
3185 });
3186 }
3187 }),
3188 ),
3189 )
3190 })
3191 .children(
3192 editor
3193 .addons
3194 .values()
3195 .filter_map(|addon| {
3196 addon.render_buffer_header_controls(for_excerpt, window, cx)
3197 })
3198 .take(1),
3199 )
3200 .child(
3201 h_flex()
3202 .cursor_pointer()
3203 .id("path header block")
3204 .size_full()
3205 .justify_between()
3206 .child(
3207 h_flex()
3208 .gap_2()
3209 .child(
3210 Label::new(
3211 filename
3212 .map(SharedString::from)
3213 .unwrap_or_else(|| "untitled".into()),
3214 )
3215 .single_line()
3216 .when_some(
3217 file_status,
3218 |el, status| {
3219 el.color(if status.is_conflicted() {
3220 Color::Conflict
3221 } else if status.is_modified() {
3222 Color::Modified
3223 } else if status.is_deleted() {
3224 Color::Disabled
3225 } else {
3226 Color::Created
3227 })
3228 .when(status.is_deleted(), |el| el.strikethrough())
3229 },
3230 ),
3231 )
3232 .when_some(parent_path, |then, path| {
3233 then.child(div().child(path).text_color(
3234 if file_status.is_some_and(FileStatus::is_deleted) {
3235 colors.text_disabled
3236 } else {
3237 colors.text_muted
3238 },
3239 ))
3240 }),
3241 )
3242 .when(can_open_excerpts && is_selected && path.is_some(), |el| {
3243 el.child(
3244 h_flex()
3245 .id("jump-to-file-button")
3246 .gap_2p5()
3247 .child(Label::new("Jump To File"))
3248 .children(
3249 KeyBinding::for_action_in(
3250 &OpenExcerpts,
3251 &focus_handle,
3252 window,
3253 cx,
3254 )
3255 .map(|binding| binding.into_any_element()),
3256 ),
3257 )
3258 })
3259 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
3260 .on_click(window.listener_for(&self.editor, {
3261 move |editor, e: &ClickEvent, window, cx| {
3262 editor.open_excerpts_common(
3263 Some(jump_data.clone()),
3264 e.down.modifiers.secondary(),
3265 window,
3266 cx,
3267 );
3268 }
3269 })),
3270 ),
3271 )
3272 }
3273
3274 fn render_blocks(
3275 &self,
3276 rows: Range<DisplayRow>,
3277 snapshot: &EditorSnapshot,
3278 hitbox: &Hitbox,
3279 text_hitbox: &Hitbox,
3280 editor_width: Pixels,
3281 scroll_width: &mut Pixels,
3282 editor_margins: &EditorMargins,
3283 em_width: Pixels,
3284 text_x: Pixels,
3285 line_height: Pixels,
3286 line_layouts: &mut [LineWithInvisibles],
3287 selections: &[Selection<Point>],
3288 selected_buffer_ids: &Vec<BufferId>,
3289 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3290 sticky_header_excerpt_id: Option<ExcerptId>,
3291 window: &mut Window,
3292 cx: &mut App,
3293 ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
3294 let (fixed_blocks, non_fixed_blocks) = snapshot
3295 .blocks_in_range(rows.clone())
3296 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
3297
3298 let mut focused_block = self
3299 .editor
3300 .update(cx, |editor, _| editor.take_focused_block());
3301 let mut fixed_block_max_width = Pixels::ZERO;
3302 let mut blocks = Vec::new();
3303 let mut resized_blocks = HashMap::default();
3304 let mut row_block_types = HashMap::default();
3305
3306 for (row, block) in fixed_blocks {
3307 let block_id = block.id();
3308
3309 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3310 focused_block = None;
3311 }
3312
3313 if let Some((element, element_size, row, x_offset)) = self.render_block(
3314 block,
3315 AvailableSpace::MinContent,
3316 block_id,
3317 row,
3318 snapshot,
3319 text_x,
3320 &rows,
3321 line_layouts,
3322 editor_margins,
3323 line_height,
3324 em_width,
3325 text_hitbox,
3326 editor_width,
3327 scroll_width,
3328 &mut resized_blocks,
3329 &mut row_block_types,
3330 selections,
3331 selected_buffer_ids,
3332 is_row_soft_wrapped,
3333 sticky_header_excerpt_id,
3334 window,
3335 cx,
3336 ) {
3337 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
3338 blocks.push(BlockLayout {
3339 id: block_id,
3340 x_offset,
3341 row: Some(row),
3342 element,
3343 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
3344 style: BlockStyle::Fixed,
3345 overlaps_gutter: true,
3346 is_buffer_header: block.is_buffer_header(),
3347 });
3348 }
3349 }
3350
3351 for (row, block) in non_fixed_blocks {
3352 let style = block.style();
3353 let width = match (style, block.place_near()) {
3354 (_, true) => AvailableSpace::MinContent,
3355 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
3356 (BlockStyle::Flex, _) => hitbox
3357 .size
3358 .width
3359 .max(fixed_block_max_width)
3360 .max(editor_margins.gutter.width + *scroll_width)
3361 .into(),
3362 (BlockStyle::Fixed, _) => unreachable!(),
3363 };
3364 let block_id = block.id();
3365
3366 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
3367 focused_block = None;
3368 }
3369
3370 if let Some((element, element_size, row, x_offset)) = self.render_block(
3371 block,
3372 width,
3373 block_id,
3374 row,
3375 snapshot,
3376 text_x,
3377 &rows,
3378 line_layouts,
3379 editor_margins,
3380 line_height,
3381 em_width,
3382 text_hitbox,
3383 editor_width,
3384 scroll_width,
3385 &mut resized_blocks,
3386 &mut row_block_types,
3387 selections,
3388 selected_buffer_ids,
3389 is_row_soft_wrapped,
3390 sticky_header_excerpt_id,
3391 window,
3392 cx,
3393 ) {
3394 blocks.push(BlockLayout {
3395 id: block_id,
3396 x_offset,
3397 row: Some(row),
3398 element,
3399 available_space: size(width, element_size.height.into()),
3400 style,
3401 overlaps_gutter: !block.place_near(),
3402 is_buffer_header: block.is_buffer_header(),
3403 });
3404 }
3405 }
3406
3407 if let Some(focused_block) = focused_block {
3408 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
3409 if focus_handle.is_focused(window) {
3410 if let Some(block) = snapshot.block_for_id(focused_block.id) {
3411 let style = block.style();
3412 let width = match style {
3413 BlockStyle::Fixed => AvailableSpace::MinContent,
3414 BlockStyle::Flex => AvailableSpace::Definite(
3415 hitbox
3416 .size
3417 .width
3418 .max(fixed_block_max_width)
3419 .max(editor_margins.gutter.width + *scroll_width),
3420 ),
3421 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
3422 };
3423
3424 if let Some((element, element_size, _, x_offset)) = self.render_block(
3425 &block,
3426 width,
3427 focused_block.id,
3428 rows.end,
3429 snapshot,
3430 text_x,
3431 &rows,
3432 line_layouts,
3433 editor_margins,
3434 line_height,
3435 em_width,
3436 text_hitbox,
3437 editor_width,
3438 scroll_width,
3439 &mut resized_blocks,
3440 &mut row_block_types,
3441 selections,
3442 selected_buffer_ids,
3443 is_row_soft_wrapped,
3444 sticky_header_excerpt_id,
3445 window,
3446 cx,
3447 ) {
3448 blocks.push(BlockLayout {
3449 id: block.id(),
3450 x_offset,
3451 row: None,
3452 element,
3453 available_space: size(width, element_size.height.into()),
3454 style,
3455 overlaps_gutter: true,
3456 is_buffer_header: block.is_buffer_header(),
3457 });
3458 }
3459 }
3460 }
3461 }
3462 }
3463
3464 if resized_blocks.is_empty() {
3465 *scroll_width =
3466 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
3467 Ok((blocks, row_block_types))
3468 } else {
3469 Err(resized_blocks)
3470 }
3471 }
3472
3473 fn layout_blocks(
3474 &self,
3475 blocks: &mut Vec<BlockLayout>,
3476 hitbox: &Hitbox,
3477 line_height: Pixels,
3478 scroll_pixel_position: gpui::Point<Pixels>,
3479 window: &mut Window,
3480 cx: &mut App,
3481 ) {
3482 for block in blocks {
3483 let mut origin = if let Some(row) = block.row {
3484 hitbox.origin
3485 + point(
3486 block.x_offset,
3487 row.as_f32() * line_height - scroll_pixel_position.y,
3488 )
3489 } else {
3490 // Position the block outside the visible area
3491 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
3492 };
3493
3494 if !matches!(block.style, BlockStyle::Sticky) {
3495 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
3496 }
3497
3498 let focus_handle =
3499 block
3500 .element
3501 .prepaint_as_root(origin, block.available_space, window, cx);
3502
3503 if let Some(focus_handle) = focus_handle {
3504 self.editor.update(cx, |editor, _cx| {
3505 editor.set_focused_block(FocusedBlock {
3506 id: block.id,
3507 focus_handle: focus_handle.downgrade(),
3508 });
3509 });
3510 }
3511 }
3512 }
3513
3514 fn layout_sticky_buffer_header(
3515 &self,
3516 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
3517 scroll_position: f32,
3518 line_height: Pixels,
3519 right_margin: Pixels,
3520 snapshot: &EditorSnapshot,
3521 hitbox: &Hitbox,
3522 selected_buffer_ids: &Vec<BufferId>,
3523 blocks: &[BlockLayout],
3524 window: &mut Window,
3525 cx: &mut App,
3526 ) -> AnyElement {
3527 let jump_data = header_jump_data(
3528 snapshot,
3529 DisplayRow(scroll_position as u32),
3530 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3531 excerpt,
3532 );
3533
3534 let editor_bg_color = cx.theme().colors().editor_background;
3535
3536 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3537
3538 let available_width = hitbox.bounds.size.width - right_margin;
3539
3540 let mut header = v_flex()
3541 .relative()
3542 .child(
3543 div()
3544 .w(available_width)
3545 .h(FILE_HEADER_HEIGHT as f32 * line_height)
3546 .bg(linear_gradient(
3547 0.,
3548 linear_color_stop(editor_bg_color.opacity(0.), 0.),
3549 linear_color_stop(editor_bg_color, 0.6),
3550 ))
3551 .absolute()
3552 .top_0(),
3553 )
3554 .child(
3555 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
3556 .into_any_element(),
3557 )
3558 .into_any_element();
3559
3560 let mut origin = hitbox.origin;
3561 // Move floating header up to avoid colliding with the next buffer header.
3562 for block in blocks.iter() {
3563 if !block.is_buffer_header {
3564 continue;
3565 }
3566
3567 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
3568 continue;
3569 };
3570
3571 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
3572 let offset = scroll_position - max_row as f32;
3573
3574 if offset > 0.0 {
3575 origin.y -= offset * line_height;
3576 }
3577 break;
3578 }
3579
3580 let size = size(
3581 AvailableSpace::Definite(available_width),
3582 AvailableSpace::MinContent,
3583 );
3584
3585 header.prepaint_as_root(origin, size, window, cx);
3586
3587 header
3588 }
3589
3590 fn layout_cursor_popovers(
3591 &self,
3592 line_height: Pixels,
3593 text_hitbox: &Hitbox,
3594 content_origin: gpui::Point<Pixels>,
3595 right_margin: Pixels,
3596 start_row: DisplayRow,
3597 scroll_pixel_position: gpui::Point<Pixels>,
3598 line_layouts: &[LineWithInvisibles],
3599 cursor: DisplayPoint,
3600 cursor_point: Point,
3601 style: &EditorStyle,
3602 window: &mut Window,
3603 cx: &mut App,
3604 ) {
3605 let mut min_menu_height = Pixels::ZERO;
3606 let mut max_menu_height = Pixels::ZERO;
3607 let mut height_above_menu = Pixels::ZERO;
3608 let height_below_menu = Pixels::ZERO;
3609 let mut edit_prediction_popover_visible = false;
3610 let mut context_menu_visible = false;
3611 let context_menu_placement;
3612
3613 {
3614 let editor = self.editor.read(cx);
3615 if editor
3616 .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3617 {
3618 height_above_menu +=
3619 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3620 edit_prediction_popover_visible = true;
3621 }
3622
3623 if editor.context_menu_visible() {
3624 if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3625 let (min_height_in_lines, max_height_in_lines) = editor
3626 .context_menu_options
3627 .as_ref()
3628 .map_or((3, 12), |options| {
3629 (options.min_entries_visible, options.max_entries_visible)
3630 });
3631
3632 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
3633 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
3634 context_menu_visible = true;
3635 }
3636 }
3637 context_menu_placement = editor
3638 .context_menu_options
3639 .as_ref()
3640 .and_then(|options| options.placement.clone());
3641 }
3642
3643 let visible = edit_prediction_popover_visible || context_menu_visible;
3644 if !visible {
3645 return;
3646 }
3647
3648 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3649 let target_position = content_origin
3650 + gpui::Point {
3651 x: cmp::max(
3652 px(0.),
3653 cursor_row_layout.x_for_index(cursor.column() as usize)
3654 - scroll_pixel_position.x,
3655 ),
3656 y: cmp::max(
3657 px(0.),
3658 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3659 ),
3660 };
3661
3662 let viewport_bounds =
3663 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3664 right: -right_margin - MENU_GAP,
3665 ..Default::default()
3666 });
3667
3668 let min_height = height_above_menu + min_menu_height + height_below_menu;
3669 let max_height = height_above_menu + max_menu_height + height_below_menu;
3670 let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3671 target_position,
3672 line_height,
3673 min_height,
3674 max_height,
3675 context_menu_placement,
3676 text_hitbox,
3677 viewport_bounds,
3678 window,
3679 cx,
3680 |height, max_width_for_stable_x, y_flipped, window, cx| {
3681 // First layout the menu to get its size - others can be at least this wide.
3682 let context_menu = if context_menu_visible {
3683 let menu_height = if y_flipped {
3684 height - height_below_menu
3685 } else {
3686 height - height_above_menu
3687 };
3688 let mut element = self
3689 .render_context_menu(line_height, menu_height, window, cx)
3690 .expect("Visible context menu should always render.");
3691 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3692 Some((CursorPopoverType::CodeContextMenu, element, size))
3693 } else {
3694 None
3695 };
3696 let min_width = context_menu
3697 .as_ref()
3698 .map_or(px(0.), |(_, _, size)| size.width);
3699 let max_width = max_width_for_stable_x.max(
3700 context_menu
3701 .as_ref()
3702 .map_or(px(0.), |(_, _, size)| size.width),
3703 );
3704
3705 let edit_prediction = if edit_prediction_popover_visible {
3706 self.editor.update(cx, move |editor, cx| {
3707 let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3708 let mut element = editor.render_edit_prediction_cursor_popover(
3709 min_width,
3710 max_width,
3711 cursor_point,
3712 style,
3713 accept_binding.keystroke(),
3714 window,
3715 cx,
3716 )?;
3717 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3718 Some((CursorPopoverType::EditPrediction, element, size))
3719 })
3720 } else {
3721 None
3722 };
3723 vec![edit_prediction, context_menu]
3724 .into_iter()
3725 .flatten()
3726 .collect::<Vec<_>>()
3727 },
3728 ) else {
3729 return;
3730 };
3731
3732 let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3733 .iter()
3734 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3735 else {
3736 return;
3737 };
3738 let last_ix = laid_out_popovers.len() - 1;
3739 let menu_is_last = menu_ix == last_ix;
3740 let first_popover_bounds = laid_out_popovers[0].1;
3741 let last_popover_bounds = laid_out_popovers[last_ix].1;
3742
3743 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3744 // right, and otherwise it goes below or to the right.
3745 let mut target_bounds = Bounds::from_corners(
3746 first_popover_bounds.origin,
3747 last_popover_bounds.bottom_right(),
3748 );
3749 target_bounds.size.width = menu_bounds.size.width;
3750
3751 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3752 // based on this is preferred for layout stability.
3753 let mut max_target_bounds = target_bounds;
3754 max_target_bounds.size.height = max_height;
3755 if y_flipped {
3756 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3757 }
3758
3759 // Add spacing around `target_bounds` and `max_target_bounds`.
3760 let mut extend_amount = Edges::all(MENU_GAP);
3761 if y_flipped {
3762 extend_amount.bottom = line_height;
3763 } else {
3764 extend_amount.top = line_height;
3765 }
3766 let target_bounds = target_bounds.extend(extend_amount);
3767 let max_target_bounds = max_target_bounds.extend(extend_amount);
3768
3769 let must_place_above_or_below =
3770 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3771 laid_out_popovers[menu_ix + 1..]
3772 .iter()
3773 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3774 } else {
3775 false
3776 };
3777
3778 self.layout_context_menu_aside(
3779 y_flipped,
3780 *menu_bounds,
3781 target_bounds,
3782 max_target_bounds,
3783 max_menu_height,
3784 must_place_above_or_below,
3785 text_hitbox,
3786 viewport_bounds,
3787 window,
3788 cx,
3789 );
3790 }
3791
3792 fn layout_gutter_menu(
3793 &self,
3794 line_height: Pixels,
3795 text_hitbox: &Hitbox,
3796 content_origin: gpui::Point<Pixels>,
3797 right_margin: Pixels,
3798 scroll_pixel_position: gpui::Point<Pixels>,
3799 gutter_overshoot: Pixels,
3800 window: &mut Window,
3801 cx: &mut App,
3802 ) {
3803 let editor = self.editor.read(cx);
3804 if !editor.context_menu_visible() {
3805 return;
3806 }
3807 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3808 editor.context_menu_origin()
3809 else {
3810 return;
3811 };
3812 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3813 // indicator than just a plain first column of the text field.
3814 let target_position = content_origin
3815 + gpui::Point {
3816 x: -gutter_overshoot,
3817 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3818 };
3819
3820 let (min_height_in_lines, max_height_in_lines) = editor
3821 .context_menu_options
3822 .as_ref()
3823 .map_or((3, 12), |options| {
3824 (options.min_entries_visible, options.max_entries_visible)
3825 });
3826
3827 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
3828 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
3829 let viewport_bounds =
3830 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3831 right: -right_margin - MENU_GAP,
3832 ..Default::default()
3833 });
3834 self.layout_popovers_above_or_below_line(
3835 target_position,
3836 line_height,
3837 min_height,
3838 max_height,
3839 editor
3840 .context_menu_options
3841 .as_ref()
3842 .and_then(|options| options.placement.clone()),
3843 text_hitbox,
3844 viewport_bounds,
3845 window,
3846 cx,
3847 move |height, _max_width_for_stable_x, _, window, cx| {
3848 let mut element = self
3849 .render_context_menu(line_height, height, window, cx)
3850 .expect("Visible context menu should always render.");
3851 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3852 vec![(CursorPopoverType::CodeContextMenu, element, size)]
3853 },
3854 );
3855 }
3856
3857 fn layout_popovers_above_or_below_line(
3858 &self,
3859 target_position: gpui::Point<Pixels>,
3860 line_height: Pixels,
3861 min_height: Pixels,
3862 max_height: Pixels,
3863 placement: Option<ContextMenuPlacement>,
3864 text_hitbox: &Hitbox,
3865 viewport_bounds: Bounds<Pixels>,
3866 window: &mut Window,
3867 cx: &mut App,
3868 make_sized_popovers: impl FnOnce(
3869 Pixels,
3870 Pixels,
3871 bool,
3872 &mut Window,
3873 &mut App,
3874 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3875 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3876 let text_style = TextStyleRefinement {
3877 line_height: Some(DefiniteLength::Fraction(
3878 BufferLineHeight::Comfortable.value(),
3879 )),
3880 ..Default::default()
3881 };
3882 window.with_text_style(Some(text_style), |window| {
3883 // If the max height won't fit below and there is more space above, put it above the line.
3884 let bottom_y_when_flipped = target_position.y - line_height;
3885 let available_above = bottom_y_when_flipped - text_hitbox.top();
3886 let available_below = text_hitbox.bottom() - target_position.y;
3887 let y_overflows_below = max_height > available_below;
3888 let mut y_flipped = match placement {
3889 Some(ContextMenuPlacement::Above) => true,
3890 Some(ContextMenuPlacement::Below) => false,
3891 None => y_overflows_below && available_above > available_below,
3892 };
3893 let mut height = cmp::min(
3894 max_height,
3895 if y_flipped {
3896 available_above
3897 } else {
3898 available_below
3899 },
3900 );
3901
3902 // If the min height doesn't fit within text bounds, instead fit within the window.
3903 if height < min_height {
3904 let available_above = bottom_y_when_flipped;
3905 let available_below = viewport_bounds.bottom() - target_position.y;
3906 let (y_flipped_override, height_override) = match placement {
3907 Some(ContextMenuPlacement::Above) => {
3908 (true, cmp::min(available_above, min_height))
3909 }
3910 Some(ContextMenuPlacement::Below) => {
3911 (false, cmp::min(available_below, min_height))
3912 }
3913 None => {
3914 if available_below > min_height {
3915 (false, min_height)
3916 } else if available_above > min_height {
3917 (true, min_height)
3918 } else if available_above > available_below {
3919 (true, available_above)
3920 } else {
3921 (false, available_below)
3922 }
3923 }
3924 };
3925 y_flipped = y_flipped_override;
3926 height = height_override;
3927 }
3928
3929 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3930
3931 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3932 // for very narrow windows.
3933 let popovers =
3934 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3935 if popovers.is_empty() {
3936 return None;
3937 }
3938
3939 let max_width = popovers
3940 .iter()
3941 .map(|(_, _, size)| size.width)
3942 .max()
3943 .unwrap_or_default();
3944
3945 let mut current_position = gpui::Point {
3946 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3947 // overflow. Include space for the scrollbar.
3948 x: target_position
3949 .x
3950 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3951 y: if y_flipped {
3952 bottom_y_when_flipped
3953 } else {
3954 target_position.y
3955 },
3956 };
3957
3958 let mut laid_out_popovers = popovers
3959 .into_iter()
3960 .map(|(popover_type, element, size)| {
3961 if y_flipped {
3962 current_position.y -= size.height;
3963 }
3964 let position = current_position;
3965 window.defer_draw(element, current_position, 1);
3966 if !y_flipped {
3967 current_position.y += size.height + MENU_GAP;
3968 } else {
3969 current_position.y -= MENU_GAP;
3970 }
3971 (popover_type, Bounds::new(position, size))
3972 })
3973 .collect::<Vec<_>>();
3974
3975 if y_flipped {
3976 laid_out_popovers.reverse();
3977 }
3978
3979 Some((laid_out_popovers, y_flipped))
3980 })
3981 }
3982
3983 fn layout_context_menu_aside(
3984 &self,
3985 y_flipped: bool,
3986 menu_bounds: Bounds<Pixels>,
3987 target_bounds: Bounds<Pixels>,
3988 max_target_bounds: Bounds<Pixels>,
3989 max_height: Pixels,
3990 must_place_above_or_below: bool,
3991 text_hitbox: &Hitbox,
3992 viewport_bounds: Bounds<Pixels>,
3993 window: &mut Window,
3994 cx: &mut App,
3995 ) {
3996 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3997 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3998 && !must_place_above_or_below
3999 {
4000 let max_width = cmp::min(
4001 available_within_viewport.right - px(1.),
4002 MENU_ASIDE_MAX_WIDTH,
4003 );
4004 let Some(mut aside) = self.render_context_menu_aside(
4005 size(max_width, max_height - POPOVER_Y_PADDING),
4006 window,
4007 cx,
4008 ) else {
4009 return;
4010 };
4011 aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4012 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
4013 Some((aside, right_position))
4014 } else {
4015 let max_size = size(
4016 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
4017 // won't be needed here.
4018 cmp::min(
4019 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
4020 viewport_bounds.right(),
4021 ),
4022 cmp::min(
4023 max_height,
4024 cmp::max(
4025 available_within_viewport.top,
4026 available_within_viewport.bottom,
4027 ),
4028 ) - POPOVER_Y_PADDING,
4029 );
4030 let Some(mut aside) = self.render_context_menu_aside(max_size, window, cx) else {
4031 return;
4032 };
4033 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4034
4035 let top_position = point(
4036 menu_bounds.origin.x,
4037 target_bounds.top() - actual_size.height,
4038 );
4039 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
4040
4041 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
4042 // Prefer to fit on the same side of the line as the menu, then on the other side of
4043 // the line.
4044 if !y_flipped && wanted.height < available.bottom {
4045 Some(bottom_position)
4046 } else if !y_flipped && wanted.height < available.top {
4047 Some(top_position)
4048 } else if y_flipped && wanted.height < available.top {
4049 Some(top_position)
4050 } else if y_flipped && wanted.height < available.bottom {
4051 Some(bottom_position)
4052 } else {
4053 None
4054 }
4055 };
4056
4057 // Prefer choosing a direction using max sizes rather than actual size for stability.
4058 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
4059 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
4060 let aside_position = fit_within(available_within_text, wanted)
4061 // Fallback: fit max size in window.
4062 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
4063 // Fallback: fit actual size in window.
4064 .or_else(|| fit_within(available_within_viewport, actual_size));
4065
4066 aside_position.map(|position| (aside, position))
4067 };
4068
4069 // Skip drawing if it doesn't fit anywhere.
4070 if let Some((aside, position)) = positioned_aside {
4071 window.defer_draw(aside, position, 2);
4072 }
4073 }
4074
4075 fn render_context_menu(
4076 &self,
4077 line_height: Pixels,
4078 height: Pixels,
4079 window: &mut Window,
4080 cx: &mut App,
4081 ) -> Option<AnyElement> {
4082 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
4083 self.editor.update(cx, |editor, cx| {
4084 editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
4085 })
4086 }
4087
4088 fn render_context_menu_aside(
4089 &self,
4090 max_size: Size<Pixels>,
4091 window: &mut Window,
4092 cx: &mut App,
4093 ) -> Option<AnyElement> {
4094 if max_size.width < px(100.) || max_size.height < px(12.) {
4095 None
4096 } else {
4097 self.editor.update(cx, |editor, cx| {
4098 editor.render_context_menu_aside(max_size, window, cx)
4099 })
4100 }
4101 }
4102
4103 fn layout_mouse_context_menu(
4104 &self,
4105 editor_snapshot: &EditorSnapshot,
4106 visible_range: Range<DisplayRow>,
4107 content_origin: gpui::Point<Pixels>,
4108 window: &mut Window,
4109 cx: &mut App,
4110 ) -> Option<AnyElement> {
4111 let position = self.editor.update(cx, |editor, _cx| {
4112 let visible_start_point = editor.display_to_pixel_point(
4113 DisplayPoint::new(visible_range.start, 0),
4114 editor_snapshot,
4115 window,
4116 )?;
4117 let visible_end_point = editor.display_to_pixel_point(
4118 DisplayPoint::new(visible_range.end, 0),
4119 editor_snapshot,
4120 window,
4121 )?;
4122
4123 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4124 let (source_display_point, position) = match mouse_context_menu.position {
4125 MenuPosition::PinnedToScreen(point) => (None, point),
4126 MenuPosition::PinnedToEditor { source, offset } => {
4127 let source_display_point = source.to_display_point(editor_snapshot);
4128 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
4129 let position = content_origin + source_point + offset;
4130 (Some(source_display_point), position)
4131 }
4132 };
4133
4134 let source_included = source_display_point.map_or(true, |source_display_point| {
4135 visible_range
4136 .to_inclusive()
4137 .contains(&source_display_point.row())
4138 });
4139 let position_included =
4140 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
4141 if !source_included && !position_included {
4142 None
4143 } else {
4144 Some(position)
4145 }
4146 })?;
4147
4148 let text_style = TextStyleRefinement {
4149 line_height: Some(DefiniteLength::Fraction(
4150 BufferLineHeight::Comfortable.value(),
4151 )),
4152 ..Default::default()
4153 };
4154 window.with_text_style(Some(text_style), |window| {
4155 let mut element = self.editor.update(cx, |editor, _| {
4156 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4157 let context_menu = mouse_context_menu.context_menu.clone();
4158
4159 Some(
4160 deferred(
4161 anchored()
4162 .position(position)
4163 .child(context_menu)
4164 .anchor(Corner::TopLeft)
4165 .snap_to_window_with_margin(px(8.)),
4166 )
4167 .with_priority(1)
4168 .into_any(),
4169 )
4170 })?;
4171
4172 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
4173 Some(element)
4174 })
4175 }
4176
4177 fn layout_hover_popovers(
4178 &self,
4179 snapshot: &EditorSnapshot,
4180 hitbox: &Hitbox,
4181 text_hitbox: &Hitbox,
4182 visible_display_row_range: Range<DisplayRow>,
4183 content_origin: gpui::Point<Pixels>,
4184 scroll_pixel_position: gpui::Point<Pixels>,
4185 line_layouts: &[LineWithInvisibles],
4186 line_height: Pixels,
4187 em_width: Pixels,
4188 window: &mut Window,
4189 cx: &mut App,
4190 ) {
4191 struct MeasuredHoverPopover {
4192 element: AnyElement,
4193 size: Size<Pixels>,
4194 horizontal_offset: Pixels,
4195 }
4196
4197 let max_size = size(
4198 (120. * em_width) // Default size
4199 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4200 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4201 (16. * line_height) // Default size
4202 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4203 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4204 );
4205
4206 let hover_popovers = self.editor.update(cx, |editor, cx| {
4207 editor.hover_state.render(
4208 snapshot,
4209 visible_display_row_range.clone(),
4210 max_size,
4211 window,
4212 cx,
4213 )
4214 });
4215 let Some((position, hover_popovers)) = hover_popovers else {
4216 return;
4217 };
4218
4219 // This is safe because we check on layout whether the required row is available
4220 let hovered_row_layout =
4221 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
4222
4223 // Compute Hovered Point
4224 let x =
4225 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
4226 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
4227 let hovered_point = content_origin + point(x, y);
4228
4229 let mut overall_height = Pixels::ZERO;
4230 let mut measured_hover_popovers = Vec::new();
4231 for mut hover_popover in hover_popovers {
4232 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
4233 let horizontal_offset =
4234 (text_hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
4235 .min(Pixels::ZERO);
4236
4237 overall_height += HOVER_POPOVER_GAP + size.height;
4238
4239 measured_hover_popovers.push(MeasuredHoverPopover {
4240 element: hover_popover,
4241 size,
4242 horizontal_offset,
4243 });
4244 }
4245 overall_height += HOVER_POPOVER_GAP;
4246
4247 fn draw_occluder(
4248 width: Pixels,
4249 origin: gpui::Point<Pixels>,
4250 window: &mut Window,
4251 cx: &mut App,
4252 ) {
4253 let mut occlusion = div()
4254 .size_full()
4255 .occlude()
4256 .on_mouse_move(|_, _, cx| cx.stop_propagation())
4257 .into_any_element();
4258 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4259 window.defer_draw(occlusion, origin, 2);
4260 }
4261
4262 if hovered_point.y > overall_height {
4263 // There is enough space above. Render popovers above the hovered point
4264 let mut current_y = hovered_point.y;
4265 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4266 let size = popover.size;
4267 let popover_origin = point(
4268 hovered_point.x + popover.horizontal_offset,
4269 current_y - size.height,
4270 );
4271
4272 window.defer_draw(popover.element, popover_origin, 2);
4273 if position != itertools::Position::Last {
4274 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4275 draw_occluder(size.width, origin, window, cx);
4276 }
4277
4278 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4279 }
4280 } else {
4281 // There is not enough space above. Render popovers below the hovered point
4282 let mut current_y = hovered_point.y + line_height;
4283 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4284 let size = popover.size;
4285 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4286
4287 window.defer_draw(popover.element, popover_origin, 2);
4288 if position != itertools::Position::Last {
4289 let origin = point(popover_origin.x, popover_origin.y + size.height);
4290 draw_occluder(size.width, origin, window, cx);
4291 }
4292
4293 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4294 }
4295 }
4296 }
4297
4298 fn layout_diff_hunk_controls(
4299 &self,
4300 row_range: Range<DisplayRow>,
4301 row_infos: &[RowInfo],
4302 text_hitbox: &Hitbox,
4303 position_map: &PositionMap,
4304 newest_cursor_position: Option<DisplayPoint>,
4305 line_height: Pixels,
4306 right_margin: Pixels,
4307 scroll_pixel_position: gpui::Point<Pixels>,
4308 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4309 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
4310 editor: Entity<Editor>,
4311 window: &mut Window,
4312 cx: &mut App,
4313 ) -> Vec<AnyElement> {
4314 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
4315 let point_for_position = position_map.point_for_position(window.mouse_position());
4316
4317 let mut controls = vec![];
4318
4319 let active_positions = [
4320 Some(point_for_position.previous_valid),
4321 newest_cursor_position,
4322 ];
4323
4324 for (hunk, _) in display_hunks {
4325 if let DisplayDiffHunk::Unfolded {
4326 display_row_range,
4327 multi_buffer_range,
4328 status,
4329 is_created_file,
4330 ..
4331 } = &hunk
4332 {
4333 if display_row_range.start < row_range.start
4334 || display_row_range.start >= row_range.end
4335 {
4336 continue;
4337 }
4338 if highlighted_rows
4339 .get(&display_row_range.start)
4340 .and_then(|highlight| highlight.type_id)
4341 .is_some_and(|type_id| {
4342 [
4343 TypeId::of::<ConflictsOuter>(),
4344 TypeId::of::<ConflictsOursMarker>(),
4345 TypeId::of::<ConflictsOurs>(),
4346 TypeId::of::<ConflictsTheirs>(),
4347 TypeId::of::<ConflictsTheirsMarker>(),
4348 ]
4349 .contains(&type_id)
4350 })
4351 {
4352 continue;
4353 }
4354 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4355 if row_infos[row_ix].diff_status.is_none() {
4356 continue;
4357 }
4358 if row_infos[row_ix]
4359 .diff_status
4360 .is_some_and(|status| status.is_added())
4361 && !status.is_added()
4362 {
4363 continue;
4364 }
4365 if active_positions
4366 .iter()
4367 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4368 {
4369 let y = display_row_range.start.as_f32() * line_height
4370 + text_hitbox.bounds.top()
4371 - scroll_pixel_position.y;
4372
4373 let mut element = render_diff_hunk_controls(
4374 display_row_range.start.0,
4375 status,
4376 multi_buffer_range.clone(),
4377 *is_created_file,
4378 line_height,
4379 &editor,
4380 window,
4381 cx,
4382 );
4383 let size =
4384 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
4385
4386 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
4387
4388 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
4389 element.prepaint(window, cx)
4390 });
4391 controls.push(element);
4392 }
4393 }
4394 }
4395
4396 controls
4397 }
4398
4399 fn layout_signature_help(
4400 &self,
4401 hitbox: &Hitbox,
4402 text_hitbox: &Hitbox,
4403 content_origin: gpui::Point<Pixels>,
4404 scroll_pixel_position: gpui::Point<Pixels>,
4405 newest_selection_head: Option<DisplayPoint>,
4406 start_row: DisplayRow,
4407 line_layouts: &[LineWithInvisibles],
4408 line_height: Pixels,
4409 em_width: Pixels,
4410 window: &mut Window,
4411 cx: &mut App,
4412 ) {
4413 if !self.editor.focus_handle(cx).is_focused(window) {
4414 return;
4415 }
4416 let Some(newest_selection_head) = newest_selection_head else {
4417 return;
4418 };
4419
4420 let max_size = size(
4421 (120. * em_width) // Default size
4422 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4423 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4424 (16. * line_height) // Default size
4425 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4426 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4427 );
4428
4429 let maybe_element = self.editor.update(cx, |editor, cx| {
4430 if let Some(popover) = editor.signature_help_state.popover_mut() {
4431 let element = popover.render(max_size, cx);
4432 Some(element)
4433 } else {
4434 None
4435 }
4436 });
4437 let Some(mut element) = maybe_element else {
4438 return;
4439 };
4440
4441 let selection_row = newest_selection_head.row();
4442 let Some(cursor_row_layout) = (selection_row >= start_row)
4443 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
4444 .flatten()
4445 else {
4446 return;
4447 };
4448
4449 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4450 - scroll_pixel_position.x;
4451 let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
4452 let target_point = content_origin + point(target_x, target_y);
4453
4454 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4455 let overall_height = actual_size.height + HOVER_POPOVER_GAP;
4456
4457 let popover_origin = if target_point.y > overall_height {
4458 point(target_point.x, target_point.y - actual_size.height)
4459 } else {
4460 point(
4461 target_point.x,
4462 target_point.y + line_height + HOVER_POPOVER_GAP,
4463 )
4464 };
4465
4466 let horizontal_offset = (text_hitbox.top_right().x
4467 - POPOVER_RIGHT_OFFSET
4468 - (popover_origin.x + actual_size.width))
4469 .min(Pixels::ZERO);
4470 let final_origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
4471
4472 window.defer_draw(element, final_origin, 2);
4473 }
4474
4475 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4476 window.paint_layer(layout.hitbox.bounds, |window| {
4477 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4478 let gutter_bg = cx.theme().colors().editor_gutter_background;
4479 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4480 window.paint_quad(fill(
4481 layout.position_map.text_hitbox.bounds,
4482 self.style.background,
4483 ));
4484
4485 if matches!(
4486 layout.mode,
4487 EditorMode::Full { .. } | EditorMode::Minimap { .. }
4488 ) {
4489 let show_active_line_background = match layout.mode {
4490 EditorMode::Full {
4491 show_active_line_background,
4492 ..
4493 } => show_active_line_background,
4494 EditorMode::Minimap { .. } => true,
4495 _ => false,
4496 };
4497 let mut active_rows = layout.active_rows.iter().peekable();
4498 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4499 let mut end_row = start_row.0;
4500 while active_rows
4501 .peek()
4502 .map_or(false, |(active_row, has_selection)| {
4503 active_row.0 == end_row + 1
4504 && has_selection.selection == contains_non_empty_selection.selection
4505 })
4506 {
4507 active_rows.next().unwrap();
4508 end_row += 1;
4509 }
4510
4511 if show_active_line_background && !contains_non_empty_selection.selection {
4512 let highlight_h_range =
4513 match layout.position_map.snapshot.current_line_highlight {
4514 CurrentLineHighlight::Gutter => Some(Range {
4515 start: layout.hitbox.left(),
4516 end: layout.gutter_hitbox.right(),
4517 }),
4518 CurrentLineHighlight::Line => Some(Range {
4519 start: layout.position_map.text_hitbox.bounds.left(),
4520 end: layout.position_map.text_hitbox.bounds.right(),
4521 }),
4522 CurrentLineHighlight::All => Some(Range {
4523 start: layout.hitbox.left(),
4524 end: layout.hitbox.right(),
4525 }),
4526 CurrentLineHighlight::None => None,
4527 };
4528 if let Some(range) = highlight_h_range {
4529 let active_line_bg = cx.theme().colors().editor_active_line_background;
4530 let bounds = Bounds {
4531 origin: point(
4532 range.start,
4533 layout.hitbox.origin.y
4534 + (start_row.as_f32() - scroll_top)
4535 * layout.position_map.line_height,
4536 ),
4537 size: size(
4538 range.end - range.start,
4539 layout.position_map.line_height
4540 * (end_row - start_row.0 + 1) as f32,
4541 ),
4542 };
4543 window.paint_quad(fill(bounds, active_line_bg));
4544 }
4545 }
4546 }
4547
4548 let mut paint_highlight = |highlight_row_start: DisplayRow,
4549 highlight_row_end: DisplayRow,
4550 highlight: crate::LineHighlight,
4551 edges| {
4552 let mut origin_x = layout.hitbox.left();
4553 let mut width = layout.hitbox.size.width;
4554 if !highlight.include_gutter {
4555 origin_x += layout.gutter_hitbox.size.width;
4556 width -= layout.gutter_hitbox.size.width;
4557 }
4558
4559 let origin = point(
4560 origin_x,
4561 layout.hitbox.origin.y
4562 + (highlight_row_start.as_f32() - scroll_top)
4563 * layout.position_map.line_height,
4564 );
4565 let size = size(
4566 width,
4567 layout.position_map.line_height
4568 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4569 );
4570 let mut quad = fill(Bounds { origin, size }, highlight.background);
4571 if let Some(border_color) = highlight.border {
4572 quad.border_color = border_color;
4573 quad.border_widths = edges
4574 }
4575 window.paint_quad(quad);
4576 };
4577
4578 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
4579 None;
4580 for (&new_row, &new_background) in &layout.highlighted_rows {
4581 match &mut current_paint {
4582 &mut Some((current_background, ref mut current_range, mut edges)) => {
4583 let new_range_started = current_background != new_background
4584 || current_range.end.next_row() != new_row;
4585 if new_range_started {
4586 if current_range.end.next_row() == new_row {
4587 edges.bottom = px(0.);
4588 };
4589 paint_highlight(
4590 current_range.start,
4591 current_range.end,
4592 current_background,
4593 edges,
4594 );
4595 let edges = Edges {
4596 top: if current_range.end.next_row() != new_row {
4597 px(1.)
4598 } else {
4599 px(0.)
4600 },
4601 bottom: px(1.),
4602 ..Default::default()
4603 };
4604 current_paint = Some((new_background, new_row..new_row, edges));
4605 continue;
4606 } else {
4607 current_range.end = current_range.end.next_row();
4608 }
4609 }
4610 None => {
4611 let edges = Edges {
4612 top: px(1.),
4613 bottom: px(1.),
4614 ..Default::default()
4615 };
4616 current_paint = Some((new_background, new_row..new_row, edges))
4617 }
4618 };
4619 }
4620 if let Some((color, range, edges)) = current_paint {
4621 paint_highlight(range.start, range.end, color, edges);
4622 }
4623
4624 let scroll_left =
4625 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4626
4627 for (wrap_position, active) in layout.wrap_guides.iter() {
4628 let x = (layout.position_map.text_hitbox.origin.x
4629 + *wrap_position
4630 + layout.position_map.em_width / 2.)
4631 - scroll_left;
4632
4633 let show_scrollbars = layout
4634 .scrollbars_layout
4635 .as_ref()
4636 .map_or(false, |layout| layout.visible);
4637
4638 if x < layout.position_map.text_hitbox.origin.x
4639 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4640 {
4641 continue;
4642 }
4643
4644 let color = if *active {
4645 cx.theme().colors().editor_active_wrap_guide
4646 } else {
4647 cx.theme().colors().editor_wrap_guide
4648 };
4649 window.paint_quad(fill(
4650 Bounds {
4651 origin: point(x, layout.position_map.text_hitbox.origin.y),
4652 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4653 },
4654 color,
4655 ));
4656 }
4657 }
4658 })
4659 }
4660
4661 fn paint_indent_guides(
4662 &mut self,
4663 layout: &mut EditorLayout,
4664 window: &mut Window,
4665 cx: &mut App,
4666 ) {
4667 let Some(indent_guides) = &layout.indent_guides else {
4668 return;
4669 };
4670
4671 let faded_color = |color: Hsla, alpha: f32| {
4672 let mut faded = color;
4673 faded.a = alpha;
4674 faded
4675 };
4676
4677 for indent_guide in indent_guides {
4678 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4679 let settings = indent_guide.settings;
4680
4681 // TODO fixed for now, expose them through themes later
4682 const INDENT_AWARE_ALPHA: f32 = 0.2;
4683 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4684 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4685 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4686
4687 let line_color = match (settings.coloring, indent_guide.active) {
4688 (IndentGuideColoring::Disabled, _) => None,
4689 (IndentGuideColoring::Fixed, false) => {
4690 Some(cx.theme().colors().editor_indent_guide)
4691 }
4692 (IndentGuideColoring::Fixed, true) => {
4693 Some(cx.theme().colors().editor_indent_guide_active)
4694 }
4695 (IndentGuideColoring::IndentAware, false) => {
4696 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4697 }
4698 (IndentGuideColoring::IndentAware, true) => {
4699 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4700 }
4701 };
4702
4703 let background_color = match (settings.background_coloring, indent_guide.active) {
4704 (IndentGuideBackgroundColoring::Disabled, _) => None,
4705 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4706 indent_accent_colors,
4707 INDENT_AWARE_BACKGROUND_ALPHA,
4708 )),
4709 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4710 indent_accent_colors,
4711 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4712 )),
4713 };
4714
4715 let requested_line_width = if indent_guide.active {
4716 settings.active_line_width
4717 } else {
4718 settings.line_width
4719 }
4720 .clamp(1, 10);
4721 let mut line_indicator_width = 0.;
4722 if let Some(color) = line_color {
4723 window.paint_quad(fill(
4724 Bounds {
4725 origin: indent_guide.origin,
4726 size: size(px(requested_line_width as f32), indent_guide.length),
4727 },
4728 color,
4729 ));
4730 line_indicator_width = requested_line_width as f32;
4731 }
4732
4733 if let Some(color) = background_color {
4734 let width = indent_guide.single_indent_width - px(line_indicator_width);
4735 window.paint_quad(fill(
4736 Bounds {
4737 origin: point(
4738 indent_guide.origin.x + px(line_indicator_width),
4739 indent_guide.origin.y,
4740 ),
4741 size: size(width, indent_guide.length),
4742 },
4743 color,
4744 ));
4745 }
4746 }
4747 }
4748
4749 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4750 let is_singleton = self.editor.read(cx).is_singleton(cx);
4751
4752 let line_height = layout.position_map.line_height;
4753 window.set_cursor_style(CursorStyle::Arrow, Some(&layout.gutter_hitbox));
4754
4755 for LineNumberLayout {
4756 shaped_line,
4757 hitbox,
4758 } in layout.line_numbers.values()
4759 {
4760 let Some(hitbox) = hitbox else {
4761 continue;
4762 };
4763
4764 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
4765 let color = cx.theme().colors().editor_hover_line_number;
4766
4767 let Some(line) = self
4768 .shape_line_number(shaped_line.text.clone(), color, window)
4769 .log_err()
4770 else {
4771 continue;
4772 };
4773
4774 line.paint(hitbox.origin, line_height, window, cx).log_err()
4775 } else {
4776 shaped_line
4777 .paint(hitbox.origin, line_height, window, cx)
4778 .log_err()
4779 }) else {
4780 continue;
4781 };
4782
4783 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4784 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4785 if is_singleton {
4786 window.set_cursor_style(CursorStyle::IBeam, Some(&hitbox));
4787 } else {
4788 window.set_cursor_style(CursorStyle::PointingHand, Some(&hitbox));
4789 }
4790 }
4791 }
4792
4793 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4794 if layout.display_hunks.is_empty() {
4795 return;
4796 }
4797
4798 let line_height = layout.position_map.line_height;
4799 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4800 for (hunk, hitbox) in &layout.display_hunks {
4801 let hunk_to_paint = match hunk {
4802 DisplayDiffHunk::Folded { .. } => {
4803 let hunk_bounds = Self::diff_hunk_bounds(
4804 &layout.position_map.snapshot,
4805 line_height,
4806 layout.gutter_hitbox.bounds,
4807 &hunk,
4808 );
4809 Some((
4810 hunk_bounds,
4811 cx.theme().colors().version_control_modified,
4812 Corners::all(px(0.)),
4813 DiffHunkStatus::modified_none(),
4814 ))
4815 }
4816 DisplayDiffHunk::Unfolded {
4817 status,
4818 display_row_range,
4819 ..
4820 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
4821 DiffHunkStatusKind::Added => (
4822 hunk_hitbox.bounds,
4823 cx.theme().colors().version_control_added,
4824 Corners::all(px(0.)),
4825 *status,
4826 ),
4827 DiffHunkStatusKind::Modified => (
4828 hunk_hitbox.bounds,
4829 cx.theme().colors().version_control_modified,
4830 Corners::all(px(0.)),
4831 *status,
4832 ),
4833 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
4834 hunk_hitbox.bounds,
4835 cx.theme().colors().version_control_deleted,
4836 Corners::all(px(0.)),
4837 *status,
4838 ),
4839 DiffHunkStatusKind::Deleted => (
4840 Bounds::new(
4841 point(
4842 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4843 hunk_hitbox.origin.y,
4844 ),
4845 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
4846 ),
4847 cx.theme().colors().version_control_deleted,
4848 Corners::all(1. * line_height),
4849 *status,
4850 ),
4851 }),
4852 };
4853
4854 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
4855 // Flatten the background color with the editor color to prevent
4856 // elements below transparent hunks from showing through
4857 let flattened_background_color = cx
4858 .theme()
4859 .colors()
4860 .editor_background
4861 .blend(background_color);
4862
4863 if !Self::diff_hunk_hollow(status, cx) {
4864 window.paint_quad(quad(
4865 hunk_bounds,
4866 corner_radii,
4867 flattened_background_color,
4868 Edges::default(),
4869 transparent_black(),
4870 BorderStyle::default(),
4871 ));
4872 } else {
4873 let flattened_unstaged_background_color = cx
4874 .theme()
4875 .colors()
4876 .editor_background
4877 .blend(background_color.opacity(0.3));
4878
4879 window.paint_quad(quad(
4880 hunk_bounds,
4881 corner_radii,
4882 flattened_unstaged_background_color,
4883 Edges::all(Pixels(1.0)),
4884 flattened_background_color,
4885 BorderStyle::Solid,
4886 ));
4887 }
4888 }
4889 }
4890 });
4891 }
4892
4893 fn gutter_strip_width(line_height: Pixels) -> Pixels {
4894 (0.275 * line_height).floor()
4895 }
4896
4897 fn diff_hunk_bounds(
4898 snapshot: &EditorSnapshot,
4899 line_height: Pixels,
4900 gutter_bounds: Bounds<Pixels>,
4901 hunk: &DisplayDiffHunk,
4902 ) -> Bounds<Pixels> {
4903 let scroll_position = snapshot.scroll_position();
4904 let scroll_top = scroll_position.y * line_height;
4905 let gutter_strip_width = Self::gutter_strip_width(line_height);
4906
4907 match hunk {
4908 DisplayDiffHunk::Folded { display_row, .. } => {
4909 let start_y = display_row.as_f32() * line_height - scroll_top;
4910 let end_y = start_y + line_height;
4911 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4912 let highlight_size = size(gutter_strip_width, end_y - start_y);
4913 Bounds::new(highlight_origin, highlight_size)
4914 }
4915 DisplayDiffHunk::Unfolded {
4916 display_row_range,
4917 status,
4918 ..
4919 } => {
4920 if status.is_deleted() && display_row_range.is_empty() {
4921 let row = display_row_range.start;
4922
4923 let offset = line_height / 2.;
4924 let start_y = row.as_f32() * line_height - offset - scroll_top;
4925 let end_y = start_y + line_height;
4926
4927 let width = (0.35 * line_height).floor();
4928 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4929 let highlight_size = size(width, end_y - start_y);
4930 Bounds::new(highlight_origin, highlight_size)
4931 } else {
4932 let start_row = display_row_range.start;
4933 let end_row = display_row_range.end;
4934 // If we're in a multibuffer, row range span might include an
4935 // excerpt header, so if we were to draw the marker straight away,
4936 // the hunk might include the rows of that header.
4937 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4938 // Instead, we simply check whether the range we're dealing with includes
4939 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4940 let end_row_in_current_excerpt = snapshot
4941 .blocks_in_range(start_row..end_row)
4942 .find_map(|(start_row, block)| {
4943 if matches!(block, Block::ExcerptBoundary { .. }) {
4944 Some(start_row)
4945 } else {
4946 None
4947 }
4948 })
4949 .unwrap_or(end_row);
4950
4951 let start_y = start_row.as_f32() * line_height - scroll_top;
4952 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4953
4954 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4955 let highlight_size = size(gutter_strip_width, end_y - start_y);
4956 Bounds::new(highlight_origin, highlight_size)
4957 }
4958 }
4959 }
4960 }
4961
4962 fn paint_gutter_indicators(
4963 &self,
4964 layout: &mut EditorLayout,
4965 window: &mut Window,
4966 cx: &mut App,
4967 ) {
4968 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4969 window.with_element_namespace("crease_toggles", |window| {
4970 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4971 crease_toggle.paint(window, cx);
4972 }
4973 });
4974
4975 window.with_element_namespace("expand_toggles", |window| {
4976 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
4977 expand_toggle.paint(window, cx);
4978 }
4979 });
4980
4981 for breakpoint in layout.breakpoints.iter_mut() {
4982 breakpoint.paint(window, cx);
4983 }
4984
4985 for test_indicator in layout.test_indicators.iter_mut() {
4986 test_indicator.paint(window, cx);
4987 }
4988 });
4989 }
4990
4991 fn paint_gutter_highlights(
4992 &self,
4993 layout: &mut EditorLayout,
4994 window: &mut Window,
4995 cx: &mut App,
4996 ) {
4997 for (_, hunk_hitbox) in &layout.display_hunks {
4998 if let Some(hunk_hitbox) = hunk_hitbox {
4999 if !self
5000 .editor
5001 .read(cx)
5002 .buffer()
5003 .read(cx)
5004 .all_diff_hunks_expanded()
5005 {
5006 window.set_cursor_style(CursorStyle::PointingHand, Some(hunk_hitbox));
5007 }
5008 }
5009 }
5010
5011 let show_git_gutter = layout
5012 .position_map
5013 .snapshot
5014 .show_git_diff_gutter
5015 .unwrap_or_else(|| {
5016 matches!(
5017 ProjectSettings::get_global(cx).git.git_gutter,
5018 Some(GitGutterSetting::TrackedFiles)
5019 )
5020 });
5021 if show_git_gutter {
5022 Self::paint_gutter_diff_hunks(layout, window, cx)
5023 }
5024
5025 let highlight_width = 0.275 * layout.position_map.line_height;
5026 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
5027 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5028 for (range, color) in &layout.highlighted_gutter_ranges {
5029 let start_row = if range.start.row() < layout.visible_display_row_range.start {
5030 layout.visible_display_row_range.start - DisplayRow(1)
5031 } else {
5032 range.start.row()
5033 };
5034 let end_row = if range.end.row() > layout.visible_display_row_range.end {
5035 layout.visible_display_row_range.end + DisplayRow(1)
5036 } else {
5037 range.end.row()
5038 };
5039
5040 let start_y = layout.gutter_hitbox.top()
5041 + start_row.0 as f32 * layout.position_map.line_height
5042 - layout.position_map.scroll_pixel_position.y;
5043 let end_y = layout.gutter_hitbox.top()
5044 + (end_row.0 + 1) as f32 * layout.position_map.line_height
5045 - layout.position_map.scroll_pixel_position.y;
5046 let bounds = Bounds::from_corners(
5047 point(layout.gutter_hitbox.left(), start_y),
5048 point(layout.gutter_hitbox.left() + highlight_width, end_y),
5049 );
5050 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
5051 }
5052 });
5053 }
5054
5055 fn paint_blamed_display_rows(
5056 &self,
5057 layout: &mut EditorLayout,
5058 window: &mut Window,
5059 cx: &mut App,
5060 ) {
5061 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
5062 return;
5063 };
5064
5065 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5066 for mut blame_element in blamed_display_rows.into_iter() {
5067 blame_element.paint(window, cx);
5068 }
5069 })
5070 }
5071
5072 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5073 window.with_content_mask(
5074 Some(ContentMask {
5075 bounds: layout.position_map.text_hitbox.bounds,
5076 }),
5077 |window| {
5078 let editor = self.editor.read(cx);
5079 if editor.mouse_cursor_hidden {
5080 window.set_cursor_style(CursorStyle::None, None);
5081 } else if editor
5082 .hovered_link_state
5083 .as_ref()
5084 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
5085 {
5086 window.set_cursor_style(
5087 CursorStyle::PointingHand,
5088 Some(&layout.position_map.text_hitbox),
5089 );
5090 } else {
5091 window.set_cursor_style(
5092 CursorStyle::IBeam,
5093 Some(&layout.position_map.text_hitbox),
5094 );
5095 };
5096
5097 self.paint_lines_background(layout, window, cx);
5098 let invisible_display_ranges = self.paint_highlights(layout, window);
5099 self.paint_lines(&invisible_display_ranges, layout, window, cx);
5100 self.paint_redactions(layout, window);
5101 self.paint_cursors(layout, window, cx);
5102 self.paint_inline_diagnostics(layout, window, cx);
5103 self.paint_inline_blame(layout, window, cx);
5104 self.paint_diff_hunk_controls(layout, window, cx);
5105 window.with_element_namespace("crease_trailers", |window| {
5106 for trailer in layout.crease_trailers.iter_mut().flatten() {
5107 trailer.element.paint(window, cx);
5108 }
5109 });
5110 },
5111 )
5112 }
5113
5114 fn paint_highlights(
5115 &mut self,
5116 layout: &mut EditorLayout,
5117 window: &mut Window,
5118 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
5119 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5120 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
5121 let line_end_overshoot = 0.15 * layout.position_map.line_height;
5122 for (range, color) in &layout.highlighted_ranges {
5123 self.paint_highlighted_range(
5124 range.clone(),
5125 *color,
5126 Pixels::ZERO,
5127 line_end_overshoot,
5128 layout,
5129 window,
5130 );
5131 }
5132
5133 let corner_radius = 0.15 * layout.position_map.line_height;
5134
5135 for (player_color, selections) in &layout.selections {
5136 for selection in selections.iter() {
5137 self.paint_highlighted_range(
5138 selection.range.clone(),
5139 player_color.selection,
5140 corner_radius,
5141 corner_radius * 2.,
5142 layout,
5143 window,
5144 );
5145
5146 if selection.is_local && !selection.range.is_empty() {
5147 invisible_display_ranges.push(selection.range.clone());
5148 }
5149 }
5150 }
5151 invisible_display_ranges
5152 })
5153 }
5154
5155 fn paint_lines(
5156 &mut self,
5157 invisible_display_ranges: &[Range<DisplayPoint>],
5158 layout: &mut EditorLayout,
5159 window: &mut Window,
5160 cx: &mut App,
5161 ) {
5162 let whitespace_setting = self
5163 .editor
5164 .read(cx)
5165 .buffer
5166 .read(cx)
5167 .language_settings(cx)
5168 .show_whitespaces;
5169
5170 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5171 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5172 line_with_invisibles.draw(
5173 layout,
5174 row,
5175 layout.content_origin,
5176 whitespace_setting,
5177 invisible_display_ranges,
5178 window,
5179 cx,
5180 )
5181 }
5182
5183 for line_element in &mut layout.line_elements {
5184 line_element.paint(window, cx);
5185 }
5186 }
5187
5188 fn paint_lines_background(
5189 &mut self,
5190 layout: &mut EditorLayout,
5191 window: &mut Window,
5192 cx: &mut App,
5193 ) {
5194 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
5195 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
5196 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
5197 }
5198 }
5199
5200 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
5201 if layout.redacted_ranges.is_empty() {
5202 return;
5203 }
5204
5205 let line_end_overshoot = layout.line_end_overshoot();
5206
5207 // A softer than perfect black
5208 let redaction_color = gpui::rgb(0x0e1111);
5209
5210 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5211 for range in layout.redacted_ranges.iter() {
5212 self.paint_highlighted_range(
5213 range.clone(),
5214 redaction_color.into(),
5215 Pixels::ZERO,
5216 line_end_overshoot,
5217 layout,
5218 window,
5219 );
5220 }
5221 });
5222 }
5223
5224 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5225 for cursor in &mut layout.visible_cursors {
5226 cursor.paint(layout.content_origin, window, cx);
5227 }
5228 }
5229
5230 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5231 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
5232 return;
5233 };
5234
5235 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
5236 let hitbox = &scrollbar_layout.hitbox;
5237 if scrollbars_layout.visible {
5238 let scrollbar_edges = match axis {
5239 ScrollbarAxis::Horizontal => Edges {
5240 top: Pixels::ZERO,
5241 right: Pixels::ZERO,
5242 bottom: Pixels::ZERO,
5243 left: Pixels::ZERO,
5244 },
5245 ScrollbarAxis::Vertical => Edges {
5246 top: Pixels::ZERO,
5247 right: Pixels::ZERO,
5248 bottom: Pixels::ZERO,
5249 left: ScrollbarLayout::BORDER_WIDTH,
5250 },
5251 };
5252
5253 window.paint_layer(hitbox.bounds, |window| {
5254 window.paint_quad(quad(
5255 hitbox.bounds,
5256 Corners::default(),
5257 cx.theme().colors().scrollbar_track_background,
5258 scrollbar_edges,
5259 cx.theme().colors().scrollbar_track_border,
5260 BorderStyle::Solid,
5261 ));
5262
5263 if axis == ScrollbarAxis::Vertical {
5264 let fast_markers =
5265 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5266 // Refresh slow scrollbar markers in the background. Below, we
5267 // paint whatever markers have already been computed.
5268 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5269
5270 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5271 for marker in markers.iter().chain(&fast_markers) {
5272 let mut marker = marker.clone();
5273 marker.bounds.origin += hitbox.origin;
5274 window.paint_quad(marker);
5275 }
5276 }
5277
5278 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
5279 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
5280 ScrollbarThumbState::Dragging => {
5281 cx.theme().colors().scrollbar_thumb_active_background
5282 }
5283 ScrollbarThumbState::Hovered => {
5284 cx.theme().colors().scrollbar_thumb_hover_background
5285 }
5286 ScrollbarThumbState::Idle => {
5287 cx.theme().colors().scrollbar_thumb_background
5288 }
5289 };
5290 window.paint_quad(quad(
5291 thumb_bounds,
5292 Corners::default(),
5293 scrollbar_thumb_color,
5294 scrollbar_edges,
5295 cx.theme().colors().scrollbar_thumb_border,
5296 BorderStyle::Solid,
5297 ));
5298
5299 window.set_cursor_style(CursorStyle::Arrow, Some(&hitbox));
5300 }
5301 })
5302 }
5303 }
5304
5305 window.on_mouse_event({
5306 let editor = self.editor.clone();
5307 let scrollbars_layout = scrollbars_layout.clone();
5308
5309 let mut mouse_position = window.mouse_position();
5310 move |event: &MouseMoveEvent, phase, window, cx| {
5311 if phase == DispatchPhase::Capture {
5312 return;
5313 }
5314
5315 editor.update(cx, |editor, cx| {
5316 if let Some((scrollbar_layout, axis)) = event
5317 .pressed_button
5318 .filter(|button| *button == MouseButton::Left)
5319 .and(editor.scroll_manager.dragging_scrollbar_axis())
5320 .and_then(|axis| {
5321 scrollbars_layout
5322 .iter_scrollbars()
5323 .find(|(_, a)| *a == axis)
5324 })
5325 {
5326 let ScrollbarLayout {
5327 hitbox,
5328 text_unit_size,
5329 ..
5330 } = scrollbar_layout;
5331
5332 let old_position = mouse_position.along(axis);
5333 let new_position = event.position.along(axis);
5334 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
5335 .contains(&old_position)
5336 {
5337 let position = editor.scroll_position(cx).apply_along(axis, |p| {
5338 (p + (new_position - old_position) / *text_unit_size).max(0.)
5339 });
5340 editor.set_scroll_position(position, window, cx);
5341 }
5342
5343 editor.scroll_manager.show_scrollbars(window, cx);
5344 cx.stop_propagation();
5345 } else if let Some((layout, axis)) = scrollbars_layout.get_hovered_axis(window)
5346 {
5347 if layout
5348 .thumb_bounds
5349 .is_some_and(|bounds| bounds.contains(&event.position))
5350 {
5351 editor
5352 .scroll_manager
5353 .set_hovered_scroll_thumb_axis(axis, cx);
5354 } else {
5355 editor.scroll_manager.reset_scrollbar_state(cx);
5356 }
5357
5358 editor.scroll_manager.show_scrollbars(window, cx);
5359 } else {
5360 editor.scroll_manager.reset_scrollbar_state(cx);
5361 }
5362
5363 mouse_position = event.position;
5364 })
5365 }
5366 });
5367
5368 if self.editor.read(cx).scroll_manager.any_scrollbar_dragged() {
5369 window.on_mouse_event({
5370 let editor = self.editor.clone();
5371 move |_: &MouseUpEvent, phase, window, cx| {
5372 if phase == DispatchPhase::Capture {
5373 return;
5374 }
5375
5376 editor.update(cx, |editor, cx| {
5377 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
5378 editor
5379 .scroll_manager
5380 .set_hovered_scroll_thumb_axis(axis, cx);
5381 } else {
5382 editor.scroll_manager.reset_scrollbar_state(cx);
5383 }
5384 cx.stop_propagation();
5385 });
5386 }
5387 });
5388 } else {
5389 window.on_mouse_event({
5390 let editor = self.editor.clone();
5391
5392 move |event: &MouseDownEvent, phase, window, cx| {
5393 if phase == DispatchPhase::Capture {
5394 return;
5395 }
5396 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
5397 else {
5398 return;
5399 };
5400
5401 let ScrollbarLayout {
5402 hitbox,
5403 visible_range,
5404 text_unit_size,
5405 thumb_bounds,
5406 ..
5407 } = scrollbar_layout;
5408
5409 let Some(thumb_bounds) = thumb_bounds else {
5410 return;
5411 };
5412
5413 editor.update(cx, |editor, cx| {
5414 editor
5415 .scroll_manager
5416 .set_dragged_scroll_thumb_axis(axis, cx);
5417
5418 let event_position = event.position.along(axis);
5419
5420 if event_position < thumb_bounds.origin.along(axis)
5421 || thumb_bounds.bottom_right().along(axis) < event_position
5422 {
5423 let center_position = ((event_position - hitbox.origin.along(axis))
5424 / *text_unit_size)
5425 .round() as u32;
5426 let start_position = center_position.saturating_sub(
5427 (visible_range.end - visible_range.start) as u32 / 2,
5428 );
5429
5430 let position = editor
5431 .scroll_position(cx)
5432 .apply_along(axis, |_| start_position as f32);
5433
5434 editor.set_scroll_position(position, window, cx);
5435 } else {
5436 editor.scroll_manager.show_scrollbars(window, cx);
5437 }
5438
5439 cx.stop_propagation();
5440 });
5441 }
5442 });
5443 }
5444 }
5445
5446 fn collect_fast_scrollbar_markers(
5447 &self,
5448 layout: &EditorLayout,
5449 scrollbar_layout: &ScrollbarLayout,
5450 cx: &mut App,
5451 ) -> Vec<PaintQuad> {
5452 const LIMIT: usize = 100;
5453 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5454 return vec![];
5455 }
5456 let cursor_ranges = layout
5457 .cursors
5458 .iter()
5459 .map(|(point, color)| ColoredRange {
5460 start: point.row(),
5461 end: point.row(),
5462 color: *color,
5463 })
5464 .collect_vec();
5465 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5466 }
5467
5468 fn refresh_slow_scrollbar_markers(
5469 &self,
5470 layout: &EditorLayout,
5471 scrollbar_layout: &ScrollbarLayout,
5472 window: &mut Window,
5473 cx: &mut App,
5474 ) {
5475 self.editor.update(cx, |editor, cx| {
5476 if !editor.is_singleton(cx)
5477 || !editor
5478 .scrollbar_marker_state
5479 .should_refresh(scrollbar_layout.hitbox.size)
5480 {
5481 return;
5482 }
5483
5484 let scrollbar_layout = scrollbar_layout.clone();
5485 let background_highlights = editor.background_highlights.clone();
5486 let snapshot = layout.position_map.snapshot.clone();
5487 let theme = cx.theme().clone();
5488 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5489
5490 editor.scrollbar_marker_state.dirty = false;
5491 editor.scrollbar_marker_state.pending_refresh =
5492 Some(cx.spawn_in(window, async move |editor, cx| {
5493 let scrollbar_size = scrollbar_layout.hitbox.size;
5494 let scrollbar_markers = cx
5495 .background_spawn(async move {
5496 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5497 let mut marker_quads = Vec::new();
5498 if scrollbar_settings.git_diff {
5499 let marker_row_ranges =
5500 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5501 let start_display_row =
5502 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5503 .to_display_point(&snapshot.display_snapshot)
5504 .row();
5505 let mut end_display_row =
5506 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5507 .to_display_point(&snapshot.display_snapshot)
5508 .row();
5509 if end_display_row != start_display_row {
5510 end_display_row.0 -= 1;
5511 }
5512 let color = match &hunk.status().kind {
5513 DiffHunkStatusKind::Added => {
5514 theme.colors().version_control_added
5515 }
5516 DiffHunkStatusKind::Modified => {
5517 theme.colors().version_control_modified
5518 }
5519 DiffHunkStatusKind::Deleted => {
5520 theme.colors().version_control_deleted
5521 }
5522 };
5523 ColoredRange {
5524 start: start_display_row,
5525 end: end_display_row,
5526 color,
5527 }
5528 });
5529
5530 marker_quads.extend(
5531 scrollbar_layout
5532 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5533 );
5534 }
5535
5536 for (background_highlight_id, (_, background_ranges)) in
5537 background_highlights.iter()
5538 {
5539 let is_search_highlights = *background_highlight_id
5540 == TypeId::of::<BufferSearchHighlights>();
5541 let is_text_highlights = *background_highlight_id
5542 == TypeId::of::<SelectedTextHighlight>();
5543 let is_symbol_occurrences = *background_highlight_id
5544 == TypeId::of::<DocumentHighlightRead>()
5545 || *background_highlight_id
5546 == TypeId::of::<DocumentHighlightWrite>();
5547 if (is_search_highlights && scrollbar_settings.search_results)
5548 || (is_text_highlights && scrollbar_settings.selected_text)
5549 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5550 {
5551 let mut color = theme.status().info;
5552 if is_symbol_occurrences {
5553 color.fade_out(0.5);
5554 }
5555 let marker_row_ranges = background_ranges.iter().map(|range| {
5556 let display_start = range
5557 .start
5558 .to_display_point(&snapshot.display_snapshot);
5559 let display_end =
5560 range.end.to_display_point(&snapshot.display_snapshot);
5561 ColoredRange {
5562 start: display_start.row(),
5563 end: display_end.row(),
5564 color,
5565 }
5566 });
5567 marker_quads.extend(
5568 scrollbar_layout
5569 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5570 );
5571 }
5572 }
5573
5574 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5575 let diagnostics = snapshot
5576 .buffer_snapshot
5577 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5578 // Don't show diagnostics the user doesn't care about
5579 .filter(|diagnostic| {
5580 match (
5581 scrollbar_settings.diagnostics,
5582 diagnostic.diagnostic.severity,
5583 ) {
5584 (ScrollbarDiagnostics::All, _) => true,
5585 (
5586 ScrollbarDiagnostics::Error,
5587 lsp::DiagnosticSeverity::ERROR,
5588 ) => true,
5589 (
5590 ScrollbarDiagnostics::Warning,
5591 lsp::DiagnosticSeverity::ERROR
5592 | lsp::DiagnosticSeverity::WARNING,
5593 ) => true,
5594 (
5595 ScrollbarDiagnostics::Information,
5596 lsp::DiagnosticSeverity::ERROR
5597 | lsp::DiagnosticSeverity::WARNING
5598 | lsp::DiagnosticSeverity::INFORMATION,
5599 ) => true,
5600 (_, _) => false,
5601 }
5602 })
5603 // We want to sort by severity, in order to paint the most severe diagnostics last.
5604 .sorted_by_key(|diagnostic| {
5605 std::cmp::Reverse(diagnostic.diagnostic.severity)
5606 });
5607
5608 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5609 let start_display = diagnostic
5610 .range
5611 .start
5612 .to_display_point(&snapshot.display_snapshot);
5613 let end_display = diagnostic
5614 .range
5615 .end
5616 .to_display_point(&snapshot.display_snapshot);
5617 let color = match diagnostic.diagnostic.severity {
5618 lsp::DiagnosticSeverity::ERROR => theme.status().error,
5619 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
5620 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
5621 _ => theme.status().hint,
5622 };
5623 ColoredRange {
5624 start: start_display.row(),
5625 end: end_display.row(),
5626 color,
5627 }
5628 });
5629 marker_quads.extend(
5630 scrollbar_layout
5631 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5632 );
5633 }
5634
5635 Arc::from(marker_quads)
5636 })
5637 .await;
5638
5639 editor.update(cx, |editor, cx| {
5640 editor.scrollbar_marker_state.markers = scrollbar_markers;
5641 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5642 editor.scrollbar_marker_state.pending_refresh = None;
5643 cx.notify();
5644 })?;
5645
5646 Ok(())
5647 }));
5648 });
5649 }
5650
5651 fn paint_highlighted_range(
5652 &self,
5653 range: Range<DisplayPoint>,
5654 color: Hsla,
5655 corner_radius: Pixels,
5656 line_end_overshoot: Pixels,
5657 layout: &EditorLayout,
5658 window: &mut Window,
5659 ) {
5660 let start_row = layout.visible_display_row_range.start;
5661 let end_row = layout.visible_display_row_range.end;
5662 if range.start != range.end {
5663 let row_range = if range.end.column() == 0 {
5664 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5665 } else {
5666 cmp::max(range.start.row(), start_row)
5667 ..cmp::min(range.end.row().next_row(), end_row)
5668 };
5669
5670 let highlighted_range = HighlightedRange {
5671 color,
5672 line_height: layout.position_map.line_height,
5673 corner_radius,
5674 start_y: layout.content_origin.y
5675 + row_range.start.as_f32() * layout.position_map.line_height
5676 - layout.position_map.scroll_pixel_position.y,
5677 lines: row_range
5678 .iter_rows()
5679 .map(|row| {
5680 let line_layout =
5681 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5682 HighlightedRangeLine {
5683 start_x: if row == range.start.row() {
5684 layout.content_origin.x
5685 + line_layout.x_for_index(range.start.column() as usize)
5686 - layout.position_map.scroll_pixel_position.x
5687 } else {
5688 layout.content_origin.x
5689 - layout.position_map.scroll_pixel_position.x
5690 },
5691 end_x: if row == range.end.row() {
5692 layout.content_origin.x
5693 + line_layout.x_for_index(range.end.column() as usize)
5694 - layout.position_map.scroll_pixel_position.x
5695 } else {
5696 layout.content_origin.x + line_layout.width + line_end_overshoot
5697 - layout.position_map.scroll_pixel_position.x
5698 },
5699 }
5700 })
5701 .collect(),
5702 };
5703
5704 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5705 }
5706 }
5707
5708 fn paint_inline_diagnostics(
5709 &mut self,
5710 layout: &mut EditorLayout,
5711 window: &mut Window,
5712 cx: &mut App,
5713 ) {
5714 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
5715 inline_diagnostic.1.paint(window, cx);
5716 }
5717 }
5718
5719 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5720 if let Some(mut inline_blame) = layout.inline_blame.take() {
5721 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5722 inline_blame.paint(window, cx);
5723 })
5724 }
5725 }
5726
5727 fn paint_diff_hunk_controls(
5728 &mut self,
5729 layout: &mut EditorLayout,
5730 window: &mut Window,
5731 cx: &mut App,
5732 ) {
5733 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5734 diff_hunk_control.paint(window, cx);
5735 }
5736 }
5737
5738 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5739 if let Some(mut layout) = layout.minimap.take() {
5740 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
5741
5742 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
5743 window.with_element_namespace("minimap", |window| {
5744 layout.minimap.paint(window, cx);
5745 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
5746 let minimap_thumb_border = match layout.thumb_border_style {
5747 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
5748 MinimapThumbBorder::LeftOnly => Edges {
5749 left: ScrollbarLayout::BORDER_WIDTH,
5750 ..Default::default()
5751 },
5752 MinimapThumbBorder::LeftOpen => Edges {
5753 right: ScrollbarLayout::BORDER_WIDTH,
5754 top: ScrollbarLayout::BORDER_WIDTH,
5755 bottom: ScrollbarLayout::BORDER_WIDTH,
5756 ..Default::default()
5757 },
5758 MinimapThumbBorder::RightOpen => Edges {
5759 left: ScrollbarLayout::BORDER_WIDTH,
5760 top: ScrollbarLayout::BORDER_WIDTH,
5761 bottom: ScrollbarLayout::BORDER_WIDTH,
5762 ..Default::default()
5763 },
5764 MinimapThumbBorder::None => Default::default(),
5765 };
5766
5767 window.paint_layer(minimap_hitbox.bounds, |window| {
5768 window.paint_quad(quad(
5769 thumb_bounds,
5770 Corners::default(),
5771 cx.theme().colors().scrollbar_thumb_background,
5772 minimap_thumb_border,
5773 cx.theme().colors().scrollbar_thumb_border,
5774 BorderStyle::Solid,
5775 ));
5776 });
5777 }
5778 });
5779 });
5780
5781 window.set_cursor_style(CursorStyle::Arrow, Some(&minimap_hitbox));
5782
5783 let minimap_axis = ScrollbarAxis::Vertical;
5784 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
5785 .min(layout.minimap_line_height);
5786
5787 let mut mouse_position = window.mouse_position();
5788
5789 window.on_mouse_event({
5790 let editor = self.editor.clone();
5791
5792 let minimap_hitbox = minimap_hitbox.clone();
5793
5794 move |event: &MouseMoveEvent, phase, window, cx| {
5795 if phase == DispatchPhase::Capture {
5796 return;
5797 }
5798
5799 editor.update(cx, |editor, cx| {
5800 if event.pressed_button == Some(MouseButton::Left)
5801 && editor.scroll_manager.is_dragging_minimap()
5802 {
5803 let old_position = mouse_position.along(minimap_axis);
5804 let new_position = event.position.along(minimap_axis);
5805 if (minimap_hitbox.origin.along(minimap_axis)
5806 ..minimap_hitbox.bottom_right().along(minimap_axis))
5807 .contains(&old_position)
5808 {
5809 let position =
5810 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
5811 (p + (new_position - old_position) / pixels_per_line)
5812 .max(0.)
5813 });
5814 editor.set_scroll_position(position, window, cx);
5815 }
5816 cx.stop_propagation();
5817 } else {
5818 editor.scroll_manager.set_is_dragging_minimap(false, cx);
5819
5820 if minimap_hitbox.is_hovered(window) {
5821 editor.scroll_manager.show_minimap_thumb(cx);
5822
5823 // Stop hover events from propagating to the
5824 // underlying editor if the minimap hitbox is hovered
5825 if !event.dragging() {
5826 cx.stop_propagation();
5827 }
5828 } else {
5829 editor.scroll_manager.hide_minimap_thumb(cx);
5830 }
5831 }
5832 mouse_position = event.position;
5833 });
5834 }
5835 });
5836
5837 if self.editor.read(cx).scroll_manager.is_dragging_minimap() {
5838 window.on_mouse_event({
5839 let editor = self.editor.clone();
5840 move |_: &MouseUpEvent, phase, _, cx| {
5841 if phase == DispatchPhase::Capture {
5842 return;
5843 }
5844
5845 editor.update(cx, |editor, cx| {
5846 editor.scroll_manager.set_is_dragging_minimap(false, cx);
5847 cx.stop_propagation();
5848 });
5849 }
5850 });
5851 } else {
5852 window.on_mouse_event({
5853 let editor = self.editor.clone();
5854
5855 move |event: &MouseDownEvent, phase, window, cx| {
5856 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
5857 return;
5858 }
5859
5860 let event_position = event.position;
5861
5862 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
5863 return;
5864 };
5865
5866 editor.update(cx, |editor, cx| {
5867 if !thumb_bounds.contains(&event_position) {
5868 let click_position =
5869 event_position.relative_to(&minimap_hitbox.origin).y;
5870
5871 let top_position = (click_position
5872 - thumb_bounds.size.along(minimap_axis) / 2.0)
5873 .max(Pixels::ZERO);
5874
5875 let scroll_offset = (layout.minimap_scroll_top
5876 + top_position / layout.minimap_line_height)
5877 .min(layout.max_scroll_top);
5878
5879 let scroll_position = editor
5880 .scroll_position(cx)
5881 .apply_along(minimap_axis, |_| scroll_offset);
5882 editor.set_scroll_position(scroll_position, window, cx);
5883 }
5884
5885 editor.scroll_manager.set_is_dragging_minimap(true, cx);
5886 cx.stop_propagation();
5887 });
5888 }
5889 });
5890 }
5891 }
5892 }
5893
5894 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5895 for mut block in layout.blocks.drain(..) {
5896 if block.overlaps_gutter {
5897 block.element.paint(window, cx);
5898 } else {
5899 let mut bounds = layout.hitbox.bounds;
5900 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
5901 window.with_content_mask(Some(ContentMask { bounds }), |window| {
5902 block.element.paint(window, cx);
5903 })
5904 }
5905 }
5906 }
5907
5908 fn paint_inline_completion_popover(
5909 &mut self,
5910 layout: &mut EditorLayout,
5911 window: &mut Window,
5912 cx: &mut App,
5913 ) {
5914 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5915 inline_completion_popover.paint(window, cx);
5916 }
5917 }
5918
5919 fn paint_mouse_context_menu(
5920 &mut self,
5921 layout: &mut EditorLayout,
5922 window: &mut Window,
5923 cx: &mut App,
5924 ) {
5925 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5926 mouse_context_menu.paint(window, cx);
5927 }
5928 }
5929
5930 fn paint_scroll_wheel_listener(
5931 &mut self,
5932 layout: &EditorLayout,
5933 window: &mut Window,
5934 cx: &mut App,
5935 ) {
5936 window.on_mouse_event({
5937 let position_map = layout.position_map.clone();
5938 let editor = self.editor.clone();
5939 let hitbox = layout.hitbox.clone();
5940 let mut delta = ScrollDelta::default();
5941
5942 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5943 // accidentally turn off their scrolling.
5944 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5945
5946 move |event: &ScrollWheelEvent, phase, window, cx| {
5947 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5948 delta = delta.coalesce(event.delta);
5949 editor.update(cx, |editor, cx| {
5950 let position_map: &PositionMap = &position_map;
5951
5952 let line_height = position_map.line_height;
5953 let max_glyph_width = position_map.em_width;
5954 let (delta, axis) = match delta {
5955 gpui::ScrollDelta::Pixels(mut pixels) => {
5956 //Trackpad
5957 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5958 (pixels, axis)
5959 }
5960
5961 gpui::ScrollDelta::Lines(lines) => {
5962 //Not trackpad
5963 let pixels =
5964 point(lines.x * max_glyph_width, lines.y * line_height);
5965 (pixels, None)
5966 }
5967 };
5968
5969 let current_scroll_position = position_map.snapshot.scroll_position();
5970 let x = (current_scroll_position.x * max_glyph_width
5971 - (delta.x * scroll_sensitivity))
5972 / max_glyph_width;
5973 let y = (current_scroll_position.y * line_height
5974 - (delta.y * scroll_sensitivity))
5975 / line_height;
5976 let mut scroll_position =
5977 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5978 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5979 if forbid_vertical_scroll {
5980 scroll_position.y = current_scroll_position.y;
5981 }
5982
5983 if scroll_position != current_scroll_position {
5984 editor.scroll(scroll_position, axis, window, cx);
5985 cx.stop_propagation();
5986 } else if y < 0. {
5987 // Due to clamping, we may fail to detect cases of overscroll to the top;
5988 // We want the scroll manager to get an update in such cases and detect the change of direction
5989 // on the next frame.
5990 cx.notify();
5991 }
5992 });
5993 }
5994 }
5995 });
5996 }
5997
5998 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5999 if self.editor.read(cx).mode.is_minimap() {
6000 return;
6001 }
6002
6003 self.paint_scroll_wheel_listener(layout, window, cx);
6004
6005 window.on_mouse_event({
6006 let position_map = layout.position_map.clone();
6007 let editor = self.editor.clone();
6008 let diff_hunk_range =
6009 layout
6010 .display_hunks
6011 .iter()
6012 .find_map(|(hunk, hunk_hitbox)| match hunk {
6013 DisplayDiffHunk::Folded { .. } => None,
6014 DisplayDiffHunk::Unfolded {
6015 multi_buffer_range, ..
6016 } => {
6017 if hunk_hitbox
6018 .as_ref()
6019 .map(|hitbox| hitbox.is_hovered(window))
6020 .unwrap_or(false)
6021 {
6022 Some(multi_buffer_range.clone())
6023 } else {
6024 None
6025 }
6026 }
6027 });
6028 let line_numbers = layout.line_numbers.clone();
6029
6030 move |event: &MouseDownEvent, phase, window, cx| {
6031 if phase == DispatchPhase::Bubble {
6032 match event.button {
6033 MouseButton::Left => editor.update(cx, |editor, cx| {
6034 let pending_mouse_down = editor
6035 .pending_mouse_down
6036 .get_or_insert_with(Default::default)
6037 .clone();
6038
6039 *pending_mouse_down.borrow_mut() = Some(event.clone());
6040
6041 Self::mouse_left_down(
6042 editor,
6043 event,
6044 diff_hunk_range.clone(),
6045 &position_map,
6046 line_numbers.as_ref(),
6047 window,
6048 cx,
6049 );
6050 }),
6051 MouseButton::Right => editor.update(cx, |editor, cx| {
6052 Self::mouse_right_down(editor, event, &position_map, window, cx);
6053 }),
6054 MouseButton::Middle => editor.update(cx, |editor, cx| {
6055 Self::mouse_middle_down(editor, event, &position_map, window, cx);
6056 }),
6057 _ => {}
6058 };
6059 }
6060 }
6061 });
6062
6063 window.on_mouse_event({
6064 let editor = self.editor.clone();
6065 let position_map = layout.position_map.clone();
6066
6067 move |event: &MouseUpEvent, phase, window, cx| {
6068 if phase == DispatchPhase::Bubble {
6069 editor.update(cx, |editor, cx| {
6070 Self::mouse_up(editor, event, &position_map, window, cx)
6071 });
6072 }
6073 }
6074 });
6075
6076 window.on_mouse_event({
6077 let editor = self.editor.clone();
6078 let position_map = layout.position_map.clone();
6079 let mut captured_mouse_down = None;
6080
6081 move |event: &MouseUpEvent, phase, window, cx| match phase {
6082 // Clear the pending mouse down during the capture phase,
6083 // so that it happens even if another event handler stops
6084 // propagation.
6085 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
6086 let pending_mouse_down = editor
6087 .pending_mouse_down
6088 .get_or_insert_with(Default::default)
6089 .clone();
6090
6091 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
6092 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
6093 captured_mouse_down = pending_mouse_down.take();
6094 window.refresh();
6095 }
6096 }),
6097 // Fire click handlers during the bubble phase.
6098 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
6099 if let Some(mouse_down) = captured_mouse_down.take() {
6100 let event = ClickEvent {
6101 down: mouse_down,
6102 up: event.clone(),
6103 };
6104 Self::click(editor, &event, &position_map, window, cx);
6105 }
6106 }),
6107 }
6108 });
6109
6110 window.on_mouse_event({
6111 let position_map = layout.position_map.clone();
6112 let editor = self.editor.clone();
6113
6114 move |event: &MouseMoveEvent, phase, window, cx| {
6115 if phase == DispatchPhase::Bubble {
6116 editor.update(cx, |editor, cx| {
6117 if editor.hover_state.focused(window, cx) {
6118 return;
6119 }
6120 if event.pressed_button == Some(MouseButton::Left)
6121 || event.pressed_button == Some(MouseButton::Middle)
6122 {
6123 Self::mouse_dragged(editor, event, &position_map, window, cx)
6124 }
6125
6126 Self::mouse_moved(editor, event, &position_map, window, cx)
6127 });
6128 }
6129 }
6130 });
6131 }
6132
6133 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
6134 bounds.top_right().x - self.style.scrollbar_width
6135 }
6136
6137 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
6138 let style = &self.style;
6139 let font_size = style.text.font_size.to_pixels(window.rem_size());
6140 let layout = window
6141 .text_system()
6142 .shape_line(
6143 SharedString::from(" ".repeat(column)),
6144 font_size,
6145 &[TextRun {
6146 len: column,
6147 font: style.text.font(),
6148 color: Hsla::default(),
6149 background_color: None,
6150 underline: None,
6151 strikethrough: None,
6152 }],
6153 )
6154 .unwrap();
6155
6156 layout.width
6157 }
6158
6159 fn max_line_number_width(
6160 &self,
6161 snapshot: &EditorSnapshot,
6162 window: &mut Window,
6163 cx: &mut App,
6164 ) -> Pixels {
6165 let digit_count = snapshot.widest_line_number().ilog10() + 1;
6166 self.column_pixels(digit_count as usize, window, cx)
6167 }
6168
6169 fn shape_line_number(
6170 &self,
6171 text: SharedString,
6172 color: Hsla,
6173 window: &mut Window,
6174 ) -> anyhow::Result<ShapedLine> {
6175 let run = TextRun {
6176 len: text.len(),
6177 font: self.style.text.font(),
6178 color,
6179 background_color: None,
6180 underline: None,
6181 strikethrough: None,
6182 };
6183 window.text_system().shape_line(
6184 text,
6185 self.style.text.font_size.to_pixels(window.rem_size()),
6186 &[run],
6187 )
6188 }
6189
6190 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
6191 let unstaged = status.has_secondary_hunk();
6192 let unstaged_hollow = ProjectSettings::get_global(cx)
6193 .git
6194 .hunk_style
6195 .map_or(false, |style| {
6196 matches!(style, GitHunkStyleSetting::UnstagedHollow)
6197 });
6198
6199 unstaged == unstaged_hollow
6200 }
6201}
6202
6203fn header_jump_data(
6204 snapshot: &EditorSnapshot,
6205 block_row_start: DisplayRow,
6206 height: u32,
6207 for_excerpt: &ExcerptInfo,
6208) -> JumpData {
6209 let range = &for_excerpt.range;
6210 let buffer = &for_excerpt.buffer;
6211 let jump_anchor = range.primary.start;
6212
6213 let excerpt_start = range.context.start;
6214 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
6215 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
6216 0
6217 } else {
6218 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
6219 jump_position.row.saturating_sub(excerpt_start_point.row)
6220 };
6221
6222 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
6223 .saturating_sub(
6224 snapshot
6225 .scroll_anchor
6226 .scroll_position(&snapshot.display_snapshot)
6227 .y as u32,
6228 );
6229
6230 JumpData::MultiBufferPoint {
6231 excerpt_id: for_excerpt.id,
6232 anchor: jump_anchor,
6233 position: jump_position,
6234 line_offset_from_top,
6235 }
6236}
6237
6238pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
6239
6240impl AcceptEditPredictionBinding {
6241 pub fn keystroke(&self) -> Option<&Keystroke> {
6242 if let Some(binding) = self.0.as_ref() {
6243 match &binding.keystrokes() {
6244 [keystroke] => Some(keystroke),
6245 _ => None,
6246 }
6247 } else {
6248 None
6249 }
6250 }
6251}
6252
6253fn prepaint_gutter_button(
6254 button: IconButton,
6255 row: DisplayRow,
6256 line_height: Pixels,
6257 gutter_dimensions: &GutterDimensions,
6258 scroll_pixel_position: gpui::Point<Pixels>,
6259 gutter_hitbox: &Hitbox,
6260 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
6261 window: &mut Window,
6262 cx: &mut App,
6263) -> AnyElement {
6264 let mut button = button.into_any_element();
6265
6266 let available_space = size(
6267 AvailableSpace::MinContent,
6268 AvailableSpace::Definite(line_height),
6269 );
6270 let indicator_size = button.layout_as_root(available_space, window, cx);
6271
6272 let blame_width = gutter_dimensions.git_blame_entries_width;
6273 let gutter_width = display_hunks
6274 .binary_search_by(|(hunk, _)| match hunk {
6275 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
6276 DisplayDiffHunk::Unfolded {
6277 display_row_range, ..
6278 } => {
6279 if display_row_range.end <= row {
6280 Ordering::Less
6281 } else if display_row_range.start > row {
6282 Ordering::Greater
6283 } else {
6284 Ordering::Equal
6285 }
6286 }
6287 })
6288 .ok()
6289 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
6290 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
6291
6292 let mut x = left_offset;
6293 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
6294 - indicator_size.width
6295 - left_offset;
6296 x += available_width / 2.;
6297
6298 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
6299 y += (line_height - indicator_size.height) / 2.;
6300
6301 button.prepaint_as_root(
6302 gutter_hitbox.origin + point(x, y),
6303 available_space,
6304 window,
6305 cx,
6306 );
6307 button
6308}
6309
6310fn render_inline_blame_entry(
6311 blame_entry: BlameEntry,
6312 style: &EditorStyle,
6313 cx: &mut App,
6314) -> Option<AnyElement> {
6315 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6316 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
6317}
6318
6319fn render_blame_entry_popover(
6320 blame_entry: BlameEntry,
6321 scroll_handle: ScrollHandle,
6322 commit_message: Option<ParsedCommitMessage>,
6323 markdown: Entity<Markdown>,
6324 workspace: WeakEntity<Workspace>,
6325 blame: &Entity<GitBlame>,
6326 window: &mut Window,
6327 cx: &mut App,
6328) -> Option<AnyElement> {
6329 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6330 let blame = blame.read(cx);
6331 let repository = blame.repository(cx)?.clone();
6332 renderer.render_blame_entry_popover(
6333 blame_entry,
6334 scroll_handle,
6335 commit_message,
6336 markdown,
6337 repository,
6338 workspace,
6339 window,
6340 cx,
6341 )
6342}
6343
6344fn render_blame_entry(
6345 ix: usize,
6346 blame: &Entity<GitBlame>,
6347 blame_entry: BlameEntry,
6348 style: &EditorStyle,
6349 last_used_color: &mut Option<(PlayerColor, Oid)>,
6350 editor: Entity<Editor>,
6351 workspace: Entity<Workspace>,
6352 renderer: Arc<dyn BlameRenderer>,
6353 cx: &mut App,
6354) -> Option<AnyElement> {
6355 let mut sha_color = cx
6356 .theme()
6357 .players()
6358 .color_for_participant(blame_entry.sha.into());
6359
6360 // If the last color we used is the same as the one we get for this line, but
6361 // the commit SHAs are different, then we try again to get a different color.
6362 match *last_used_color {
6363 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
6364 let index: u32 = blame_entry.sha.into();
6365 sha_color = cx.theme().players().color_for_participant(index + 1);
6366 }
6367 _ => {}
6368 };
6369 last_used_color.replace((sha_color, blame_entry.sha));
6370
6371 let blame = blame.read(cx);
6372 let details = blame.details_for_entry(&blame_entry);
6373 let repository = blame.repository(cx)?;
6374 renderer.render_blame_entry(
6375 &style.text,
6376 blame_entry,
6377 details,
6378 repository,
6379 workspace.downgrade(),
6380 editor,
6381 ix,
6382 sha_color.cursor,
6383 cx,
6384 )
6385}
6386
6387#[derive(Debug)]
6388pub(crate) struct LineWithInvisibles {
6389 fragments: SmallVec<[LineFragment; 1]>,
6390 invisibles: Vec<Invisible>,
6391 len: usize,
6392 pub(crate) width: Pixels,
6393 font_size: Pixels,
6394}
6395
6396enum LineFragment {
6397 Text(ShapedLine),
6398 Element {
6399 id: FoldId,
6400 element: Option<AnyElement>,
6401 size: Size<Pixels>,
6402 len: usize,
6403 },
6404}
6405
6406impl fmt::Debug for LineFragment {
6407 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6408 match self {
6409 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6410 LineFragment::Element { size, len, .. } => f
6411 .debug_struct("Element")
6412 .field("size", size)
6413 .field("len", len)
6414 .finish(),
6415 }
6416 }
6417}
6418
6419impl LineWithInvisibles {
6420 fn from_chunks<'a>(
6421 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6422 editor_style: &EditorStyle,
6423 max_line_len: usize,
6424 max_line_count: usize,
6425 editor_mode: &EditorMode,
6426 text_width: Pixels,
6427 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6428 window: &mut Window,
6429 cx: &mut App,
6430 ) -> Vec<Self> {
6431 let text_style = &editor_style.text;
6432 let mut layouts = Vec::with_capacity(max_line_count);
6433 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6434 let mut line = String::new();
6435 let mut invisibles = Vec::new();
6436 let mut width = Pixels::ZERO;
6437 let mut len = 0;
6438 let mut styles = Vec::new();
6439 let mut non_whitespace_added = false;
6440 let mut row = 0;
6441 let mut line_exceeded_max_len = false;
6442 let font_size = text_style.font_size.to_pixels(window.rem_size());
6443
6444 let ellipsis = SharedString::from("⋯");
6445
6446 for highlighted_chunk in chunks.chain([HighlightedChunk {
6447 text: "\n",
6448 style: None,
6449 is_tab: false,
6450 replacement: None,
6451 }]) {
6452 if let Some(replacement) = highlighted_chunk.replacement {
6453 if !line.is_empty() {
6454 let shaped_line = window
6455 .text_system()
6456 .shape_line(line.clone().into(), font_size, &styles)
6457 .unwrap();
6458 width += shaped_line.width;
6459 len += shaped_line.len;
6460 fragments.push(LineFragment::Text(shaped_line));
6461 line.clear();
6462 styles.clear();
6463 }
6464
6465 match replacement {
6466 ChunkReplacement::Renderer(renderer) => {
6467 let available_width = if renderer.constrain_width {
6468 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6469 ellipsis.clone()
6470 } else {
6471 SharedString::from(Arc::from(highlighted_chunk.text))
6472 };
6473 let shaped_line = window
6474 .text_system()
6475 .shape_line(
6476 chunk,
6477 font_size,
6478 &[text_style.to_run(highlighted_chunk.text.len())],
6479 )
6480 .unwrap();
6481 AvailableSpace::Definite(shaped_line.width)
6482 } else {
6483 AvailableSpace::MinContent
6484 };
6485
6486 let mut element = (renderer.render)(&mut ChunkRendererContext {
6487 context: cx,
6488 window,
6489 max_width: text_width,
6490 });
6491 let line_height = text_style.line_height_in_pixels(window.rem_size());
6492 let size = element.layout_as_root(
6493 size(available_width, AvailableSpace::Definite(line_height)),
6494 window,
6495 cx,
6496 );
6497
6498 width += size.width;
6499 len += highlighted_chunk.text.len();
6500 fragments.push(LineFragment::Element {
6501 id: renderer.id,
6502 element: Some(element),
6503 size,
6504 len: highlighted_chunk.text.len(),
6505 });
6506 }
6507 ChunkReplacement::Str(x) => {
6508 let text_style = if let Some(style) = highlighted_chunk.style {
6509 Cow::Owned(text_style.clone().highlight(style))
6510 } else {
6511 Cow::Borrowed(text_style)
6512 };
6513
6514 let run = TextRun {
6515 len: x.len(),
6516 font: text_style.font(),
6517 color: text_style.color,
6518 background_color: text_style.background_color,
6519 underline: text_style.underline,
6520 strikethrough: text_style.strikethrough,
6521 };
6522 let line_layout = window
6523 .text_system()
6524 .shape_line(x, font_size, &[run])
6525 .unwrap()
6526 .with_len(highlighted_chunk.text.len());
6527
6528 width += line_layout.width;
6529 len += highlighted_chunk.text.len();
6530 fragments.push(LineFragment::Text(line_layout))
6531 }
6532 }
6533 } else {
6534 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6535 if ix > 0 {
6536 let shaped_line = window
6537 .text_system()
6538 .shape_line(line.clone().into(), font_size, &styles)
6539 .unwrap();
6540 width += shaped_line.width;
6541 len += shaped_line.len;
6542 fragments.push(LineFragment::Text(shaped_line));
6543 layouts.push(Self {
6544 width: mem::take(&mut width),
6545 len: mem::take(&mut len),
6546 fragments: mem::take(&mut fragments),
6547 invisibles: std::mem::take(&mut invisibles),
6548 font_size,
6549 });
6550
6551 line.clear();
6552 styles.clear();
6553 row += 1;
6554 line_exceeded_max_len = false;
6555 non_whitespace_added = false;
6556 if row == max_line_count {
6557 return layouts;
6558 }
6559 }
6560
6561 if !line_chunk.is_empty() && !line_exceeded_max_len {
6562 let text_style = if let Some(style) = highlighted_chunk.style {
6563 Cow::Owned(text_style.clone().highlight(style))
6564 } else {
6565 Cow::Borrowed(text_style)
6566 };
6567
6568 if line.len() + line_chunk.len() > max_line_len {
6569 let mut chunk_len = max_line_len - line.len();
6570 while !line_chunk.is_char_boundary(chunk_len) {
6571 chunk_len -= 1;
6572 }
6573 line_chunk = &line_chunk[..chunk_len];
6574 line_exceeded_max_len = true;
6575 }
6576
6577 styles.push(TextRun {
6578 len: line_chunk.len(),
6579 font: text_style.font(),
6580 color: text_style.color,
6581 background_color: text_style.background_color,
6582 underline: text_style.underline,
6583 strikethrough: text_style.strikethrough,
6584 });
6585
6586 if editor_mode.is_full() {
6587 // Line wrap pads its contents with fake whitespaces,
6588 // avoid printing them
6589 let is_soft_wrapped = is_row_soft_wrapped(row);
6590 if highlighted_chunk.is_tab {
6591 if non_whitespace_added || !is_soft_wrapped {
6592 invisibles.push(Invisible::Tab {
6593 line_start_offset: line.len(),
6594 line_end_offset: line.len() + line_chunk.len(),
6595 });
6596 }
6597 } else {
6598 invisibles.extend(line_chunk.char_indices().filter_map(
6599 |(index, c)| {
6600 let is_whitespace = c.is_whitespace();
6601 non_whitespace_added |= !is_whitespace;
6602 if is_whitespace
6603 && (non_whitespace_added || !is_soft_wrapped)
6604 {
6605 Some(Invisible::Whitespace {
6606 line_offset: line.len() + index,
6607 })
6608 } else {
6609 None
6610 }
6611 },
6612 ))
6613 }
6614 }
6615
6616 line.push_str(line_chunk);
6617 }
6618 }
6619 }
6620 }
6621
6622 layouts
6623 }
6624
6625 fn prepaint(
6626 &mut self,
6627 line_height: Pixels,
6628 scroll_pixel_position: gpui::Point<Pixels>,
6629 row: DisplayRow,
6630 content_origin: gpui::Point<Pixels>,
6631 line_elements: &mut SmallVec<[AnyElement; 1]>,
6632 window: &mut Window,
6633 cx: &mut App,
6634 ) {
6635 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6636 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6637 for fragment in &mut self.fragments {
6638 match fragment {
6639 LineFragment::Text(line) => {
6640 fragment_origin.x += line.width;
6641 }
6642 LineFragment::Element { element, size, .. } => {
6643 let mut element = element
6644 .take()
6645 .expect("you can't prepaint LineWithInvisibles twice");
6646
6647 // Center the element vertically within the line.
6648 let mut element_origin = fragment_origin;
6649 element_origin.y += (line_height - size.height) / 2.;
6650 element.prepaint_at(element_origin, window, cx);
6651 line_elements.push(element);
6652
6653 fragment_origin.x += size.width;
6654 }
6655 }
6656 }
6657 }
6658
6659 fn draw(
6660 &self,
6661 layout: &EditorLayout,
6662 row: DisplayRow,
6663 content_origin: gpui::Point<Pixels>,
6664 whitespace_setting: ShowWhitespaceSetting,
6665 selection_ranges: &[Range<DisplayPoint>],
6666 window: &mut Window,
6667 cx: &mut App,
6668 ) {
6669 let line_height = layout.position_map.line_height;
6670 let line_y = line_height
6671 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6672
6673 let mut fragment_origin =
6674 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6675
6676 for fragment in &self.fragments {
6677 match fragment {
6678 LineFragment::Text(line) => {
6679 line.paint(fragment_origin, line_height, window, cx)
6680 .log_err();
6681 fragment_origin.x += line.width;
6682 }
6683 LineFragment::Element { size, .. } => {
6684 fragment_origin.x += size.width;
6685 }
6686 }
6687 }
6688
6689 self.draw_invisibles(
6690 selection_ranges,
6691 layout,
6692 content_origin,
6693 line_y,
6694 row,
6695 line_height,
6696 whitespace_setting,
6697 window,
6698 cx,
6699 );
6700 }
6701
6702 fn draw_background(
6703 &self,
6704 layout: &EditorLayout,
6705 row: DisplayRow,
6706 content_origin: gpui::Point<Pixels>,
6707 window: &mut Window,
6708 cx: &mut App,
6709 ) {
6710 let line_height = layout.position_map.line_height;
6711 let line_y = line_height
6712 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6713
6714 let mut fragment_origin =
6715 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6716
6717 for fragment in &self.fragments {
6718 match fragment {
6719 LineFragment::Text(line) => {
6720 line.paint_background(fragment_origin, line_height, window, cx)
6721 .log_err();
6722 fragment_origin.x += line.width;
6723 }
6724 LineFragment::Element { size, .. } => {
6725 fragment_origin.x += size.width;
6726 }
6727 }
6728 }
6729 }
6730
6731 fn draw_invisibles(
6732 &self,
6733 selection_ranges: &[Range<DisplayPoint>],
6734 layout: &EditorLayout,
6735 content_origin: gpui::Point<Pixels>,
6736 line_y: Pixels,
6737 row: DisplayRow,
6738 line_height: Pixels,
6739 whitespace_setting: ShowWhitespaceSetting,
6740 window: &mut Window,
6741 cx: &mut App,
6742 ) {
6743 let extract_whitespace_info = |invisible: &Invisible| {
6744 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6745 Invisible::Tab {
6746 line_start_offset,
6747 line_end_offset,
6748 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6749 Invisible::Whitespace { line_offset } => {
6750 (*line_offset, line_offset + 1, &layout.space_invisible)
6751 }
6752 };
6753
6754 let x_offset = self.x_for_index(token_offset);
6755 let invisible_offset =
6756 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6757 let origin = content_origin
6758 + gpui::point(
6759 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6760 line_y,
6761 );
6762
6763 (
6764 [token_offset, token_end_offset],
6765 Box::new(move |window: &mut Window, cx: &mut App| {
6766 invisible_symbol
6767 .paint(origin, line_height, window, cx)
6768 .log_err();
6769 }),
6770 )
6771 };
6772
6773 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6774 match whitespace_setting {
6775 ShowWhitespaceSetting::None => (),
6776 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6777 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6778 let invisible_point = DisplayPoint::new(row, start as u32);
6779 if !selection_ranges
6780 .iter()
6781 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6782 {
6783 return;
6784 }
6785
6786 paint(window, cx);
6787 }),
6788
6789 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6790 // - It is a tab
6791 // - It is adjacent to an edge (start or end)
6792 // - It is adjacent to a whitespace (left or right)
6793 ShowWhitespaceSetting::Boundary => {
6794 // 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
6795 // the above cases.
6796 // Note: We zip in the original `invisibles` to check for tab equality
6797 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6798 for (([start, end], paint), invisible) in
6799 invisible_iter.zip_eq(self.invisibles.iter())
6800 {
6801 let should_render = match (&last_seen, invisible) {
6802 (_, Invisible::Tab { .. }) => true,
6803 (Some((_, last_end, _)), _) => *last_end == start,
6804 _ => false,
6805 };
6806
6807 if should_render || start == 0 || end == self.len {
6808 paint(window, cx);
6809
6810 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6811 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6812 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6813 // Note that we need to make sure that the last one is actually adjacent
6814 if !should_render_last && last_end == start {
6815 paint_last(window, cx);
6816 }
6817 }
6818 }
6819
6820 // Manually render anything within a selection
6821 let invisible_point = DisplayPoint::new(row, start as u32);
6822 if selection_ranges.iter().any(|region| {
6823 region.start <= invisible_point && invisible_point < region.end
6824 }) {
6825 paint(window, cx);
6826 }
6827
6828 last_seen = Some((should_render, end, paint));
6829 }
6830 }
6831 }
6832 }
6833
6834 pub fn x_for_index(&self, index: usize) -> Pixels {
6835 let mut fragment_start_x = Pixels::ZERO;
6836 let mut fragment_start_index = 0;
6837
6838 for fragment in &self.fragments {
6839 match fragment {
6840 LineFragment::Text(shaped_line) => {
6841 let fragment_end_index = fragment_start_index + shaped_line.len;
6842 if index < fragment_end_index {
6843 return fragment_start_x
6844 + shaped_line.x_for_index(index - fragment_start_index);
6845 }
6846 fragment_start_x += shaped_line.width;
6847 fragment_start_index = fragment_end_index;
6848 }
6849 LineFragment::Element { len, size, .. } => {
6850 let fragment_end_index = fragment_start_index + len;
6851 if index < fragment_end_index {
6852 return fragment_start_x;
6853 }
6854 fragment_start_x += size.width;
6855 fragment_start_index = fragment_end_index;
6856 }
6857 }
6858 }
6859
6860 fragment_start_x
6861 }
6862
6863 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6864 let mut fragment_start_x = Pixels::ZERO;
6865 let mut fragment_start_index = 0;
6866
6867 for fragment in &self.fragments {
6868 match fragment {
6869 LineFragment::Text(shaped_line) => {
6870 let fragment_end_x = fragment_start_x + shaped_line.width;
6871 if x < fragment_end_x {
6872 return Some(
6873 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6874 );
6875 }
6876 fragment_start_x = fragment_end_x;
6877 fragment_start_index += shaped_line.len;
6878 }
6879 LineFragment::Element { len, size, .. } => {
6880 let fragment_end_x = fragment_start_x + size.width;
6881 if x < fragment_end_x {
6882 return Some(fragment_start_index);
6883 }
6884 fragment_start_index += len;
6885 fragment_start_x = fragment_end_x;
6886 }
6887 }
6888 }
6889
6890 None
6891 }
6892
6893 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6894 let mut fragment_start_index = 0;
6895
6896 for fragment in &self.fragments {
6897 match fragment {
6898 LineFragment::Text(shaped_line) => {
6899 let fragment_end_index = fragment_start_index + shaped_line.len;
6900 if index < fragment_end_index {
6901 return shaped_line.font_id_for_index(index - fragment_start_index);
6902 }
6903 fragment_start_index = fragment_end_index;
6904 }
6905 LineFragment::Element { len, .. } => {
6906 let fragment_end_index = fragment_start_index + len;
6907 if index < fragment_end_index {
6908 return None;
6909 }
6910 fragment_start_index = fragment_end_index;
6911 }
6912 }
6913 }
6914
6915 None
6916 }
6917}
6918
6919#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6920enum Invisible {
6921 /// A tab character
6922 ///
6923 /// A tab character is internally represented by spaces (configured by the user's tab width)
6924 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6925 /// adjacency checks.
6926 Tab {
6927 line_start_offset: usize,
6928 line_end_offset: usize,
6929 },
6930 Whitespace {
6931 line_offset: usize,
6932 },
6933}
6934
6935impl EditorElement {
6936 /// Returns the rem size to use when rendering the [`EditorElement`].
6937 ///
6938 /// This allows UI elements to scale based on the `buffer_font_size`.
6939 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6940 match self.editor.read(cx).mode {
6941 EditorMode::Full {
6942 scale_ui_elements_with_buffer_font_size: true,
6943 ..
6944 }
6945 | EditorMode::Minimap { .. } => {
6946 let buffer_font_size = self.style.text.font_size;
6947 match buffer_font_size {
6948 AbsoluteLength::Pixels(pixels) => {
6949 let rem_size_scale = {
6950 // Our default UI font size is 14px on a 16px base scale.
6951 // This means the default UI font size is 0.875rems.
6952 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6953
6954 // We then determine the delta between a single rem and the default font
6955 // size scale.
6956 let default_font_size_delta = 1. - default_font_size_scale;
6957
6958 // Finally, we add this delta to 1rem to get the scale factor that
6959 // should be used to scale up the UI.
6960 1. + default_font_size_delta
6961 };
6962
6963 Some(pixels * rem_size_scale)
6964 }
6965 AbsoluteLength::Rems(rems) => {
6966 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6967 }
6968 }
6969 }
6970 // We currently use single-line and auto-height editors in UI contexts,
6971 // so we don't want to scale everything with the buffer font size, as it
6972 // ends up looking off.
6973 _ => None,
6974 }
6975 }
6976
6977 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
6978 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
6979 parent.upgrade()
6980 } else {
6981 Some(self.editor.clone())
6982 }
6983 }
6984}
6985
6986impl Element for EditorElement {
6987 type RequestLayoutState = ();
6988 type PrepaintState = EditorLayout;
6989
6990 fn id(&self) -> Option<ElementId> {
6991 None
6992 }
6993
6994 fn request_layout(
6995 &mut self,
6996 _: Option<&GlobalElementId>,
6997 window: &mut Window,
6998 cx: &mut App,
6999 ) -> (gpui::LayoutId, ()) {
7000 let rem_size = self.rem_size(cx);
7001 window.with_rem_size(rem_size, |window| {
7002 self.editor.update(cx, |editor, cx| {
7003 editor.set_style(self.style.clone(), window, cx);
7004
7005 let layout_id = match editor.mode {
7006 EditorMode::SingleLine { auto_width } => {
7007 let rem_size = window.rem_size();
7008
7009 let height = self.style.text.line_height_in_pixels(rem_size);
7010 if auto_width {
7011 let editor_handle = cx.entity().clone();
7012 let style = self.style.clone();
7013 window.request_measured_layout(
7014 Style::default(),
7015 move |_, _, window, cx| {
7016 let editor_snapshot = editor_handle
7017 .update(cx, |editor, cx| editor.snapshot(window, cx));
7018 let line = Self::layout_lines(
7019 DisplayRow(0)..DisplayRow(1),
7020 &editor_snapshot,
7021 &style,
7022 px(f32::MAX),
7023 |_| false, // Single lines never soft wrap
7024 window,
7025 cx,
7026 )
7027 .pop()
7028 .unwrap();
7029
7030 let font_id =
7031 window.text_system().resolve_font(&style.text.font());
7032 let font_size =
7033 style.text.font_size.to_pixels(window.rem_size());
7034 let em_width =
7035 window.text_system().em_width(font_id, font_size).unwrap();
7036
7037 size(line.width + em_width, height)
7038 },
7039 )
7040 } else {
7041 let mut style = Style::default();
7042 style.size.height = height.into();
7043 style.size.width = relative(1.).into();
7044 window.request_layout(style, None, cx)
7045 }
7046 }
7047 EditorMode::AutoHeight { max_lines } => {
7048 let editor_handle = cx.entity().clone();
7049 let max_line_number_width =
7050 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
7051 window.request_measured_layout(
7052 Style::default(),
7053 move |known_dimensions, available_space, window, cx| {
7054 editor_handle
7055 .update(cx, |editor, cx| {
7056 compute_auto_height_layout(
7057 editor,
7058 max_lines,
7059 max_line_number_width,
7060 known_dimensions,
7061 available_space.width,
7062 window,
7063 cx,
7064 )
7065 })
7066 .unwrap_or_default()
7067 },
7068 )
7069 }
7070 EditorMode::Minimap { .. } => {
7071 let mut style = Style::default();
7072 style.size.width = relative(1.).into();
7073 style.size.height = relative(1.).into();
7074 window.request_layout(style, None, cx)
7075 }
7076 EditorMode::Full {
7077 sized_by_content, ..
7078 } => {
7079 let mut style = Style::default();
7080 style.size.width = relative(1.).into();
7081 if sized_by_content {
7082 let snapshot = editor.snapshot(window, cx);
7083 let line_height =
7084 self.style.text.line_height_in_pixels(window.rem_size());
7085 let scroll_height =
7086 (snapshot.max_point().row().next_row().0 as f32) * line_height;
7087 style.size.height = scroll_height.into();
7088 } else {
7089 style.size.height = relative(1.).into();
7090 }
7091 window.request_layout(style, None, cx)
7092 }
7093 };
7094
7095 (layout_id, ())
7096 })
7097 })
7098 }
7099
7100 fn prepaint(
7101 &mut self,
7102 _: Option<&GlobalElementId>,
7103 bounds: Bounds<Pixels>,
7104 _: &mut Self::RequestLayoutState,
7105 window: &mut Window,
7106 cx: &mut App,
7107 ) -> Self::PrepaintState {
7108 let text_style = TextStyleRefinement {
7109 font_size: Some(self.style.text.font_size),
7110 line_height: Some(self.style.text.line_height),
7111 ..Default::default()
7112 };
7113 let focus_handle = self.editor.focus_handle(cx);
7114 window.set_view_id(self.editor.entity_id());
7115 window.set_focus_handle(&focus_handle, cx);
7116
7117 let rem_size = self.rem_size(cx);
7118 window.with_rem_size(rem_size, |window| {
7119 window.with_text_style(Some(text_style), |window| {
7120 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7121 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
7122 (editor.snapshot(window, cx), editor.read_only(cx))
7123 });
7124 let style = self.style.clone();
7125
7126 let font_id = window.text_system().resolve_font(&style.text.font());
7127 let font_size = style.text.font_size.to_pixels(window.rem_size());
7128 let line_height = style.text.line_height_in_pixels(window.rem_size());
7129 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
7130 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
7131
7132 let glyph_grid_cell = size(em_width, line_height);
7133
7134 let gutter_dimensions = snapshot
7135 .gutter_dimensions(
7136 font_id,
7137 font_size,
7138 self.max_line_number_width(&snapshot, window, cx),
7139 cx,
7140 )
7141 .unwrap_or_else(|| {
7142 GutterDimensions::default_with_margin(font_id, font_size, cx)
7143 });
7144 let text_width = bounds.size.width - gutter_dimensions.width;
7145
7146 let settings = EditorSettings::get_global(cx);
7147 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
7148 let vertical_scrollbar_width = (scrollbars_shown
7149 && settings.scrollbar.axes.vertical
7150 && self
7151 .editor
7152 .read_with(cx, |editor, _| editor.show_scrollbars))
7153 .then_some(style.scrollbar_width)
7154 .unwrap_or_default();
7155 let minimap_width = self
7156 .editor
7157 .read_with(cx, |editor, _| editor.minimap().is_some())
7158 .then(|| match settings.minimap.show {
7159 ShowMinimap::Auto => {
7160 scrollbars_shown.then_some(MinimapLayout::MINIMAP_WIDTH)
7161 }
7162 _ => Some(MinimapLayout::MINIMAP_WIDTH),
7163 })
7164 .flatten()
7165 .filter(|minimap_width| {
7166 text_width - vertical_scrollbar_width - *minimap_width > *minimap_width
7167 })
7168 .unwrap_or_default();
7169
7170 let right_margin = minimap_width + vertical_scrollbar_width;
7171
7172 let editor_width =
7173 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
7174
7175 let editor_margins = EditorMargins {
7176 gutter: gutter_dimensions,
7177 right: right_margin,
7178 };
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(editor_margins.gutter.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 &editor_margins,
7639 em_width,
7640 gutter_dimensions.full_width(),
7641 line_height,
7642 &mut line_layouts,
7643 &local_selections,
7644 &selected_buffer_ids,
7645 is_row_soft_wrapped,
7646 sticky_header_excerpt_id,
7647 window,
7648 cx,
7649 )
7650 });
7651 let (mut blocks, row_block_types) = match blocks {
7652 Ok(blocks) => blocks,
7653 Err(resized_blocks) => {
7654 self.editor.update(cx, |editor, cx| {
7655 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7656 });
7657 return self.prepaint(None, bounds, &mut (), window, cx);
7658 }
7659 };
7660
7661 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7662 window.with_element_namespace("blocks", |window| {
7663 self.layout_sticky_buffer_header(
7664 sticky_header_excerpt,
7665 scroll_position.y,
7666 line_height,
7667 right_margin,
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}