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