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