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
6396#[allow(clippy::large_enum_variant)]
6397enum LineFragment {
6398 Text(ShapedLine),
6399 Element {
6400 id: FoldId,
6401 element: Option<AnyElement>,
6402 size: Size<Pixels>,
6403 len: usize,
6404 },
6405}
6406
6407impl fmt::Debug for LineFragment {
6408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6409 match self {
6410 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6411 LineFragment::Element { size, len, .. } => f
6412 .debug_struct("Element")
6413 .field("size", size)
6414 .field("len", len)
6415 .finish(),
6416 }
6417 }
6418}
6419
6420impl LineWithInvisibles {
6421 fn from_chunks<'a>(
6422 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6423 editor_style: &EditorStyle,
6424 max_line_len: usize,
6425 max_line_count: usize,
6426 editor_mode: &EditorMode,
6427 text_width: Pixels,
6428 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6429 window: &mut Window,
6430 cx: &mut App,
6431 ) -> Vec<Self> {
6432 let text_style = &editor_style.text;
6433 let mut layouts = Vec::with_capacity(max_line_count);
6434 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6435 let mut line = String::new();
6436 let mut invisibles = Vec::new();
6437 let mut width = Pixels::ZERO;
6438 let mut len = 0;
6439 let mut styles = Vec::new();
6440 let mut non_whitespace_added = false;
6441 let mut row = 0;
6442 let mut line_exceeded_max_len = false;
6443 let font_size = text_style.font_size.to_pixels(window.rem_size());
6444
6445 let ellipsis = SharedString::from("⋯");
6446
6447 for highlighted_chunk in chunks.chain([HighlightedChunk {
6448 text: "\n",
6449 style: None,
6450 is_tab: false,
6451 replacement: None,
6452 }]) {
6453 if let Some(replacement) = highlighted_chunk.replacement {
6454 if !line.is_empty() {
6455 let shaped_line = window
6456 .text_system()
6457 .shape_line(line.clone().into(), font_size, &styles)
6458 .unwrap();
6459 width += shaped_line.width;
6460 len += shaped_line.len;
6461 fragments.push(LineFragment::Text(shaped_line));
6462 line.clear();
6463 styles.clear();
6464 }
6465
6466 match replacement {
6467 ChunkReplacement::Renderer(renderer) => {
6468 let available_width = if renderer.constrain_width {
6469 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6470 ellipsis.clone()
6471 } else {
6472 SharedString::from(Arc::from(highlighted_chunk.text))
6473 };
6474 let shaped_line = window
6475 .text_system()
6476 .shape_line(
6477 chunk,
6478 font_size,
6479 &[text_style.to_run(highlighted_chunk.text.len())],
6480 )
6481 .unwrap();
6482 AvailableSpace::Definite(shaped_line.width)
6483 } else {
6484 AvailableSpace::MinContent
6485 };
6486
6487 let mut element = (renderer.render)(&mut ChunkRendererContext {
6488 context: cx,
6489 window,
6490 max_width: text_width,
6491 });
6492 let line_height = text_style.line_height_in_pixels(window.rem_size());
6493 let size = element.layout_as_root(
6494 size(available_width, AvailableSpace::Definite(line_height)),
6495 window,
6496 cx,
6497 );
6498
6499 width += size.width;
6500 len += highlighted_chunk.text.len();
6501 fragments.push(LineFragment::Element {
6502 id: renderer.id,
6503 element: Some(element),
6504 size,
6505 len: highlighted_chunk.text.len(),
6506 });
6507 }
6508 ChunkReplacement::Str(x) => {
6509 let text_style = if let Some(style) = highlighted_chunk.style {
6510 Cow::Owned(text_style.clone().highlight(style))
6511 } else {
6512 Cow::Borrowed(text_style)
6513 };
6514
6515 let run = TextRun {
6516 len: x.len(),
6517 font: text_style.font(),
6518 color: text_style.color,
6519 background_color: text_style.background_color,
6520 underline: text_style.underline,
6521 strikethrough: text_style.strikethrough,
6522 };
6523 let line_layout = window
6524 .text_system()
6525 .shape_line(x, font_size, &[run])
6526 .unwrap()
6527 .with_len(highlighted_chunk.text.len());
6528
6529 width += line_layout.width;
6530 len += highlighted_chunk.text.len();
6531 fragments.push(LineFragment::Text(line_layout))
6532 }
6533 }
6534 } else {
6535 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6536 if ix > 0 {
6537 let shaped_line = window
6538 .text_system()
6539 .shape_line(line.clone().into(), font_size, &styles)
6540 .unwrap();
6541 width += shaped_line.width;
6542 len += shaped_line.len;
6543 fragments.push(LineFragment::Text(shaped_line));
6544 layouts.push(Self {
6545 width: mem::take(&mut width),
6546 len: mem::take(&mut len),
6547 fragments: mem::take(&mut fragments),
6548 invisibles: std::mem::take(&mut invisibles),
6549 font_size,
6550 });
6551
6552 line.clear();
6553 styles.clear();
6554 row += 1;
6555 line_exceeded_max_len = false;
6556 non_whitespace_added = false;
6557 if row == max_line_count {
6558 return layouts;
6559 }
6560 }
6561
6562 if !line_chunk.is_empty() && !line_exceeded_max_len {
6563 let text_style = if let Some(style) = highlighted_chunk.style {
6564 Cow::Owned(text_style.clone().highlight(style))
6565 } else {
6566 Cow::Borrowed(text_style)
6567 };
6568
6569 if line.len() + line_chunk.len() > max_line_len {
6570 let mut chunk_len = max_line_len - line.len();
6571 while !line_chunk.is_char_boundary(chunk_len) {
6572 chunk_len -= 1;
6573 }
6574 line_chunk = &line_chunk[..chunk_len];
6575 line_exceeded_max_len = true;
6576 }
6577
6578 styles.push(TextRun {
6579 len: line_chunk.len(),
6580 font: text_style.font(),
6581 color: text_style.color,
6582 background_color: text_style.background_color,
6583 underline: text_style.underline,
6584 strikethrough: text_style.strikethrough,
6585 });
6586
6587 if editor_mode.is_full() {
6588 // Line wrap pads its contents with fake whitespaces,
6589 // avoid printing them
6590 let is_soft_wrapped = is_row_soft_wrapped(row);
6591 if highlighted_chunk.is_tab {
6592 if non_whitespace_added || !is_soft_wrapped {
6593 invisibles.push(Invisible::Tab {
6594 line_start_offset: line.len(),
6595 line_end_offset: line.len() + line_chunk.len(),
6596 });
6597 }
6598 } else {
6599 invisibles.extend(line_chunk.char_indices().filter_map(
6600 |(index, c)| {
6601 let is_whitespace = c.is_whitespace();
6602 non_whitespace_added |= !is_whitespace;
6603 if is_whitespace
6604 && (non_whitespace_added || !is_soft_wrapped)
6605 {
6606 Some(Invisible::Whitespace {
6607 line_offset: line.len() + index,
6608 })
6609 } else {
6610 None
6611 }
6612 },
6613 ))
6614 }
6615 }
6616
6617 line.push_str(line_chunk);
6618 }
6619 }
6620 }
6621 }
6622
6623 layouts
6624 }
6625
6626 fn prepaint(
6627 &mut self,
6628 line_height: Pixels,
6629 scroll_pixel_position: gpui::Point<Pixels>,
6630 row: DisplayRow,
6631 content_origin: gpui::Point<Pixels>,
6632 line_elements: &mut SmallVec<[AnyElement; 1]>,
6633 window: &mut Window,
6634 cx: &mut App,
6635 ) {
6636 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6637 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6638 for fragment in &mut self.fragments {
6639 match fragment {
6640 LineFragment::Text(line) => {
6641 fragment_origin.x += line.width;
6642 }
6643 LineFragment::Element { element, size, .. } => {
6644 let mut element = element
6645 .take()
6646 .expect("you can't prepaint LineWithInvisibles twice");
6647
6648 // Center the element vertically within the line.
6649 let mut element_origin = fragment_origin;
6650 element_origin.y += (line_height - size.height) / 2.;
6651 element.prepaint_at(element_origin, window, cx);
6652 line_elements.push(element);
6653
6654 fragment_origin.x += size.width;
6655 }
6656 }
6657 }
6658 }
6659
6660 fn draw(
6661 &self,
6662 layout: &EditorLayout,
6663 row: DisplayRow,
6664 content_origin: gpui::Point<Pixels>,
6665 whitespace_setting: ShowWhitespaceSetting,
6666 selection_ranges: &[Range<DisplayPoint>],
6667 window: &mut Window,
6668 cx: &mut App,
6669 ) {
6670 let line_height = layout.position_map.line_height;
6671 let line_y = line_height
6672 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6673
6674 let mut fragment_origin =
6675 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6676
6677 for fragment in &self.fragments {
6678 match fragment {
6679 LineFragment::Text(line) => {
6680 line.paint(fragment_origin, line_height, window, cx)
6681 .log_err();
6682 fragment_origin.x += line.width;
6683 }
6684 LineFragment::Element { size, .. } => {
6685 fragment_origin.x += size.width;
6686 }
6687 }
6688 }
6689
6690 self.draw_invisibles(
6691 selection_ranges,
6692 layout,
6693 content_origin,
6694 line_y,
6695 row,
6696 line_height,
6697 whitespace_setting,
6698 window,
6699 cx,
6700 );
6701 }
6702
6703 fn draw_background(
6704 &self,
6705 layout: &EditorLayout,
6706 row: DisplayRow,
6707 content_origin: gpui::Point<Pixels>,
6708 window: &mut Window,
6709 cx: &mut App,
6710 ) {
6711 let line_height = layout.position_map.line_height;
6712 let line_y = line_height
6713 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6714
6715 let mut fragment_origin =
6716 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6717
6718 for fragment in &self.fragments {
6719 match fragment {
6720 LineFragment::Text(line) => {
6721 line.paint_background(fragment_origin, line_height, window, cx)
6722 .log_err();
6723 fragment_origin.x += line.width;
6724 }
6725 LineFragment::Element { size, .. } => {
6726 fragment_origin.x += size.width;
6727 }
6728 }
6729 }
6730 }
6731
6732 fn draw_invisibles(
6733 &self,
6734 selection_ranges: &[Range<DisplayPoint>],
6735 layout: &EditorLayout,
6736 content_origin: gpui::Point<Pixels>,
6737 line_y: Pixels,
6738 row: DisplayRow,
6739 line_height: Pixels,
6740 whitespace_setting: ShowWhitespaceSetting,
6741 window: &mut Window,
6742 cx: &mut App,
6743 ) {
6744 let extract_whitespace_info = |invisible: &Invisible| {
6745 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6746 Invisible::Tab {
6747 line_start_offset,
6748 line_end_offset,
6749 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6750 Invisible::Whitespace { line_offset } => {
6751 (*line_offset, line_offset + 1, &layout.space_invisible)
6752 }
6753 };
6754
6755 let x_offset = self.x_for_index(token_offset);
6756 let invisible_offset =
6757 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6758 let origin = content_origin
6759 + gpui::point(
6760 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6761 line_y,
6762 );
6763
6764 (
6765 [token_offset, token_end_offset],
6766 Box::new(move |window: &mut Window, cx: &mut App| {
6767 invisible_symbol
6768 .paint(origin, line_height, window, cx)
6769 .log_err();
6770 }),
6771 )
6772 };
6773
6774 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6775 match whitespace_setting {
6776 ShowWhitespaceSetting::None => (),
6777 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6778 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6779 let invisible_point = DisplayPoint::new(row, start as u32);
6780 if !selection_ranges
6781 .iter()
6782 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6783 {
6784 return;
6785 }
6786
6787 paint(window, cx);
6788 }),
6789
6790 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6791 // - It is a tab
6792 // - It is adjacent to an edge (start or end)
6793 // - It is adjacent to a whitespace (left or right)
6794 ShowWhitespaceSetting::Boundary => {
6795 // 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
6796 // the above cases.
6797 // Note: We zip in the original `invisibles` to check for tab equality
6798 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6799 for (([start, end], paint), invisible) in
6800 invisible_iter.zip_eq(self.invisibles.iter())
6801 {
6802 let should_render = match (&last_seen, invisible) {
6803 (_, Invisible::Tab { .. }) => true,
6804 (Some((_, last_end, _)), _) => *last_end == start,
6805 _ => false,
6806 };
6807
6808 if should_render || start == 0 || end == self.len {
6809 paint(window, cx);
6810
6811 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6812 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6813 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6814 // Note that we need to make sure that the last one is actually adjacent
6815 if !should_render_last && last_end == start {
6816 paint_last(window, cx);
6817 }
6818 }
6819 }
6820
6821 // Manually render anything within a selection
6822 let invisible_point = DisplayPoint::new(row, start as u32);
6823 if selection_ranges.iter().any(|region| {
6824 region.start <= invisible_point && invisible_point < region.end
6825 }) {
6826 paint(window, cx);
6827 }
6828
6829 last_seen = Some((should_render, end, paint));
6830 }
6831 }
6832 }
6833 }
6834
6835 pub fn x_for_index(&self, index: usize) -> Pixels {
6836 let mut fragment_start_x = Pixels::ZERO;
6837 let mut fragment_start_index = 0;
6838
6839 for fragment in &self.fragments {
6840 match fragment {
6841 LineFragment::Text(shaped_line) => {
6842 let fragment_end_index = fragment_start_index + shaped_line.len;
6843 if index < fragment_end_index {
6844 return fragment_start_x
6845 + shaped_line.x_for_index(index - fragment_start_index);
6846 }
6847 fragment_start_x += shaped_line.width;
6848 fragment_start_index = fragment_end_index;
6849 }
6850 LineFragment::Element { len, size, .. } => {
6851 let fragment_end_index = fragment_start_index + len;
6852 if index < fragment_end_index {
6853 return fragment_start_x;
6854 }
6855 fragment_start_x += size.width;
6856 fragment_start_index = fragment_end_index;
6857 }
6858 }
6859 }
6860
6861 fragment_start_x
6862 }
6863
6864 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6865 let mut fragment_start_x = Pixels::ZERO;
6866 let mut fragment_start_index = 0;
6867
6868 for fragment in &self.fragments {
6869 match fragment {
6870 LineFragment::Text(shaped_line) => {
6871 let fragment_end_x = fragment_start_x + shaped_line.width;
6872 if x < fragment_end_x {
6873 return Some(
6874 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6875 );
6876 }
6877 fragment_start_x = fragment_end_x;
6878 fragment_start_index += shaped_line.len;
6879 }
6880 LineFragment::Element { len, size, .. } => {
6881 let fragment_end_x = fragment_start_x + size.width;
6882 if x < fragment_end_x {
6883 return Some(fragment_start_index);
6884 }
6885 fragment_start_index += len;
6886 fragment_start_x = fragment_end_x;
6887 }
6888 }
6889 }
6890
6891 None
6892 }
6893
6894 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6895 let mut fragment_start_index = 0;
6896
6897 for fragment in &self.fragments {
6898 match fragment {
6899 LineFragment::Text(shaped_line) => {
6900 let fragment_end_index = fragment_start_index + shaped_line.len;
6901 if index < fragment_end_index {
6902 return shaped_line.font_id_for_index(index - fragment_start_index);
6903 }
6904 fragment_start_index = fragment_end_index;
6905 }
6906 LineFragment::Element { len, .. } => {
6907 let fragment_end_index = fragment_start_index + len;
6908 if index < fragment_end_index {
6909 return None;
6910 }
6911 fragment_start_index = fragment_end_index;
6912 }
6913 }
6914 }
6915
6916 None
6917 }
6918}
6919
6920#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6921enum Invisible {
6922 /// A tab character
6923 ///
6924 /// A tab character is internally represented by spaces (configured by the user's tab width)
6925 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6926 /// adjacency checks.
6927 Tab {
6928 line_start_offset: usize,
6929 line_end_offset: usize,
6930 },
6931 Whitespace {
6932 line_offset: usize,
6933 },
6934}
6935
6936impl EditorElement {
6937 /// Returns the rem size to use when rendering the [`EditorElement`].
6938 ///
6939 /// This allows UI elements to scale based on the `buffer_font_size`.
6940 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6941 match self.editor.read(cx).mode {
6942 EditorMode::Full {
6943 scale_ui_elements_with_buffer_font_size: true,
6944 ..
6945 }
6946 | EditorMode::Minimap { .. } => {
6947 let buffer_font_size = self.style.text.font_size;
6948 match buffer_font_size {
6949 AbsoluteLength::Pixels(pixels) => {
6950 let rem_size_scale = {
6951 // Our default UI font size is 14px on a 16px base scale.
6952 // This means the default UI font size is 0.875rems.
6953 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6954
6955 // We then determine the delta between a single rem and the default font
6956 // size scale.
6957 let default_font_size_delta = 1. - default_font_size_scale;
6958
6959 // Finally, we add this delta to 1rem to get the scale factor that
6960 // should be used to scale up the UI.
6961 1. + default_font_size_delta
6962 };
6963
6964 Some(pixels * rem_size_scale)
6965 }
6966 AbsoluteLength::Rems(rems) => {
6967 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6968 }
6969 }
6970 }
6971 // We currently use single-line and auto-height editors in UI contexts,
6972 // so we don't want to scale everything with the buffer font size, as it
6973 // ends up looking off.
6974 _ => None,
6975 }
6976 }
6977
6978 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
6979 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
6980 parent.upgrade()
6981 } else {
6982 Some(self.editor.clone())
6983 }
6984 }
6985}
6986
6987impl Element for EditorElement {
6988 type RequestLayoutState = ();
6989 type PrepaintState = EditorLayout;
6990
6991 fn id(&self) -> Option<ElementId> {
6992 None
6993 }
6994
6995 fn request_layout(
6996 &mut self,
6997 _: Option<&GlobalElementId>,
6998 window: &mut Window,
6999 cx: &mut App,
7000 ) -> (gpui::LayoutId, ()) {
7001 let rem_size = self.rem_size(cx);
7002 window.with_rem_size(rem_size, |window| {
7003 self.editor.update(cx, |editor, cx| {
7004 editor.set_style(self.style.clone(), window, cx);
7005
7006 let layout_id = match editor.mode {
7007 EditorMode::SingleLine { auto_width } => {
7008 let rem_size = window.rem_size();
7009
7010 let height = self.style.text.line_height_in_pixels(rem_size);
7011 if auto_width {
7012 let editor_handle = cx.entity().clone();
7013 let style = self.style.clone();
7014 window.request_measured_layout(
7015 Style::default(),
7016 move |_, _, window, cx| {
7017 let editor_snapshot = editor_handle
7018 .update(cx, |editor, cx| editor.snapshot(window, cx));
7019 let line = Self::layout_lines(
7020 DisplayRow(0)..DisplayRow(1),
7021 &editor_snapshot,
7022 &style,
7023 px(f32::MAX),
7024 |_| false, // Single lines never soft wrap
7025 window,
7026 cx,
7027 )
7028 .pop()
7029 .unwrap();
7030
7031 let font_id =
7032 window.text_system().resolve_font(&style.text.font());
7033 let font_size =
7034 style.text.font_size.to_pixels(window.rem_size());
7035 let em_width =
7036 window.text_system().em_width(font_id, font_size).unwrap();
7037
7038 size(line.width + em_width, height)
7039 },
7040 )
7041 } else {
7042 let mut style = Style::default();
7043 style.size.height = height.into();
7044 style.size.width = relative(1.).into();
7045 window.request_layout(style, None, cx)
7046 }
7047 }
7048 EditorMode::AutoHeight { max_lines } => {
7049 let editor_handle = cx.entity().clone();
7050 let max_line_number_width =
7051 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
7052 window.request_measured_layout(
7053 Style::default(),
7054 move |known_dimensions, available_space, window, cx| {
7055 editor_handle
7056 .update(cx, |editor, cx| {
7057 compute_auto_height_layout(
7058 editor,
7059 max_lines,
7060 max_line_number_width,
7061 known_dimensions,
7062 available_space.width,
7063 window,
7064 cx,
7065 )
7066 })
7067 .unwrap_or_default()
7068 },
7069 )
7070 }
7071 EditorMode::Minimap { .. } => {
7072 let mut style = Style::default();
7073 style.size.width = relative(1.).into();
7074 style.size.height = relative(1.).into();
7075 window.request_layout(style, None, cx)
7076 }
7077 EditorMode::Full {
7078 sized_by_content, ..
7079 } => {
7080 let mut style = Style::default();
7081 style.size.width = relative(1.).into();
7082 if sized_by_content {
7083 let snapshot = editor.snapshot(window, cx);
7084 let line_height =
7085 self.style.text.line_height_in_pixels(window.rem_size());
7086 let scroll_height =
7087 (snapshot.max_point().row().next_row().0 as f32) * line_height;
7088 style.size.height = scroll_height.into();
7089 } else {
7090 style.size.height = relative(1.).into();
7091 }
7092 window.request_layout(style, None, cx)
7093 }
7094 };
7095
7096 (layout_id, ())
7097 })
7098 })
7099 }
7100
7101 fn prepaint(
7102 &mut self,
7103 _: Option<&GlobalElementId>,
7104 bounds: Bounds<Pixels>,
7105 _: &mut Self::RequestLayoutState,
7106 window: &mut Window,
7107 cx: &mut App,
7108 ) -> Self::PrepaintState {
7109 let text_style = TextStyleRefinement {
7110 font_size: Some(self.style.text.font_size),
7111 line_height: Some(self.style.text.line_height),
7112 ..Default::default()
7113 };
7114 let focus_handle = self.editor.focus_handle(cx);
7115 window.set_view_id(self.editor.entity_id());
7116 window.set_focus_handle(&focus_handle, cx);
7117
7118 let rem_size = self.rem_size(cx);
7119 window.with_rem_size(rem_size, |window| {
7120 window.with_text_style(Some(text_style), |window| {
7121 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7122 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
7123 (editor.snapshot(window, cx), editor.read_only(cx))
7124 });
7125 let style = self.style.clone();
7126
7127 let font_id = window.text_system().resolve_font(&style.text.font());
7128 let font_size = style.text.font_size.to_pixels(window.rem_size());
7129 let line_height = style.text.line_height_in_pixels(window.rem_size());
7130 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
7131 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
7132
7133 let glyph_grid_cell = size(em_width, line_height);
7134
7135 let gutter_dimensions = snapshot
7136 .gutter_dimensions(
7137 font_id,
7138 font_size,
7139 self.max_line_number_width(&snapshot, window, cx),
7140 cx,
7141 )
7142 .unwrap_or_else(|| {
7143 GutterDimensions::default_with_margin(font_id, font_size, cx)
7144 });
7145 let text_width = bounds.size.width - gutter_dimensions.width;
7146
7147 let settings = EditorSettings::get_global(cx);
7148 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
7149 let vertical_scrollbar_width = (scrollbars_shown
7150 && settings.scrollbar.axes.vertical
7151 && self
7152 .editor
7153 .read_with(cx, |editor, _| editor.show_scrollbars))
7154 .then_some(style.scrollbar_width)
7155 .unwrap_or_default();
7156 let minimap_width = self
7157 .editor
7158 .read_with(cx, |editor, _| editor.minimap().is_some())
7159 .then(|| match settings.minimap.show {
7160 ShowMinimap::Auto => {
7161 scrollbars_shown.then_some(MinimapLayout::MINIMAP_WIDTH)
7162 }
7163 _ => Some(MinimapLayout::MINIMAP_WIDTH),
7164 })
7165 .flatten()
7166 .filter(|minimap_width| {
7167 text_width - vertical_scrollbar_width - *minimap_width > *minimap_width
7168 })
7169 .unwrap_or_default();
7170
7171 let right_margin = minimap_width + vertical_scrollbar_width;
7172
7173 let editor_width =
7174 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
7175
7176 let editor_margins = EditorMargins {
7177 gutter: gutter_dimensions,
7178 right: right_margin,
7179 };
7180
7181 // Offset the content_bounds from the text_bounds by the gutter margin (which
7182 // is roughly half a character wide) to make hit testing work more like how we want.
7183 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
7184
7185 let editor_content_width = editor_width - content_offset.x;
7186
7187 snapshot = self.editor.update(cx, |editor, cx| {
7188 editor.last_bounds = Some(bounds);
7189 editor.gutter_dimensions = gutter_dimensions;
7190 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
7191
7192 if matches!(
7193 editor.mode,
7194 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
7195 ) {
7196 snapshot
7197 } else {
7198 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
7199 let wrap_width = match editor.soft_wrap_mode(cx) {
7200 SoftWrap::GitDiff => None,
7201 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
7202 SoftWrap::EditorWidth => Some(editor_content_width),
7203 SoftWrap::Column(column) => Some(wrap_width_for(column)),
7204 SoftWrap::Bounded(column) => {
7205 Some(editor_content_width.min(wrap_width_for(column)))
7206 }
7207 };
7208
7209 if editor.set_wrap_width(wrap_width, cx) {
7210 editor.snapshot(window, cx)
7211 } else {
7212 snapshot
7213 }
7214 }
7215 });
7216
7217 let wrap_guides = self
7218 .editor
7219 .read(cx)
7220 .wrap_guides(cx)
7221 .iter()
7222 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
7223 .collect::<SmallVec<[_; 2]>>();
7224
7225 let hitbox = window.insert_hitbox(bounds, false);
7226 let gutter_hitbox =
7227 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
7228 let text_hitbox = window.insert_hitbox(
7229 Bounds {
7230 origin: gutter_hitbox.top_right(),
7231 size: size(text_width, bounds.size.height),
7232 },
7233 false,
7234 );
7235
7236 let content_origin = text_hitbox.origin + content_offset;
7237
7238 let editor_text_bounds =
7239 Bounds::from_corners(content_origin, bounds.bottom_right());
7240
7241 let height_in_lines = editor_text_bounds.size.height / line_height;
7242
7243 let max_row = snapshot.max_point().row().as_f32();
7244
7245 // The max scroll position for the top of the window
7246 let max_scroll_top = if matches!(
7247 snapshot.mode,
7248 EditorMode::SingleLine { .. }
7249 | EditorMode::AutoHeight { .. }
7250 | EditorMode::Full {
7251 sized_by_content: true,
7252 ..
7253 }
7254 ) {
7255 (max_row - height_in_lines + 1.).max(0.)
7256 } else {
7257 let settings = EditorSettings::get_global(cx);
7258 match settings.scroll_beyond_last_line {
7259 ScrollBeyondLastLine::OnePage => max_row,
7260 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
7261 ScrollBeyondLastLine::VerticalScrollMargin => {
7262 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
7263 .max(0.)
7264 }
7265 }
7266 };
7267
7268 // TODO: Autoscrolling for both axes
7269 let mut autoscroll_request = None;
7270 let mut autoscroll_containing_element = false;
7271 let mut autoscroll_horizontally = false;
7272 self.editor.update(cx, |editor, cx| {
7273 autoscroll_request = editor.autoscroll_request();
7274 autoscroll_containing_element =
7275 autoscroll_request.is_some() || editor.has_pending_selection();
7276 // TODO: Is this horizontal or vertical?!
7277 autoscroll_horizontally = editor.autoscroll_vertically(
7278 bounds,
7279 line_height,
7280 max_scroll_top,
7281 window,
7282 cx,
7283 );
7284 snapshot = editor.snapshot(window, cx);
7285 });
7286
7287 let mut scroll_position = snapshot.scroll_position();
7288 // The scroll position is a fractional point, the whole number of which represents
7289 // the top of the window in terms of display rows.
7290 let start_row = DisplayRow(scroll_position.y as u32);
7291 let max_row = snapshot.max_point().row();
7292 let end_row = cmp::min(
7293 (scroll_position.y + height_in_lines).ceil() as u32,
7294 max_row.next_row().0,
7295 );
7296 let end_row = DisplayRow(end_row);
7297
7298 let row_infos = snapshot
7299 .row_infos(start_row)
7300 .take((start_row..end_row).len())
7301 .collect::<Vec<RowInfo>>();
7302 let is_row_soft_wrapped = |row: usize| {
7303 row_infos
7304 .get(row)
7305 .map_or(true, |info| info.buffer_row.is_none())
7306 };
7307
7308 let start_anchor = if start_row == Default::default() {
7309 Anchor::min()
7310 } else {
7311 snapshot.buffer_snapshot.anchor_before(
7312 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
7313 )
7314 };
7315 let end_anchor = if end_row > max_row {
7316 Anchor::max()
7317 } else {
7318 snapshot.buffer_snapshot.anchor_before(
7319 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
7320 )
7321 };
7322
7323 let mut highlighted_rows = self
7324 .editor
7325 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
7326
7327 let is_light = cx.theme().appearance().is_light();
7328
7329 for (ix, row_info) in row_infos.iter().enumerate() {
7330 let Some(diff_status) = row_info.diff_status else {
7331 continue;
7332 };
7333
7334 let background_color = match diff_status.kind {
7335 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
7336 DiffHunkStatusKind::Deleted => {
7337 cx.theme().colors().version_control_deleted
7338 }
7339 DiffHunkStatusKind::Modified => {
7340 debug_panic!("modified diff status for row info");
7341 continue;
7342 }
7343 };
7344
7345 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
7346
7347 let hollow_highlight = LineHighlight {
7348 background: (background_color.opacity(if is_light {
7349 0.08
7350 } else {
7351 0.06
7352 }))
7353 .into(),
7354 border: Some(if is_light {
7355 background_color.opacity(0.48)
7356 } else {
7357 background_color.opacity(0.36)
7358 }),
7359 include_gutter: true,
7360 type_id: None,
7361 };
7362
7363 let filled_highlight = LineHighlight {
7364 background: solid_background(background_color.opacity(hunk_opacity)),
7365 border: None,
7366 include_gutter: true,
7367 type_id: None,
7368 };
7369
7370 let background = if Self::diff_hunk_hollow(diff_status, cx) {
7371 hollow_highlight
7372 } else {
7373 filled_highlight
7374 };
7375
7376 highlighted_rows
7377 .entry(start_row + DisplayRow(ix as u32))
7378 .or_insert(background);
7379 }
7380
7381 let highlighted_ranges = self
7382 .editor_with_selections(cx)
7383 .map(|editor| {
7384 editor.read(cx).background_highlights_in_range(
7385 start_anchor..end_anchor,
7386 &snapshot.display_snapshot,
7387 cx.theme().colors(),
7388 )
7389 })
7390 .unwrap_or_default();
7391 let highlighted_gutter_ranges =
7392 self.editor.read(cx).gutter_highlights_in_range(
7393 start_anchor..end_anchor,
7394 &snapshot.display_snapshot,
7395 cx,
7396 );
7397
7398 let redacted_ranges = self.editor.read(cx).redacted_ranges(
7399 start_anchor..end_anchor,
7400 &snapshot.display_snapshot,
7401 cx,
7402 );
7403
7404 let (local_selections, selected_buffer_ids): (
7405 Vec<Selection<Point>>,
7406 Vec<BufferId>,
7407 ) = self
7408 .editor_with_selections(cx)
7409 .map(|editor| {
7410 editor.update(cx, |editor, cx| {
7411 let all_selections = editor.selections.all::<Point>(cx);
7412 let selected_buffer_ids = if editor.is_singleton(cx) {
7413 Vec::new()
7414 } else {
7415 let mut selected_buffer_ids =
7416 Vec::with_capacity(all_selections.len());
7417
7418 for selection in all_selections {
7419 for buffer_id in snapshot
7420 .buffer_snapshot
7421 .buffer_ids_for_range(selection.range())
7422 {
7423 if selected_buffer_ids.last() != Some(&buffer_id) {
7424 selected_buffer_ids.push(buffer_id);
7425 }
7426 }
7427 }
7428
7429 selected_buffer_ids
7430 };
7431
7432 let mut selections = editor
7433 .selections
7434 .disjoint_in_range(start_anchor..end_anchor, cx);
7435 selections.extend(editor.selections.pending(cx));
7436
7437 (selections, selected_buffer_ids)
7438 })
7439 })
7440 .unwrap_or_default();
7441
7442 let (selections, mut active_rows, newest_selection_head) = self
7443 .layout_selections(
7444 start_anchor,
7445 end_anchor,
7446 &local_selections,
7447 &snapshot,
7448 start_row,
7449 end_row,
7450 window,
7451 cx,
7452 );
7453 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
7454 editor.active_breakpoints(start_row..end_row, window, cx)
7455 });
7456 if cx.has_flag::<DebuggerFeatureFlag>() {
7457 for display_row in breakpoint_rows.keys() {
7458 active_rows.entry(*display_row).or_default().breakpoint = true;
7459 }
7460 }
7461
7462 let line_numbers = self.layout_line_numbers(
7463 Some(&gutter_hitbox),
7464 gutter_dimensions,
7465 line_height,
7466 scroll_position,
7467 start_row..end_row,
7468 &row_infos,
7469 &active_rows,
7470 newest_selection_head,
7471 &snapshot,
7472 window,
7473 cx,
7474 );
7475
7476 // We add the gutter breakpoint indicator to breakpoint_rows after painting
7477 // line numbers so we don't paint a line number debug accent color if a user
7478 // has their mouse over that line when a breakpoint isn't there
7479 if cx.has_flag::<DebuggerFeatureFlag>() {
7480 self.editor.update(cx, |editor, _| {
7481 if let Some(phantom_breakpoint) = &mut editor
7482 .gutter_breakpoint_indicator
7483 .0
7484 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
7485 {
7486 // Is there a non-phantom breakpoint on this line?
7487 phantom_breakpoint.collides_with_existing_breakpoint = true;
7488 breakpoint_rows
7489 .entry(phantom_breakpoint.display_row)
7490 .or_insert_with(|| {
7491 let position = snapshot.display_point_to_anchor(
7492 DisplayPoint::new(phantom_breakpoint.display_row, 0),
7493 Bias::Right,
7494 );
7495 let breakpoint = Breakpoint::new_standard();
7496 phantom_breakpoint.collides_with_existing_breakpoint =
7497 false;
7498 (position, breakpoint)
7499 });
7500 }
7501 })
7502 }
7503
7504 let mut expand_toggles =
7505 window.with_element_namespace("expand_toggles", |window| {
7506 self.layout_expand_toggles(
7507 &gutter_hitbox,
7508 gutter_dimensions,
7509 em_width,
7510 line_height,
7511 scroll_position,
7512 &row_infos,
7513 window,
7514 cx,
7515 )
7516 });
7517
7518 let mut crease_toggles =
7519 window.with_element_namespace("crease_toggles", |window| {
7520 self.layout_crease_toggles(
7521 start_row..end_row,
7522 &row_infos,
7523 &active_rows,
7524 &snapshot,
7525 window,
7526 cx,
7527 )
7528 });
7529 let crease_trailers =
7530 window.with_element_namespace("crease_trailers", |window| {
7531 self.layout_crease_trailers(
7532 row_infos.iter().copied(),
7533 &snapshot,
7534 window,
7535 cx,
7536 )
7537 });
7538
7539 let display_hunks = self.layout_gutter_diff_hunks(
7540 line_height,
7541 &gutter_hitbox,
7542 start_row..end_row,
7543 &snapshot,
7544 window,
7545 cx,
7546 );
7547
7548 let mut line_layouts = Self::layout_lines(
7549 start_row..end_row,
7550 &snapshot,
7551 &self.style,
7552 editor_width,
7553 is_row_soft_wrapped,
7554 window,
7555 cx,
7556 );
7557 let new_fold_widths = line_layouts
7558 .iter()
7559 .flat_map(|layout| &layout.fragments)
7560 .filter_map(|fragment| {
7561 if let LineFragment::Element { id, size, .. } = fragment {
7562 Some((*id, size.width))
7563 } else {
7564 None
7565 }
7566 });
7567 if self.editor.update(cx, |editor, cx| {
7568 editor.update_fold_widths(new_fold_widths, cx)
7569 }) {
7570 // If the fold widths have changed, we need to prepaint
7571 // the element again to account for any changes in
7572 // wrapping.
7573 return self.prepaint(None, bounds, &mut (), window, cx);
7574 }
7575
7576 let longest_line_blame_width = self
7577 .editor
7578 .update(cx, |editor, cx| {
7579 if !editor.show_git_blame_inline {
7580 return None;
7581 }
7582 let blame = editor.blame.as_ref()?;
7583 let blame_entry = blame
7584 .update(cx, |blame, cx| {
7585 let row_infos =
7586 snapshot.row_infos(snapshot.longest_row()).next()?;
7587 blame.blame_for_rows(&[row_infos], cx).next()
7588 })
7589 .flatten()?;
7590 let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
7591 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7592 Some(
7593 element
7594 .layout_as_root(AvailableSpace::min_size(), window, cx)
7595 .width
7596 + inline_blame_padding,
7597 )
7598 })
7599 .unwrap_or(Pixels::ZERO);
7600
7601 let longest_line_width = layout_line(
7602 snapshot.longest_row(),
7603 &snapshot,
7604 &style,
7605 editor_width,
7606 is_row_soft_wrapped,
7607 window,
7608 cx,
7609 )
7610 .width;
7611
7612 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
7613 text_hitbox.bounds,
7614 glyph_grid_cell,
7615 size(longest_line_width, max_row.as_f32() * line_height),
7616 longest_line_blame_width,
7617 editor_width,
7618 EditorSettings::get_global(cx),
7619 );
7620
7621 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
7622
7623 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7624 snapshot.sticky_header_excerpt(scroll_position.y)
7625 } else {
7626 None
7627 };
7628 let sticky_header_excerpt_id =
7629 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7630
7631 let blocks = window.with_element_namespace("blocks", |window| {
7632 self.render_blocks(
7633 start_row..end_row,
7634 &snapshot,
7635 &hitbox,
7636 &text_hitbox,
7637 editor_width,
7638 &mut scroll_width,
7639 &editor_margins,
7640 em_width,
7641 gutter_dimensions.full_width(),
7642 line_height,
7643 &mut line_layouts,
7644 &local_selections,
7645 &selected_buffer_ids,
7646 is_row_soft_wrapped,
7647 sticky_header_excerpt_id,
7648 window,
7649 cx,
7650 )
7651 });
7652 let (mut blocks, row_block_types) = match blocks {
7653 Ok(blocks) => blocks,
7654 Err(resized_blocks) => {
7655 self.editor.update(cx, |editor, cx| {
7656 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7657 });
7658 return self.prepaint(None, bounds, &mut (), window, cx);
7659 }
7660 };
7661
7662 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7663 window.with_element_namespace("blocks", |window| {
7664 self.layout_sticky_buffer_header(
7665 sticky_header_excerpt,
7666 scroll_position.y,
7667 line_height,
7668 right_margin,
7669 &snapshot,
7670 &hitbox,
7671 &selected_buffer_ids,
7672 &blocks,
7673 window,
7674 cx,
7675 )
7676 })
7677 });
7678
7679 let start_buffer_row =
7680 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7681 let end_buffer_row =
7682 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7683
7684 let scroll_max = point(
7685 ((scroll_width - editor_content_width) / em_width).max(0.0),
7686 max_scroll_top,
7687 );
7688
7689 self.editor.update(cx, |editor, cx| {
7690 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7691
7692 let autoscrolled = if autoscroll_horizontally {
7693 editor.autoscroll_horizontally(
7694 start_row,
7695 editor_content_width,
7696 scroll_width,
7697 em_width,
7698 &line_layouts,
7699 cx,
7700 )
7701 } else {
7702 false
7703 };
7704
7705 if clamped || autoscrolled {
7706 snapshot = editor.snapshot(window, cx);
7707 scroll_position = snapshot.scroll_position();
7708 }
7709 });
7710
7711 let scroll_pixel_position = point(
7712 scroll_position.x * em_width,
7713 scroll_position.y * line_height,
7714 );
7715
7716 let indent_guides = self.layout_indent_guides(
7717 content_origin,
7718 text_hitbox.origin,
7719 start_buffer_row..end_buffer_row,
7720 scroll_pixel_position,
7721 line_height,
7722 &snapshot,
7723 window,
7724 cx,
7725 );
7726
7727 let crease_trailers =
7728 window.with_element_namespace("crease_trailers", |window| {
7729 self.prepaint_crease_trailers(
7730 crease_trailers,
7731 &line_layouts,
7732 line_height,
7733 content_origin,
7734 scroll_pixel_position,
7735 em_width,
7736 window,
7737 cx,
7738 )
7739 });
7740
7741 let (inline_completion_popover, inline_completion_popover_origin) = self
7742 .editor
7743 .update(cx, |editor, cx| {
7744 editor.render_edit_prediction_popover(
7745 &text_hitbox.bounds,
7746 content_origin,
7747 right_margin,
7748 &snapshot,
7749 start_row..end_row,
7750 scroll_position.y,
7751 scroll_position.y + height_in_lines,
7752 &line_layouts,
7753 line_height,
7754 scroll_pixel_position,
7755 newest_selection_head,
7756 editor_width,
7757 &style,
7758 window,
7759 cx,
7760 )
7761 })
7762 .unzip();
7763
7764 let mut inline_diagnostics = self.layout_inline_diagnostics(
7765 &line_layouts,
7766 &crease_trailers,
7767 &row_block_types,
7768 content_origin,
7769 scroll_pixel_position,
7770 inline_completion_popover_origin,
7771 start_row,
7772 end_row,
7773 line_height,
7774 em_width,
7775 &style,
7776 window,
7777 cx,
7778 );
7779
7780 let mut inline_blame = None;
7781 if let Some(newest_selection_head) = newest_selection_head {
7782 let display_row = newest_selection_head.row();
7783 if (start_row..end_row).contains(&display_row)
7784 && !row_block_types.contains_key(&display_row)
7785 {
7786 let line_ix = display_row.minus(start_row) as usize;
7787 let row_info = &row_infos[line_ix];
7788 let line_layout = &line_layouts[line_ix];
7789 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7790 inline_blame = self.layout_inline_blame(
7791 display_row,
7792 row_info,
7793 line_layout,
7794 crease_trailer_layout,
7795 em_width,
7796 content_origin,
7797 scroll_pixel_position,
7798 line_height,
7799 &text_hitbox,
7800 window,
7801 cx,
7802 );
7803 if inline_blame.is_some() {
7804 // Blame overrides inline diagnostics
7805 inline_diagnostics.remove(&display_row);
7806 }
7807 }
7808 }
7809
7810 let blamed_display_rows = self.layout_blame_entries(
7811 &row_infos,
7812 em_width,
7813 scroll_position,
7814 line_height,
7815 &gutter_hitbox,
7816 gutter_dimensions.git_blame_entries_width,
7817 window,
7818 cx,
7819 );
7820
7821 self.editor.update(cx, |editor, cx| {
7822 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7823
7824 let autoscrolled = if autoscroll_horizontally {
7825 editor.autoscroll_horizontally(
7826 start_row,
7827 editor_content_width,
7828 scroll_width,
7829 em_width,
7830 &line_layouts,
7831 cx,
7832 )
7833 } else {
7834 false
7835 };
7836
7837 if clamped || autoscrolled {
7838 snapshot = editor.snapshot(window, cx);
7839 scroll_position = snapshot.scroll_position();
7840 }
7841 });
7842
7843 let line_elements = self.prepaint_lines(
7844 start_row,
7845 &mut line_layouts,
7846 line_height,
7847 scroll_pixel_position,
7848 content_origin,
7849 window,
7850 cx,
7851 );
7852
7853 window.with_element_namespace("blocks", |window| {
7854 self.layout_blocks(
7855 &mut blocks,
7856 &hitbox,
7857 line_height,
7858 scroll_pixel_position,
7859 window,
7860 cx,
7861 );
7862 });
7863
7864 let cursors = self.collect_cursors(&snapshot, cx);
7865 let visible_row_range = start_row..end_row;
7866 let non_visible_cursors = cursors
7867 .iter()
7868 .any(|c| !visible_row_range.contains(&c.0.row()));
7869
7870 let visible_cursors = self.layout_visible_cursors(
7871 &snapshot,
7872 &selections,
7873 &row_block_types,
7874 start_row..end_row,
7875 &line_layouts,
7876 &text_hitbox,
7877 content_origin,
7878 scroll_position,
7879 scroll_pixel_position,
7880 line_height,
7881 em_width,
7882 em_advance,
7883 autoscroll_containing_element,
7884 window,
7885 cx,
7886 );
7887
7888 let scrollbars_layout = self.layout_scrollbars(
7889 &snapshot,
7890 &scrollbar_layout_information,
7891 content_offset,
7892 scroll_position,
7893 non_visible_cursors,
7894 right_margin,
7895 editor_width,
7896 window,
7897 cx,
7898 );
7899
7900 let gutter_settings = EditorSettings::get_global(cx).gutter;
7901
7902 if let Some(newest_selection_head) = newest_selection_head {
7903 let newest_selection_point =
7904 newest_selection_head.to_point(&snapshot.display_snapshot);
7905
7906 if (start_row..end_row).contains(&newest_selection_head.row()) {
7907 self.layout_cursor_popovers(
7908 line_height,
7909 &text_hitbox,
7910 content_origin,
7911 right_margin,
7912 start_row,
7913 scroll_pixel_position,
7914 &line_layouts,
7915 newest_selection_head,
7916 newest_selection_point,
7917 &style,
7918 window,
7919 cx,
7920 );
7921 }
7922 }
7923
7924 self.layout_gutter_menu(
7925 line_height,
7926 &text_hitbox,
7927 content_origin,
7928 right_margin,
7929 scroll_pixel_position,
7930 gutter_dimensions.width - gutter_dimensions.left_padding,
7931 window,
7932 cx,
7933 );
7934
7935 let test_indicators = if gutter_settings.runnables {
7936 self.layout_run_indicators(
7937 line_height,
7938 start_row..end_row,
7939 &row_infos,
7940 scroll_pixel_position,
7941 &gutter_dimensions,
7942 &gutter_hitbox,
7943 &display_hunks,
7944 &snapshot,
7945 &mut breakpoint_rows,
7946 window,
7947 cx,
7948 )
7949 } else {
7950 Vec::new()
7951 };
7952
7953 let show_breakpoints = snapshot
7954 .show_breakpoints
7955 .unwrap_or(gutter_settings.breakpoints);
7956 let breakpoints = if cx.has_flag::<DebuggerFeatureFlag>() && show_breakpoints {
7957 self.layout_breakpoints(
7958 line_height,
7959 start_row..end_row,
7960 scroll_pixel_position,
7961 &gutter_dimensions,
7962 &gutter_hitbox,
7963 &display_hunks,
7964 &snapshot,
7965 breakpoint_rows,
7966 &row_infos,
7967 window,
7968 cx,
7969 )
7970 } else {
7971 vec![]
7972 };
7973
7974 self.layout_signature_help(
7975 &hitbox,
7976 &text_hitbox,
7977 content_origin,
7978 scroll_pixel_position,
7979 newest_selection_head,
7980 start_row,
7981 &line_layouts,
7982 line_height,
7983 em_width,
7984 window,
7985 cx,
7986 );
7987
7988 if !cx.has_active_drag() {
7989 self.layout_hover_popovers(
7990 &snapshot,
7991 &hitbox,
7992 &text_hitbox,
7993 start_row..end_row,
7994 content_origin,
7995 scroll_pixel_position,
7996 &line_layouts,
7997 line_height,
7998 em_width,
7999 window,
8000 cx,
8001 );
8002 }
8003
8004 let mouse_context_menu = self.layout_mouse_context_menu(
8005 &snapshot,
8006 start_row..end_row,
8007 content_origin,
8008 window,
8009 cx,
8010 );
8011
8012 window.with_element_namespace("crease_toggles", |window| {
8013 self.prepaint_crease_toggles(
8014 &mut crease_toggles,
8015 line_height,
8016 &gutter_dimensions,
8017 gutter_settings,
8018 scroll_pixel_position,
8019 &gutter_hitbox,
8020 window,
8021 cx,
8022 )
8023 });
8024
8025 window.with_element_namespace("expand_toggles", |window| {
8026 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
8027 });
8028
8029 let minimap = window.with_element_namespace("minimap", |window| {
8030 self.layout_minimap(
8031 &snapshot,
8032 minimap_width,
8033 scroll_position,
8034 &scrollbar_layout_information,
8035 scrollbars_layout.as_ref(),
8036 window,
8037 cx,
8038 )
8039 });
8040
8041 let invisible_symbol_font_size = font_size / 2.;
8042 let tab_invisible = window
8043 .text_system()
8044 .shape_line(
8045 "→".into(),
8046 invisible_symbol_font_size,
8047 &[TextRun {
8048 len: "→".len(),
8049 font: self.style.text.font(),
8050 color: cx.theme().colors().editor_invisible,
8051 background_color: None,
8052 underline: None,
8053 strikethrough: None,
8054 }],
8055 )
8056 .unwrap();
8057 let space_invisible = window
8058 .text_system()
8059 .shape_line(
8060 "•".into(),
8061 invisible_symbol_font_size,
8062 &[TextRun {
8063 len: "•".len(),
8064 font: self.style.text.font(),
8065 color: cx.theme().colors().editor_invisible,
8066 background_color: None,
8067 underline: None,
8068 strikethrough: None,
8069 }],
8070 )
8071 .unwrap();
8072
8073 let mode = snapshot.mode.clone();
8074
8075 let position_map = Rc::new(PositionMap {
8076 size: bounds.size,
8077 visible_row_range,
8078 scroll_pixel_position,
8079 scroll_max,
8080 line_layouts,
8081 line_height,
8082 em_width,
8083 em_advance,
8084 snapshot,
8085 gutter_hitbox: gutter_hitbox.clone(),
8086 text_hitbox: text_hitbox.clone(),
8087 });
8088
8089 self.editor.update(cx, |editor, _| {
8090 editor.last_position_map = Some(position_map.clone())
8091 });
8092
8093 let diff_hunk_controls = if is_read_only {
8094 vec![]
8095 } else {
8096 self.layout_diff_hunk_controls(
8097 start_row..end_row,
8098 &row_infos,
8099 &text_hitbox,
8100 &position_map,
8101 newest_selection_head,
8102 line_height,
8103 right_margin,
8104 scroll_pixel_position,
8105 &display_hunks,
8106 &highlighted_rows,
8107 self.editor.clone(),
8108 window,
8109 cx,
8110 )
8111 };
8112
8113 EditorLayout {
8114 mode,
8115 position_map,
8116 visible_display_row_range: start_row..end_row,
8117 wrap_guides,
8118 indent_guides,
8119 hitbox,
8120 gutter_hitbox,
8121 display_hunks,
8122 content_origin,
8123 scrollbars_layout,
8124 minimap,
8125 active_rows,
8126 highlighted_rows,
8127 highlighted_ranges,
8128 highlighted_gutter_ranges,
8129 redacted_ranges,
8130 line_elements,
8131 line_numbers,
8132 blamed_display_rows,
8133 inline_diagnostics,
8134 inline_blame,
8135 blocks,
8136 cursors,
8137 visible_cursors,
8138 selections,
8139 inline_completion_popover,
8140 diff_hunk_controls,
8141 mouse_context_menu,
8142 test_indicators,
8143 breakpoints,
8144 crease_toggles,
8145 crease_trailers,
8146 tab_invisible,
8147 space_invisible,
8148 sticky_buffer_header,
8149 expand_toggles,
8150 }
8151 })
8152 })
8153 })
8154 }
8155
8156 fn paint(
8157 &mut self,
8158 _: Option<&GlobalElementId>,
8159 bounds: Bounds<gpui::Pixels>,
8160 _: &mut Self::RequestLayoutState,
8161 layout: &mut Self::PrepaintState,
8162 window: &mut Window,
8163 cx: &mut App,
8164 ) {
8165 let focus_handle = self.editor.focus_handle(cx);
8166 let key_context = self
8167 .editor
8168 .update(cx, |editor, cx| editor.key_context(window, cx));
8169
8170 window.set_key_context(key_context);
8171 window.handle_input(
8172 &focus_handle,
8173 ElementInputHandler::new(bounds, self.editor.clone()),
8174 cx,
8175 );
8176 self.register_actions(window, cx);
8177 self.register_key_listeners(window, cx, layout);
8178
8179 let text_style = TextStyleRefinement {
8180 font_size: Some(self.style.text.font_size),
8181 line_height: Some(self.style.text.line_height),
8182 ..Default::default()
8183 };
8184 let rem_size = self.rem_size(cx);
8185 window.with_rem_size(rem_size, |window| {
8186 window.with_text_style(Some(text_style), |window| {
8187 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8188 self.paint_mouse_listeners(layout, window, cx);
8189 self.paint_background(layout, window, cx);
8190 self.paint_indent_guides(layout, window, cx);
8191
8192 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8193 self.paint_blamed_display_rows(layout, window, cx);
8194 self.paint_line_numbers(layout, window, cx);
8195 }
8196
8197 self.paint_text(layout, window, cx);
8198
8199 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8200 self.paint_gutter_highlights(layout, window, cx);
8201 self.paint_gutter_indicators(layout, window, cx);
8202 }
8203
8204 if !layout.blocks.is_empty() {
8205 window.with_element_namespace("blocks", |window| {
8206 self.paint_blocks(layout, window, cx);
8207 });
8208 }
8209
8210 window.with_element_namespace("blocks", |window| {
8211 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
8212 sticky_header.paint(window, cx)
8213 }
8214 });
8215
8216 self.paint_minimap(layout, window, cx);
8217 self.paint_scrollbars(layout, window, cx);
8218 self.paint_inline_completion_popover(layout, window, cx);
8219 self.paint_mouse_context_menu(layout, window, cx);
8220 });
8221 })
8222 })
8223 }
8224}
8225
8226pub(super) fn gutter_bounds(
8227 editor_bounds: Bounds<Pixels>,
8228 gutter_dimensions: GutterDimensions,
8229) -> Bounds<Pixels> {
8230 Bounds {
8231 origin: editor_bounds.origin,
8232 size: size(gutter_dimensions.width, editor_bounds.size.height),
8233 }
8234}
8235
8236/// Holds information required for layouting the editor scrollbars.
8237struct ScrollbarLayoutInformation {
8238 /// The bounds of the editor area (excluding the content offset).
8239 editor_bounds: Bounds<Pixels>,
8240 /// The available range to scroll within the document.
8241 scroll_range: Size<Pixels>,
8242 /// The space available for one glyph in the editor.
8243 glyph_grid_cell: Size<Pixels>,
8244}
8245
8246impl ScrollbarLayoutInformation {
8247 pub fn new(
8248 editor_bounds: Bounds<Pixels>,
8249 glyph_grid_cell: Size<Pixels>,
8250 document_size: Size<Pixels>,
8251 longest_line_blame_width: Pixels,
8252 editor_width: Pixels,
8253 settings: &EditorSettings,
8254 ) -> Self {
8255 let vertical_overscroll = match settings.scroll_beyond_last_line {
8256 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
8257 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
8258 ScrollBeyondLastLine::VerticalScrollMargin => {
8259 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
8260 }
8261 };
8262
8263 let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
8264 glyph_grid_cell.width
8265 } else {
8266 px(0.0)
8267 };
8268
8269 let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
8270
8271 let scroll_range = document_size + overscroll;
8272
8273 ScrollbarLayoutInformation {
8274 editor_bounds,
8275 scroll_range,
8276 glyph_grid_cell,
8277 }
8278 }
8279}
8280
8281impl IntoElement for EditorElement {
8282 type Element = Self;
8283
8284 fn into_element(self) -> Self::Element {
8285 self
8286 }
8287}
8288
8289pub struct EditorLayout {
8290 position_map: Rc<PositionMap>,
8291 hitbox: Hitbox,
8292 gutter_hitbox: Hitbox,
8293 content_origin: gpui::Point<Pixels>,
8294 scrollbars_layout: Option<EditorScrollbars>,
8295 minimap: Option<MinimapLayout>,
8296 mode: EditorMode,
8297 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
8298 indent_guides: Option<Vec<IndentGuideLayout>>,
8299 visible_display_row_range: Range<DisplayRow>,
8300 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
8301 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
8302 line_elements: SmallVec<[AnyElement; 1]>,
8303 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
8304 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
8305 blamed_display_rows: Option<Vec<AnyElement>>,
8306 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
8307 inline_blame: Option<AnyElement>,
8308 blocks: Vec<BlockLayout>,
8309 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
8310 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
8311 redacted_ranges: Vec<Range<DisplayPoint>>,
8312 cursors: Vec<(DisplayPoint, Hsla)>,
8313 visible_cursors: Vec<CursorLayout>,
8314 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
8315 test_indicators: Vec<AnyElement>,
8316 breakpoints: Vec<AnyElement>,
8317 crease_toggles: Vec<Option<AnyElement>>,
8318 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
8319 diff_hunk_controls: Vec<AnyElement>,
8320 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
8321 inline_completion_popover: Option<AnyElement>,
8322 mouse_context_menu: Option<AnyElement>,
8323 tab_invisible: ShapedLine,
8324 space_invisible: ShapedLine,
8325 sticky_buffer_header: Option<AnyElement>,
8326}
8327
8328impl EditorLayout {
8329 fn line_end_overshoot(&self) -> Pixels {
8330 0.15 * self.position_map.line_height
8331 }
8332}
8333
8334struct LineNumberLayout {
8335 shaped_line: ShapedLine,
8336 hitbox: Option<Hitbox>,
8337}
8338
8339struct ColoredRange<T> {
8340 start: T,
8341 end: T,
8342 color: Hsla,
8343}
8344
8345impl Along for ScrollbarAxes {
8346 type Unit = bool;
8347
8348 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
8349 match axis {
8350 ScrollbarAxis::Horizontal => self.horizontal,
8351 ScrollbarAxis::Vertical => self.vertical,
8352 }
8353 }
8354
8355 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
8356 match axis {
8357 ScrollbarAxis::Horizontal => ScrollbarAxes {
8358 horizontal: f(self.horizontal),
8359 vertical: self.vertical,
8360 },
8361 ScrollbarAxis::Vertical => ScrollbarAxes {
8362 horizontal: self.horizontal,
8363 vertical: f(self.vertical),
8364 },
8365 }
8366 }
8367}
8368
8369#[derive(Clone)]
8370struct EditorScrollbars {
8371 pub vertical: Option<ScrollbarLayout>,
8372 pub horizontal: Option<ScrollbarLayout>,
8373 pub visible: bool,
8374}
8375
8376impl EditorScrollbars {
8377 pub fn from_scrollbar_axes(
8378 settings_visibility: ScrollbarAxes,
8379 layout_information: &ScrollbarLayoutInformation,
8380 content_offset: gpui::Point<Pixels>,
8381 scroll_position: gpui::Point<f32>,
8382 scrollbar_width: Pixels,
8383 right_margin: Pixels,
8384 editor_width: Pixels,
8385 show_scrollbars: bool,
8386 scrollbar_state: Option<&ActiveScrollbarState>,
8387 window: &mut Window,
8388 ) -> Self {
8389 let ScrollbarLayoutInformation {
8390 editor_bounds,
8391 scroll_range,
8392 glyph_grid_cell,
8393 } = layout_information;
8394
8395 let viewport_size = size(editor_width, editor_bounds.size.height);
8396
8397 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
8398 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
8399 Corner::BottomLeft,
8400 editor_bounds.bottom_left(),
8401 size(
8402 // The horizontal viewport size differs from the space available for the
8403 // horizontal scrollbar, so we have to manually stich it together here.
8404 editor_bounds.size.width - right_margin,
8405 scrollbar_width,
8406 ),
8407 ),
8408 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
8409 Corner::TopRight,
8410 editor_bounds.top_right(),
8411 size(scrollbar_width, viewport_size.height),
8412 ),
8413 };
8414
8415 let mut create_scrollbar_layout = |axis| {
8416 settings_visibility
8417 .along(axis)
8418 .then(|| {
8419 (
8420 viewport_size.along(axis) - content_offset.along(axis),
8421 scroll_range.along(axis),
8422 )
8423 })
8424 .filter(|(viewport_size, scroll_range)| {
8425 // The scrollbar should only be rendered if the content does
8426 // not entirely fit into the editor
8427 // However, this only applies to the horizontal scrollbar, as information about the
8428 // vertical scrollbar layout is always needed for scrollbar diagnostics.
8429 axis != ScrollbarAxis::Horizontal || viewport_size < scroll_range
8430 })
8431 .map(|(viewport_size, scroll_range)| {
8432 let thumb_state = scrollbar_state
8433 .and_then(|state| state.thumb_state_for_axis(axis))
8434 .unwrap_or(ScrollbarThumbState::Idle);
8435
8436 ScrollbarLayout::new(
8437 window.insert_hitbox(scrollbar_bounds_for(axis), false),
8438 viewport_size,
8439 scroll_range,
8440 glyph_grid_cell.along(axis),
8441 content_offset.along(axis),
8442 scroll_position.along(axis),
8443 show_scrollbars,
8444 thumb_state,
8445 axis,
8446 )
8447 })
8448 };
8449
8450 Self {
8451 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
8452 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
8453 visible: show_scrollbars,
8454 }
8455 }
8456
8457 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
8458 [
8459 (&self.vertical, ScrollbarAxis::Vertical),
8460 (&self.horizontal, ScrollbarAxis::Horizontal),
8461 ]
8462 .into_iter()
8463 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
8464 }
8465
8466 /// Returns the currently hovered scrollbar axis, if any.
8467 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
8468 self.iter_scrollbars()
8469 .find(|s| s.0.hitbox.is_hovered(window))
8470 }
8471}
8472
8473#[derive(Clone)]
8474struct ScrollbarLayout {
8475 hitbox: Hitbox,
8476 visible_range: Range<f32>,
8477 text_unit_size: Pixels,
8478 thumb_bounds: Option<Bounds<Pixels>>,
8479 thumb_state: ScrollbarThumbState,
8480}
8481
8482impl ScrollbarLayout {
8483 const BORDER_WIDTH: Pixels = px(1.0);
8484 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
8485 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
8486 const MIN_THUMB_SIZE: Pixels = px(25.0);
8487
8488 fn new(
8489 scrollbar_track_hitbox: Hitbox,
8490 viewport_size: Pixels,
8491 scroll_range: Pixels,
8492 glyph_space: Pixels,
8493 content_offset: Pixels,
8494 scroll_position: f32,
8495 show_thumb: bool,
8496 thumb_state: ScrollbarThumbState,
8497 axis: ScrollbarAxis,
8498 ) -> Self {
8499 let track_bounds = scrollbar_track_hitbox.bounds;
8500 // The length of the track available to the scrollbar thumb. We deliberately
8501 // exclude the content size here so that the thumb aligns with the content.
8502 let track_length = track_bounds.size.along(axis) - content_offset;
8503
8504 Self::new_with_hitbox_and_track_length(
8505 scrollbar_track_hitbox,
8506 track_length,
8507 viewport_size,
8508 scroll_range,
8509 glyph_space,
8510 content_offset,
8511 scroll_position,
8512 show_thumb,
8513 thumb_state,
8514 axis,
8515 )
8516 }
8517
8518 fn for_minimap(
8519 minimap_track_hitbox: Hitbox,
8520 visible_lines: f32,
8521 total_editor_lines: f32,
8522 minimap_line_height: Pixels,
8523 scroll_position: f32,
8524 minimap_scroll_top: f32,
8525 show_thumb: bool,
8526 ) -> Self {
8527 // The scrollbar thumb size is calculated as
8528 // (visible_content/total_content) × scrollbar_track_length.
8529 //
8530 // For the minimap's thumb layout, we leverage this by setting the
8531 // scrollbar track length to the entire document size (using minimap line
8532 // height). This creates a thumb that exactly represents the editor
8533 // viewport scaled to minimap proportions.
8534 //
8535 // We adjust the thumb position relative to `minimap_scroll_top` to
8536 // accommodate for the deliberately oversized track.
8537 //
8538 // This approach ensures that the minimap thumb accurately reflects the
8539 // editor's current scroll position whilst nicely synchronizing the minimap
8540 // thumb and scrollbar thumb.
8541 let scroll_range = total_editor_lines * minimap_line_height;
8542 let viewport_size = visible_lines * minimap_line_height;
8543
8544 let track_top_offset = -minimap_scroll_top * minimap_line_height;
8545
8546 Self::new_with_hitbox_and_track_length(
8547 minimap_track_hitbox,
8548 scroll_range,
8549 viewport_size,
8550 scroll_range,
8551 minimap_line_height,
8552 track_top_offset,
8553 scroll_position,
8554 show_thumb,
8555 ScrollbarThumbState::Idle,
8556 ScrollbarAxis::Vertical,
8557 )
8558 }
8559
8560 fn new_with_hitbox_and_track_length(
8561 scrollbar_track_hitbox: Hitbox,
8562 track_length: Pixels,
8563 viewport_size: Pixels,
8564 scroll_range: Pixels,
8565 glyph_space: Pixels,
8566 content_offset: Pixels,
8567 scroll_position: f32,
8568 show_thumb: bool,
8569 thumb_state: ScrollbarThumbState,
8570 axis: ScrollbarAxis,
8571 ) -> Self {
8572 let text_units_per_page = viewport_size / glyph_space;
8573 let visible_range = scroll_position..scroll_position + text_units_per_page;
8574 let total_text_units = scroll_range / glyph_space;
8575
8576 let thumb_percentage = text_units_per_page / total_text_units;
8577 let thumb_size = (track_length * thumb_percentage)
8578 .max(ScrollbarLayout::MIN_THUMB_SIZE)
8579 .min(track_length);
8580
8581 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
8582
8583 let content_larger_than_viewport = text_unit_divisor > 0.;
8584
8585 let text_unit_size = if content_larger_than_viewport {
8586 (track_length - thumb_size) / text_unit_divisor
8587 } else {
8588 glyph_space
8589 };
8590
8591 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
8592 Self::thumb_bounds(
8593 &scrollbar_track_hitbox,
8594 content_offset,
8595 visible_range.start,
8596 text_unit_size,
8597 thumb_size,
8598 axis,
8599 )
8600 });
8601
8602 ScrollbarLayout {
8603 hitbox: scrollbar_track_hitbox,
8604 visible_range,
8605 text_unit_size,
8606 thumb_bounds,
8607 thumb_state,
8608 }
8609 }
8610
8611 fn thumb_bounds(
8612 scrollbar_track: &Hitbox,
8613 content_offset: Pixels,
8614 visible_range_start: f32,
8615 text_unit_size: Pixels,
8616 thumb_size: Pixels,
8617 axis: ScrollbarAxis,
8618 ) -> Bounds<Pixels> {
8619 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
8620 origin + content_offset + visible_range_start * text_unit_size
8621 });
8622 Bounds::new(
8623 thumb_origin,
8624 scrollbar_track.size.apply_along(axis, |_| thumb_size),
8625 )
8626 }
8627
8628 fn marker_quads_for_ranges(
8629 &self,
8630 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
8631 column: Option<usize>,
8632 ) -> Vec<PaintQuad> {
8633 struct MinMax {
8634 min: Pixels,
8635 max: Pixels,
8636 }
8637 let (x_range, height_limit) = if let Some(column) = column {
8638 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
8639 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
8640 let end = start + column_width;
8641 (
8642 Range { start, end },
8643 MinMax {
8644 min: Self::MIN_MARKER_HEIGHT,
8645 max: px(f32::MAX),
8646 },
8647 )
8648 } else {
8649 (
8650 Range {
8651 start: Self::BORDER_WIDTH,
8652 end: self.hitbox.size.width,
8653 },
8654 MinMax {
8655 min: Self::LINE_MARKER_HEIGHT,
8656 max: Self::LINE_MARKER_HEIGHT,
8657 },
8658 )
8659 };
8660
8661 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
8662 let mut pixel_ranges = row_ranges
8663 .into_iter()
8664 .map(|range| {
8665 let start_y = row_to_y(range.start);
8666 let end_y = row_to_y(range.end)
8667 + self
8668 .text_unit_size
8669 .max(height_limit.min)
8670 .min(height_limit.max);
8671 ColoredRange {
8672 start: start_y,
8673 end: end_y,
8674 color: range.color,
8675 }
8676 })
8677 .peekable();
8678
8679 let mut quads = Vec::new();
8680 while let Some(mut pixel_range) = pixel_ranges.next() {
8681 while let Some(next_pixel_range) = pixel_ranges.peek() {
8682 if pixel_range.end >= next_pixel_range.start - px(1.0)
8683 && pixel_range.color == next_pixel_range.color
8684 {
8685 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
8686 pixel_ranges.next();
8687 } else {
8688 break;
8689 }
8690 }
8691
8692 let bounds = Bounds::from_corners(
8693 point(x_range.start, pixel_range.start),
8694 point(x_range.end, pixel_range.end),
8695 );
8696 quads.push(quad(
8697 bounds,
8698 Corners::default(),
8699 pixel_range.color,
8700 Edges::default(),
8701 Hsla::transparent_black(),
8702 BorderStyle::default(),
8703 ));
8704 }
8705
8706 quads
8707 }
8708}
8709
8710struct MinimapLayout {
8711 pub minimap: AnyElement,
8712 pub thumb_layout: ScrollbarLayout,
8713 pub minimap_scroll_top: f32,
8714 pub minimap_line_height: Pixels,
8715 pub thumb_border_style: MinimapThumbBorder,
8716 pub max_scroll_top: f32,
8717}
8718
8719impl MinimapLayout {
8720 const MINIMAP_WIDTH: Pixels = px(100.);
8721 /// Calculates the scroll top offset the minimap editor has to have based on the
8722 /// current scroll progress.
8723 fn calculate_minimap_top_offset(
8724 document_lines: f32,
8725 visible_editor_lines: f32,
8726 visible_minimap_lines: f32,
8727 scroll_position: f32,
8728 ) -> f32 {
8729 let scroll_percentage =
8730 (scroll_position / (document_lines - visible_editor_lines)).clamp(0., 1.);
8731 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
8732 }
8733}
8734
8735struct CreaseTrailerLayout {
8736 element: AnyElement,
8737 bounds: Bounds<Pixels>,
8738}
8739
8740pub(crate) struct PositionMap {
8741 pub size: Size<Pixels>,
8742 pub line_height: Pixels,
8743 pub scroll_pixel_position: gpui::Point<Pixels>,
8744 pub scroll_max: gpui::Point<f32>,
8745 pub em_width: Pixels,
8746 pub em_advance: Pixels,
8747 pub visible_row_range: Range<DisplayRow>,
8748 pub line_layouts: Vec<LineWithInvisibles>,
8749 pub snapshot: EditorSnapshot,
8750 pub text_hitbox: Hitbox,
8751 pub gutter_hitbox: Hitbox,
8752}
8753
8754#[derive(Debug, Copy, Clone)]
8755pub struct PointForPosition {
8756 pub previous_valid: DisplayPoint,
8757 pub next_valid: DisplayPoint,
8758 pub exact_unclipped: DisplayPoint,
8759 pub column_overshoot_after_line_end: u32,
8760}
8761
8762impl PointForPosition {
8763 pub fn as_valid(&self) -> Option<DisplayPoint> {
8764 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8765 Some(self.previous_valid)
8766 } else {
8767 None
8768 }
8769 }
8770}
8771
8772impl PositionMap {
8773 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8774 let text_bounds = self.text_hitbox.bounds;
8775 let scroll_position = self.snapshot.scroll_position();
8776 let position = position - text_bounds.origin;
8777 let y = position.y.max(px(0.)).min(self.size.height);
8778 let x = position.x + (scroll_position.x * self.em_width);
8779 let row = ((y / self.line_height) + scroll_position.y) as u32;
8780
8781 let (column, x_overshoot_after_line_end) = if let Some(line) = self
8782 .line_layouts
8783 .get(row as usize - scroll_position.y as usize)
8784 {
8785 if let Some(ix) = line.index_for_x(x) {
8786 (ix as u32, px(0.))
8787 } else {
8788 (line.len as u32, px(0.).max(x - line.width))
8789 }
8790 } else {
8791 (0, x)
8792 };
8793
8794 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8795 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8796 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8797
8798 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8799 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8800 PointForPosition {
8801 previous_valid,
8802 next_valid,
8803 exact_unclipped,
8804 column_overshoot_after_line_end,
8805 }
8806 }
8807}
8808
8809struct BlockLayout {
8810 id: BlockId,
8811 x_offset: Pixels,
8812 row: Option<DisplayRow>,
8813 element: AnyElement,
8814 available_space: Size<AvailableSpace>,
8815 style: BlockStyle,
8816 overlaps_gutter: bool,
8817 is_buffer_header: bool,
8818}
8819
8820pub fn layout_line(
8821 row: DisplayRow,
8822 snapshot: &EditorSnapshot,
8823 style: &EditorStyle,
8824 text_width: Pixels,
8825 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8826 window: &mut Window,
8827 cx: &mut App,
8828) -> LineWithInvisibles {
8829 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8830 LineWithInvisibles::from_chunks(
8831 chunks,
8832 &style,
8833 MAX_LINE_LEN,
8834 1,
8835 &snapshot.mode,
8836 text_width,
8837 is_row_soft_wrapped,
8838 window,
8839 cx,
8840 )
8841 .pop()
8842 .unwrap()
8843}
8844
8845#[derive(Debug)]
8846pub struct IndentGuideLayout {
8847 origin: gpui::Point<Pixels>,
8848 length: Pixels,
8849 single_indent_width: Pixels,
8850 depth: u32,
8851 active: bool,
8852 settings: IndentGuideSettings,
8853}
8854
8855pub struct CursorLayout {
8856 origin: gpui::Point<Pixels>,
8857 block_width: Pixels,
8858 line_height: Pixels,
8859 color: Hsla,
8860 shape: CursorShape,
8861 block_text: Option<ShapedLine>,
8862 cursor_name: Option<AnyElement>,
8863}
8864
8865#[derive(Debug)]
8866pub struct CursorName {
8867 string: SharedString,
8868 color: Hsla,
8869 is_top_row: bool,
8870}
8871
8872impl CursorLayout {
8873 pub fn new(
8874 origin: gpui::Point<Pixels>,
8875 block_width: Pixels,
8876 line_height: Pixels,
8877 color: Hsla,
8878 shape: CursorShape,
8879 block_text: Option<ShapedLine>,
8880 ) -> CursorLayout {
8881 CursorLayout {
8882 origin,
8883 block_width,
8884 line_height,
8885 color,
8886 shape,
8887 block_text,
8888 cursor_name: None,
8889 }
8890 }
8891
8892 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8893 Bounds {
8894 origin: self.origin + origin,
8895 size: size(self.block_width, self.line_height),
8896 }
8897 }
8898
8899 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8900 match self.shape {
8901 CursorShape::Bar => Bounds {
8902 origin: self.origin + origin,
8903 size: size(px(2.0), self.line_height),
8904 },
8905 CursorShape::Block | CursorShape::Hollow => Bounds {
8906 origin: self.origin + origin,
8907 size: size(self.block_width, self.line_height),
8908 },
8909 CursorShape::Underline => Bounds {
8910 origin: self.origin
8911 + origin
8912 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8913 size: size(self.block_width, px(2.0)),
8914 },
8915 }
8916 }
8917
8918 pub fn layout(
8919 &mut self,
8920 origin: gpui::Point<Pixels>,
8921 cursor_name: Option<CursorName>,
8922 window: &mut Window,
8923 cx: &mut App,
8924 ) {
8925 if let Some(cursor_name) = cursor_name {
8926 let bounds = self.bounds(origin);
8927 let text_size = self.line_height / 1.5;
8928
8929 let name_origin = if cursor_name.is_top_row {
8930 point(bounds.right() - px(1.), bounds.top())
8931 } else {
8932 match self.shape {
8933 CursorShape::Bar => point(
8934 bounds.right() - px(2.),
8935 bounds.top() - text_size / 2. - px(1.),
8936 ),
8937 _ => point(
8938 bounds.right() - px(1.),
8939 bounds.top() - text_size / 2. - px(1.),
8940 ),
8941 }
8942 };
8943 let mut name_element = div()
8944 .bg(self.color)
8945 .text_size(text_size)
8946 .px_0p5()
8947 .line_height(text_size + px(2.))
8948 .text_color(cursor_name.color)
8949 .child(cursor_name.string.clone())
8950 .into_any_element();
8951
8952 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8953
8954 self.cursor_name = Some(name_element);
8955 }
8956 }
8957
8958 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8959 let bounds = self.bounds(origin);
8960
8961 //Draw background or border quad
8962 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8963 outline(bounds, self.color, BorderStyle::Solid)
8964 } else {
8965 fill(bounds, self.color)
8966 };
8967
8968 if let Some(name) = &mut self.cursor_name {
8969 name.paint(window, cx);
8970 }
8971
8972 window.paint_quad(cursor);
8973
8974 if let Some(block_text) = &self.block_text {
8975 block_text
8976 .paint(self.origin + origin, self.line_height, window, cx)
8977 .log_err();
8978 }
8979 }
8980
8981 pub fn shape(&self) -> CursorShape {
8982 self.shape
8983 }
8984}
8985
8986#[derive(Debug)]
8987pub struct HighlightedRange {
8988 pub start_y: Pixels,
8989 pub line_height: Pixels,
8990 pub lines: Vec<HighlightedRangeLine>,
8991 pub color: Hsla,
8992 pub corner_radius: Pixels,
8993}
8994
8995#[derive(Debug)]
8996pub struct HighlightedRangeLine {
8997 pub start_x: Pixels,
8998 pub end_x: Pixels,
8999}
9000
9001impl HighlightedRange {
9002 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
9003 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
9004 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
9005 self.paint_lines(
9006 self.start_y + self.line_height,
9007 &self.lines[1..],
9008 bounds,
9009 window,
9010 );
9011 } else {
9012 self.paint_lines(self.start_y, &self.lines, bounds, window);
9013 }
9014 }
9015
9016 fn paint_lines(
9017 &self,
9018 start_y: Pixels,
9019 lines: &[HighlightedRangeLine],
9020 _bounds: Bounds<Pixels>,
9021 window: &mut Window,
9022 ) {
9023 if lines.is_empty() {
9024 return;
9025 }
9026
9027 let first_line = lines.first().unwrap();
9028 let last_line = lines.last().unwrap();
9029
9030 let first_top_left = point(first_line.start_x, start_y);
9031 let first_top_right = point(first_line.end_x, start_y);
9032
9033 let curve_height = point(Pixels::ZERO, self.corner_radius);
9034 let curve_width = |start_x: Pixels, end_x: Pixels| {
9035 let max = (end_x - start_x) / 2.;
9036 let width = if max < self.corner_radius {
9037 max
9038 } else {
9039 self.corner_radius
9040 };
9041
9042 point(width, Pixels::ZERO)
9043 };
9044
9045 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
9046 let mut builder = gpui::PathBuilder::fill();
9047 builder.move_to(first_top_right - top_curve_width);
9048 builder.curve_to(first_top_right + curve_height, first_top_right);
9049
9050 let mut iter = lines.iter().enumerate().peekable();
9051 while let Some((ix, line)) = iter.next() {
9052 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
9053
9054 if let Some((_, next_line)) = iter.peek() {
9055 let next_top_right = point(next_line.end_x, bottom_right.y);
9056
9057 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
9058 Ordering::Equal => {
9059 builder.line_to(bottom_right);
9060 }
9061 Ordering::Less => {
9062 let curve_width = curve_width(next_top_right.x, bottom_right.x);
9063 builder.line_to(bottom_right - curve_height);
9064 if self.corner_radius > Pixels::ZERO {
9065 builder.curve_to(bottom_right - curve_width, bottom_right);
9066 }
9067 builder.line_to(next_top_right + curve_width);
9068 if self.corner_radius > Pixels::ZERO {
9069 builder.curve_to(next_top_right + curve_height, next_top_right);
9070 }
9071 }
9072 Ordering::Greater => {
9073 let curve_width = curve_width(bottom_right.x, next_top_right.x);
9074 builder.line_to(bottom_right - curve_height);
9075 if self.corner_radius > Pixels::ZERO {
9076 builder.curve_to(bottom_right + curve_width, bottom_right);
9077 }
9078 builder.line_to(next_top_right - curve_width);
9079 if self.corner_radius > Pixels::ZERO {
9080 builder.curve_to(next_top_right + curve_height, next_top_right);
9081 }
9082 }
9083 }
9084 } else {
9085 let curve_width = curve_width(line.start_x, line.end_x);
9086 builder.line_to(bottom_right - curve_height);
9087 if self.corner_radius > Pixels::ZERO {
9088 builder.curve_to(bottom_right - curve_width, bottom_right);
9089 }
9090
9091 let bottom_left = point(line.start_x, bottom_right.y);
9092 builder.line_to(bottom_left + curve_width);
9093 if self.corner_radius > Pixels::ZERO {
9094 builder.curve_to(bottom_left - curve_height, bottom_left);
9095 }
9096 }
9097 }
9098
9099 if first_line.start_x > last_line.start_x {
9100 let curve_width = curve_width(last_line.start_x, first_line.start_x);
9101 let second_top_left = point(last_line.start_x, start_y + self.line_height);
9102 builder.line_to(second_top_left + curve_height);
9103 if self.corner_radius > Pixels::ZERO {
9104 builder.curve_to(second_top_left + curve_width, second_top_left);
9105 }
9106 let first_bottom_left = point(first_line.start_x, second_top_left.y);
9107 builder.line_to(first_bottom_left - curve_width);
9108 if self.corner_radius > Pixels::ZERO {
9109 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
9110 }
9111 }
9112
9113 builder.line_to(first_top_left + curve_height);
9114 if self.corner_radius > Pixels::ZERO {
9115 builder.curve_to(first_top_left + top_curve_width, first_top_left);
9116 }
9117 builder.line_to(first_top_right - top_curve_width);
9118
9119 if let Ok(path) = builder.build() {
9120 window.paint_path(path, self.color);
9121 }
9122 }
9123}
9124
9125enum CursorPopoverType {
9126 CodeContextMenu,
9127 EditPrediction,
9128}
9129
9130pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9131 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
9132}
9133
9134fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9135 (delta.pow(1.2) / 300.0).into()
9136}
9137
9138pub fn register_action<T: Action>(
9139 editor: &Entity<Editor>,
9140 window: &mut Window,
9141 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
9142) {
9143 let editor = editor.clone();
9144 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
9145 let action = action.downcast_ref().unwrap();
9146 if phase == DispatchPhase::Bubble {
9147 editor.update(cx, |editor, cx| {
9148 listener(editor, action, window, cx);
9149 })
9150 }
9151 })
9152}
9153
9154fn compute_auto_height_layout(
9155 editor: &mut Editor,
9156 max_lines: usize,
9157 max_line_number_width: Pixels,
9158 known_dimensions: Size<Option<Pixels>>,
9159 available_width: AvailableSpace,
9160 window: &mut Window,
9161 cx: &mut Context<Editor>,
9162) -> Option<Size<Pixels>> {
9163 let width = known_dimensions.width.or({
9164 if let AvailableSpace::Definite(available_width) = available_width {
9165 Some(available_width)
9166 } else {
9167 None
9168 }
9169 })?;
9170 if let Some(height) = known_dimensions.height {
9171 return Some(size(width, height));
9172 }
9173
9174 let style = editor.style.as_ref().unwrap();
9175 let font_id = window.text_system().resolve_font(&style.text.font());
9176 let font_size = style.text.font_size.to_pixels(window.rem_size());
9177 let line_height = style.text.line_height_in_pixels(window.rem_size());
9178 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
9179
9180 let mut snapshot = editor.snapshot(window, cx);
9181 let gutter_dimensions = snapshot
9182 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
9183 .unwrap_or_else(|| GutterDimensions::default_with_margin(font_id, font_size, cx));
9184
9185 editor.gutter_dimensions = gutter_dimensions;
9186 let text_width = width - gutter_dimensions.width;
9187 let overscroll = size(em_width, px(0.));
9188
9189 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
9190 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
9191 if editor.set_wrap_width(Some(editor_width), cx) {
9192 snapshot = editor.snapshot(window, cx);
9193 }
9194 }
9195
9196 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
9197 let height = scroll_height
9198 .max(line_height)
9199 .min(line_height * max_lines as f32);
9200
9201 Some(size(width, height))
9202}
9203
9204#[cfg(test)]
9205mod tests {
9206 use super::*;
9207 use crate::{
9208 Editor, MultiBuffer,
9209 display_map::{BlockPlacement, BlockProperties},
9210 editor_tests::{init_test, update_test_language_settings},
9211 };
9212 use gpui::{TestAppContext, VisualTestContext};
9213 use language::language_settings;
9214 use log::info;
9215 use std::num::NonZeroU32;
9216 use util::test::sample_text;
9217
9218 #[gpui::test]
9219 fn test_shape_line_numbers(cx: &mut TestAppContext) {
9220 init_test(cx, |_| {});
9221 let window = cx.add_window(|window, cx| {
9222 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
9223 Editor::new(EditorMode::full(), buffer, None, window, cx)
9224 });
9225
9226 let editor = window.root(cx).unwrap();
9227 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
9228 let line_height = window
9229 .update(cx, |_, window, _| {
9230 style.text.line_height_in_pixels(window.rem_size())
9231 })
9232 .unwrap();
9233 let element = EditorElement::new(&editor, style);
9234 let snapshot = window
9235 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
9236 .unwrap();
9237
9238 let layouts = cx
9239 .update_window(*window, |_, window, cx| {
9240 element.layout_line_numbers(
9241 None,
9242 GutterDimensions {
9243 left_padding: Pixels::ZERO,
9244 right_padding: Pixels::ZERO,
9245 width: px(30.0),
9246 margin: Pixels::ZERO,
9247 git_blame_entries_width: None,
9248 },
9249 line_height,
9250 gpui::Point::default(),
9251 DisplayRow(0)..DisplayRow(6),
9252 &(0..6)
9253 .map(|row| RowInfo {
9254 buffer_row: Some(row),
9255 ..Default::default()
9256 })
9257 .collect::<Vec<_>>(),
9258 &BTreeMap::default(),
9259 Some(DisplayPoint::new(DisplayRow(0), 0)),
9260 &snapshot,
9261 window,
9262 cx,
9263 )
9264 })
9265 .unwrap();
9266 assert_eq!(layouts.len(), 6);
9267
9268 let relative_rows = window
9269 .update(cx, |editor, window, cx| {
9270 let snapshot = editor.snapshot(window, cx);
9271 element.calculate_relative_line_numbers(
9272 &snapshot,
9273 &(DisplayRow(0)..DisplayRow(6)),
9274 Some(DisplayRow(3)),
9275 )
9276 })
9277 .unwrap();
9278 assert_eq!(relative_rows[&DisplayRow(0)], 3);
9279 assert_eq!(relative_rows[&DisplayRow(1)], 2);
9280 assert_eq!(relative_rows[&DisplayRow(2)], 1);
9281 // current line has no relative number
9282 assert_eq!(relative_rows[&DisplayRow(4)], 1);
9283 assert_eq!(relative_rows[&DisplayRow(5)], 2);
9284
9285 // works if cursor is before screen
9286 let relative_rows = window
9287 .update(cx, |editor, window, cx| {
9288 let snapshot = editor.snapshot(window, cx);
9289 element.calculate_relative_line_numbers(
9290 &snapshot,
9291 &(DisplayRow(3)..DisplayRow(6)),
9292 Some(DisplayRow(1)),
9293 )
9294 })
9295 .unwrap();
9296 assert_eq!(relative_rows.len(), 3);
9297 assert_eq!(relative_rows[&DisplayRow(3)], 2);
9298 assert_eq!(relative_rows[&DisplayRow(4)], 3);
9299 assert_eq!(relative_rows[&DisplayRow(5)], 4);
9300
9301 // works if cursor is after screen
9302 let relative_rows = window
9303 .update(cx, |editor, window, cx| {
9304 let snapshot = editor.snapshot(window, cx);
9305 element.calculate_relative_line_numbers(
9306 &snapshot,
9307 &(DisplayRow(0)..DisplayRow(3)),
9308 Some(DisplayRow(6)),
9309 )
9310 })
9311 .unwrap();
9312 assert_eq!(relative_rows.len(), 3);
9313 assert_eq!(relative_rows[&DisplayRow(0)], 5);
9314 assert_eq!(relative_rows[&DisplayRow(1)], 4);
9315 assert_eq!(relative_rows[&DisplayRow(2)], 3);
9316 }
9317
9318 #[gpui::test]
9319 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
9320 init_test(cx, |_| {});
9321
9322 let window = cx.add_window(|window, cx| {
9323 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
9324 Editor::new(EditorMode::full(), buffer, None, window, cx)
9325 });
9326 let cx = &mut VisualTestContext::from_window(*window, cx);
9327 let editor = window.root(cx).unwrap();
9328 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9329
9330 window
9331 .update(cx, |editor, window, cx| {
9332 editor.cursor_shape = CursorShape::Block;
9333 editor.change_selections(None, window, cx, |s| {
9334 s.select_ranges([
9335 Point::new(0, 0)..Point::new(1, 0),
9336 Point::new(3, 2)..Point::new(3, 3),
9337 Point::new(5, 6)..Point::new(6, 0),
9338 ]);
9339 });
9340 })
9341 .unwrap();
9342
9343 let (_, state) = cx.draw(
9344 point(px(500.), px(500.)),
9345 size(px(500.), px(500.)),
9346 |_, _| EditorElement::new(&editor, style),
9347 );
9348
9349 assert_eq!(state.selections.len(), 1);
9350 let local_selections = &state.selections[0].1;
9351 assert_eq!(local_selections.len(), 3);
9352 // moves cursor back one line
9353 assert_eq!(
9354 local_selections[0].head,
9355 DisplayPoint::new(DisplayRow(0), 6)
9356 );
9357 assert_eq!(
9358 local_selections[0].range,
9359 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
9360 );
9361
9362 // moves cursor back one column
9363 assert_eq!(
9364 local_selections[1].range,
9365 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
9366 );
9367 assert_eq!(
9368 local_selections[1].head,
9369 DisplayPoint::new(DisplayRow(3), 2)
9370 );
9371
9372 // leaves cursor on the max point
9373 assert_eq!(
9374 local_selections[2].range,
9375 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
9376 );
9377 assert_eq!(
9378 local_selections[2].head,
9379 DisplayPoint::new(DisplayRow(6), 0)
9380 );
9381
9382 // active lines does not include 1 (even though the range of the selection does)
9383 assert_eq!(
9384 state.active_rows.keys().cloned().collect::<Vec<_>>(),
9385 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
9386 );
9387 }
9388
9389 #[gpui::test]
9390 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
9391 init_test(cx, |_| {});
9392
9393 let window = cx.add_window(|window, cx| {
9394 let buffer = MultiBuffer::build_simple("", cx);
9395 Editor::new(EditorMode::full(), buffer, None, window, cx)
9396 });
9397 let cx = &mut VisualTestContext::from_window(*window, cx);
9398 let editor = window.root(cx).unwrap();
9399 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9400 window
9401 .update(cx, |editor, window, cx| {
9402 editor.set_placeholder_text("hello", cx);
9403 editor.insert_blocks(
9404 [BlockProperties {
9405 style: BlockStyle::Fixed,
9406 placement: BlockPlacement::Above(Anchor::min()),
9407 height: Some(3),
9408 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
9409 priority: 0,
9410 render_in_minimap: true,
9411 }],
9412 None,
9413 cx,
9414 );
9415
9416 // Blur the editor so that it displays placeholder text.
9417 window.blur();
9418 })
9419 .unwrap();
9420
9421 let (_, state) = cx.draw(
9422 point(px(500.), px(500.)),
9423 size(px(500.), px(500.)),
9424 |_, _| EditorElement::new(&editor, style),
9425 );
9426 assert_eq!(state.position_map.line_layouts.len(), 4);
9427 assert_eq!(state.line_numbers.len(), 1);
9428 assert_eq!(
9429 state
9430 .line_numbers
9431 .get(&MultiBufferRow(0))
9432 .map(|line_number| line_number.shaped_line.text.as_ref()),
9433 Some("1")
9434 );
9435 }
9436
9437 #[gpui::test]
9438 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
9439 const TAB_SIZE: u32 = 4;
9440
9441 let input_text = "\t \t|\t| a b";
9442 let expected_invisibles = vec![
9443 Invisible::Tab {
9444 line_start_offset: 0,
9445 line_end_offset: TAB_SIZE as usize,
9446 },
9447 Invisible::Whitespace {
9448 line_offset: TAB_SIZE as usize,
9449 },
9450 Invisible::Tab {
9451 line_start_offset: TAB_SIZE as usize + 1,
9452 line_end_offset: TAB_SIZE as usize * 2,
9453 },
9454 Invisible::Tab {
9455 line_start_offset: TAB_SIZE as usize * 2 + 1,
9456 line_end_offset: TAB_SIZE as usize * 3,
9457 },
9458 Invisible::Whitespace {
9459 line_offset: TAB_SIZE as usize * 3 + 1,
9460 },
9461 Invisible::Whitespace {
9462 line_offset: TAB_SIZE as usize * 3 + 3,
9463 },
9464 ];
9465 assert_eq!(
9466 expected_invisibles.len(),
9467 input_text
9468 .chars()
9469 .filter(|initial_char| initial_char.is_whitespace())
9470 .count(),
9471 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9472 );
9473
9474 for show_line_numbers in [true, false] {
9475 init_test(cx, |s| {
9476 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9477 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
9478 });
9479
9480 let actual_invisibles = collect_invisibles_from_new_editor(
9481 cx,
9482 EditorMode::full(),
9483 input_text,
9484 px(500.0),
9485 show_line_numbers,
9486 );
9487
9488 assert_eq!(expected_invisibles, actual_invisibles);
9489 }
9490 }
9491
9492 #[gpui::test]
9493 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
9494 init_test(cx, |s| {
9495 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9496 s.defaults.tab_size = NonZeroU32::new(4);
9497 });
9498
9499 for editor_mode_without_invisibles in [
9500 EditorMode::SingleLine { auto_width: false },
9501 EditorMode::AutoHeight { max_lines: 100 },
9502 ] {
9503 for show_line_numbers in [true, false] {
9504 let invisibles = collect_invisibles_from_new_editor(
9505 cx,
9506 editor_mode_without_invisibles.clone(),
9507 "\t\t\t| | a b",
9508 px(500.0),
9509 show_line_numbers,
9510 );
9511 assert!(
9512 invisibles.is_empty(),
9513 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
9514 );
9515 }
9516 }
9517 }
9518
9519 #[gpui::test]
9520 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
9521 let tab_size = 4;
9522 let input_text = "a\tbcd ".repeat(9);
9523 let repeated_invisibles = [
9524 Invisible::Tab {
9525 line_start_offset: 1,
9526 line_end_offset: tab_size as usize,
9527 },
9528 Invisible::Whitespace {
9529 line_offset: tab_size as usize + 3,
9530 },
9531 Invisible::Whitespace {
9532 line_offset: tab_size as usize + 4,
9533 },
9534 Invisible::Whitespace {
9535 line_offset: tab_size as usize + 5,
9536 },
9537 Invisible::Whitespace {
9538 line_offset: tab_size as usize + 6,
9539 },
9540 Invisible::Whitespace {
9541 line_offset: tab_size as usize + 7,
9542 },
9543 ];
9544 let expected_invisibles = std::iter::once(repeated_invisibles)
9545 .cycle()
9546 .take(9)
9547 .flatten()
9548 .collect::<Vec<_>>();
9549 assert_eq!(
9550 expected_invisibles.len(),
9551 input_text
9552 .chars()
9553 .filter(|initial_char| initial_char.is_whitespace())
9554 .count(),
9555 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9556 );
9557 info!("Expected invisibles: {expected_invisibles:?}");
9558
9559 init_test(cx, |_| {});
9560
9561 // Put the same string with repeating whitespace pattern into editors of various size,
9562 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
9563 let resize_step = 10.0;
9564 let mut editor_width = 200.0;
9565 while editor_width <= 1000.0 {
9566 for show_line_numbers in [true, false] {
9567 update_test_language_settings(cx, |s| {
9568 s.defaults.tab_size = NonZeroU32::new(tab_size);
9569 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9570 s.defaults.preferred_line_length = Some(editor_width as u32);
9571 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
9572 });
9573
9574 let actual_invisibles = collect_invisibles_from_new_editor(
9575 cx,
9576 EditorMode::full(),
9577 &input_text,
9578 px(editor_width),
9579 show_line_numbers,
9580 );
9581
9582 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
9583 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
9584 let mut i = 0;
9585 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
9586 i = actual_index;
9587 match expected_invisibles.get(i) {
9588 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
9589 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
9590 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
9591 _ => {
9592 panic!(
9593 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
9594 )
9595 }
9596 },
9597 None => {
9598 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
9599 }
9600 }
9601 }
9602 let missing_expected_invisibles = &expected_invisibles[i + 1..];
9603 assert!(
9604 missing_expected_invisibles.is_empty(),
9605 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
9606 );
9607
9608 editor_width += resize_step;
9609 }
9610 }
9611 }
9612
9613 fn collect_invisibles_from_new_editor(
9614 cx: &mut TestAppContext,
9615 editor_mode: EditorMode,
9616 input_text: &str,
9617 editor_width: Pixels,
9618 show_line_numbers: bool,
9619 ) -> Vec<Invisible> {
9620 info!(
9621 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
9622 editor_width.0
9623 );
9624 let window = cx.add_window(|window, cx| {
9625 let buffer = MultiBuffer::build_simple(input_text, cx);
9626 Editor::new(editor_mode, buffer, None, window, cx)
9627 });
9628 let cx = &mut VisualTestContext::from_window(*window, cx);
9629 let editor = window.root(cx).unwrap();
9630
9631 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9632 window
9633 .update(cx, |editor, _, cx| {
9634 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
9635 editor.set_wrap_width(Some(editor_width), cx);
9636 editor.set_show_line_numbers(show_line_numbers, cx);
9637 })
9638 .unwrap();
9639 let (_, state) = cx.draw(
9640 point(px(500.), px(500.)),
9641 size(px(500.), px(500.)),
9642 |_, _| EditorElement::new(&editor, style),
9643 );
9644 state
9645 .position_map
9646 .line_layouts
9647 .iter()
9648 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
9649 .cloned()
9650 .collect()
9651 }
9652}