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