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