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.hover_state.render(
3918 snapshot,
3919 visible_display_row_range.clone(),
3920 max_size,
3921 window,
3922 cx,
3923 )
3924 });
3925 let Some((position, hover_popovers)) = hover_popovers else {
3926 return;
3927 };
3928
3929 // This is safe because we check on layout whether the required row is available
3930 let hovered_row_layout =
3931 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3932
3933 // Compute Hovered Point
3934 let x =
3935 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3936 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3937 let hovered_point = content_origin + point(x, y);
3938
3939 let mut overall_height = Pixels::ZERO;
3940 let mut measured_hover_popovers = Vec::new();
3941 for mut hover_popover in hover_popovers {
3942 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
3943 let horizontal_offset =
3944 (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3945
3946 overall_height += HOVER_POPOVER_GAP + size.height;
3947
3948 measured_hover_popovers.push(MeasuredHoverPopover {
3949 element: hover_popover,
3950 size,
3951 horizontal_offset,
3952 });
3953 }
3954 overall_height += HOVER_POPOVER_GAP;
3955
3956 fn draw_occluder(
3957 width: Pixels,
3958 origin: gpui::Point<Pixels>,
3959 window: &mut Window,
3960 cx: &mut App,
3961 ) {
3962 let mut occlusion = div()
3963 .size_full()
3964 .occlude()
3965 .on_mouse_move(|_, _, cx| cx.stop_propagation())
3966 .into_any_element();
3967 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
3968 window.defer_draw(occlusion, origin, 2);
3969 }
3970
3971 if hovered_point.y > overall_height {
3972 // There is enough space above. Render popovers above the hovered point
3973 let mut current_y = hovered_point.y;
3974 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3975 let size = popover.size;
3976 let popover_origin = point(
3977 hovered_point.x + popover.horizontal_offset,
3978 current_y - size.height,
3979 );
3980
3981 window.defer_draw(popover.element, popover_origin, 2);
3982 if position != itertools::Position::Last {
3983 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3984 draw_occluder(size.width, origin, window, cx);
3985 }
3986
3987 current_y = popover_origin.y - HOVER_POPOVER_GAP;
3988 }
3989 } else {
3990 // There is not enough space above. Render popovers below the hovered point
3991 let mut current_y = hovered_point.y + line_height;
3992 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3993 let size = popover.size;
3994 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3995
3996 window.defer_draw(popover.element, popover_origin, 2);
3997 if position != itertools::Position::Last {
3998 let origin = point(popover_origin.x, popover_origin.y + size.height);
3999 draw_occluder(size.width, origin, window, cx);
4000 }
4001
4002 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4003 }
4004 }
4005 }
4006
4007 fn layout_diff_hunk_controls(
4008 &self,
4009 row_range: Range<DisplayRow>,
4010 row_infos: &[RowInfo],
4011 text_hitbox: &Hitbox,
4012 position_map: &PositionMap,
4013 newest_cursor_position: Option<DisplayPoint>,
4014 line_height: Pixels,
4015 scroll_pixel_position: gpui::Point<Pixels>,
4016 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4017 editor: Entity<Editor>,
4018 window: &mut Window,
4019 cx: &mut App,
4020 ) -> Vec<AnyElement> {
4021 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
4022 let point_for_position = position_map.point_for_position(window.mouse_position());
4023
4024 let mut controls = vec![];
4025
4026 let active_positions = [
4027 Some(point_for_position.previous_valid),
4028 newest_cursor_position,
4029 ];
4030
4031 for (hunk, _) in display_hunks {
4032 if let DisplayDiffHunk::Unfolded {
4033 display_row_range,
4034 multi_buffer_range,
4035 status,
4036 is_created_file,
4037 ..
4038 } = &hunk
4039 {
4040 if display_row_range.start < row_range.start
4041 || display_row_range.start >= row_range.end
4042 {
4043 continue;
4044 }
4045 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4046 if row_infos[row_ix].diff_status.is_none() {
4047 continue;
4048 }
4049 if row_infos[row_ix]
4050 .diff_status
4051 .is_some_and(|status| status.is_added())
4052 && !status.is_added()
4053 {
4054 continue;
4055 }
4056 if active_positions
4057 .iter()
4058 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4059 {
4060 let y = display_row_range.start.as_f32() * line_height
4061 + text_hitbox.bounds.top()
4062 - scroll_pixel_position.y;
4063
4064 let mut element = render_diff_hunk_controls(
4065 display_row_range.start.0,
4066 status,
4067 multi_buffer_range.clone(),
4068 *is_created_file,
4069 line_height,
4070 &editor,
4071 window,
4072 cx,
4073 );
4074 let size =
4075 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
4076
4077 let x = text_hitbox.bounds.right()
4078 - self.style.scrollbar_width
4079 - px(10.)
4080 - size.width;
4081
4082 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
4083 element.prepaint(window, cx)
4084 });
4085 controls.push(element);
4086 }
4087 }
4088 }
4089
4090 controls
4091 }
4092
4093 fn layout_signature_help(
4094 &self,
4095 hitbox: &Hitbox,
4096 content_origin: gpui::Point<Pixels>,
4097 scroll_pixel_position: gpui::Point<Pixels>,
4098 newest_selection_head: Option<DisplayPoint>,
4099 start_row: DisplayRow,
4100 line_layouts: &[LineWithInvisibles],
4101 line_height: Pixels,
4102 em_width: Pixels,
4103 window: &mut Window,
4104 cx: &mut App,
4105 ) {
4106 if !self.editor.focus_handle(cx).is_focused(window) {
4107 return;
4108 }
4109 let Some(newest_selection_head) = newest_selection_head else {
4110 return;
4111 };
4112 let selection_row = newest_selection_head.row();
4113 if selection_row < start_row {
4114 return;
4115 }
4116 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4117 else {
4118 return;
4119 };
4120
4121 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4122 - scroll_pixel_position.x
4123 + content_origin.x;
4124 let start_y =
4125 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4126
4127 let max_size = size(
4128 (120. * em_width) // Default size
4129 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4130 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4131 (16. * line_height) // Default size
4132 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4133 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4134 );
4135
4136 let maybe_element = self.editor.update(cx, |editor, cx| {
4137 if let Some(popover) = editor.signature_help_state.popover_mut() {
4138 let element = popover.render(max_size, cx);
4139 Some(element)
4140 } else {
4141 None
4142 }
4143 });
4144 if let Some(mut element) = maybe_element {
4145 let window_size = window.viewport_size();
4146 let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4147 let mut point = point(start_x, start_y - size.height);
4148
4149 // Adjusting to ensure the popover does not overflow in the X-axis direction.
4150 if point.x + size.width >= window_size.width {
4151 point.x = window_size.width - size.width;
4152 }
4153
4154 window.defer_draw(element, point, 1)
4155 }
4156 }
4157
4158 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4159 window.paint_layer(layout.hitbox.bounds, |window| {
4160 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4161 let gutter_bg = cx.theme().colors().editor_gutter_background;
4162 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4163 window.paint_quad(fill(
4164 layout.position_map.text_hitbox.bounds,
4165 self.style.background,
4166 ));
4167
4168 if let EditorMode::Full = layout.mode {
4169 let mut active_rows = layout.active_rows.iter().peekable();
4170 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4171 let mut end_row = start_row.0;
4172 while active_rows
4173 .peek()
4174 .map_or(false, |(active_row, has_selection)| {
4175 active_row.0 == end_row + 1
4176 && has_selection.selection == contains_non_empty_selection.selection
4177 })
4178 {
4179 active_rows.next().unwrap();
4180 end_row += 1;
4181 }
4182
4183 if !contains_non_empty_selection.selection {
4184 let highlight_h_range =
4185 match layout.position_map.snapshot.current_line_highlight {
4186 CurrentLineHighlight::Gutter => Some(Range {
4187 start: layout.hitbox.left(),
4188 end: layout.gutter_hitbox.right(),
4189 }),
4190 CurrentLineHighlight::Line => Some(Range {
4191 start: layout.position_map.text_hitbox.bounds.left(),
4192 end: layout.position_map.text_hitbox.bounds.right(),
4193 }),
4194 CurrentLineHighlight::All => Some(Range {
4195 start: layout.hitbox.left(),
4196 end: layout.hitbox.right(),
4197 }),
4198 CurrentLineHighlight::None => None,
4199 };
4200 if let Some(range) = highlight_h_range {
4201 let active_line_bg = cx.theme().colors().editor_active_line_background;
4202 let bounds = Bounds {
4203 origin: point(
4204 range.start,
4205 layout.hitbox.origin.y
4206 + (start_row.as_f32() - scroll_top)
4207 * layout.position_map.line_height,
4208 ),
4209 size: size(
4210 range.end - range.start,
4211 layout.position_map.line_height
4212 * (end_row - start_row.0 + 1) as f32,
4213 ),
4214 };
4215 window.paint_quad(fill(bounds, active_line_bg));
4216 }
4217 }
4218 }
4219
4220 let mut paint_highlight = |highlight_row_start: DisplayRow,
4221 highlight_row_end: DisplayRow,
4222 highlight: crate::LineHighlight,
4223 edges| {
4224 let origin = point(
4225 layout.hitbox.origin.x,
4226 layout.hitbox.origin.y
4227 + (highlight_row_start.as_f32() - scroll_top)
4228 * layout.position_map.line_height,
4229 );
4230 let size = size(
4231 layout.hitbox.size.width,
4232 layout.position_map.line_height
4233 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4234 );
4235 let mut quad = fill(Bounds { origin, size }, highlight.background);
4236 if let Some(border_color) = highlight.border {
4237 quad.border_color = border_color;
4238 quad.border_widths = edges
4239 }
4240 window.paint_quad(quad);
4241 };
4242
4243 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
4244 None;
4245 for (&new_row, &new_background) in &layout.highlighted_rows {
4246 match &mut current_paint {
4247 &mut Some((current_background, ref mut current_range, mut edges)) => {
4248 let new_range_started = current_background != new_background
4249 || current_range.end.next_row() != new_row;
4250 if new_range_started {
4251 if current_range.end.next_row() == new_row {
4252 edges.bottom = px(0.);
4253 };
4254 paint_highlight(
4255 current_range.start,
4256 current_range.end,
4257 current_background,
4258 edges,
4259 );
4260 let edges = Edges {
4261 top: if current_range.end.next_row() != new_row {
4262 px(1.)
4263 } else {
4264 px(0.)
4265 },
4266 bottom: px(1.),
4267 ..Default::default()
4268 };
4269 current_paint = Some((new_background, new_row..new_row, edges));
4270 continue;
4271 } else {
4272 current_range.end = current_range.end.next_row();
4273 }
4274 }
4275 None => {
4276 let edges = Edges {
4277 top: px(1.),
4278 bottom: px(1.),
4279 ..Default::default()
4280 };
4281 current_paint = Some((new_background, new_row..new_row, edges))
4282 }
4283 };
4284 }
4285 if let Some((color, range, edges)) = current_paint {
4286 paint_highlight(range.start, range.end, color, edges);
4287 }
4288
4289 let scroll_left =
4290 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4291
4292 for (wrap_position, active) in layout.wrap_guides.iter() {
4293 let x = (layout.position_map.text_hitbox.origin.x
4294 + *wrap_position
4295 + layout.position_map.em_width / 2.)
4296 - scroll_left;
4297
4298 let show_scrollbars = layout
4299 .scrollbars_layout
4300 .as_ref()
4301 .map_or(false, |layout| layout.visible);
4302
4303 if x < layout.position_map.text_hitbox.origin.x
4304 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4305 {
4306 continue;
4307 }
4308
4309 let color = if *active {
4310 cx.theme().colors().editor_active_wrap_guide
4311 } else {
4312 cx.theme().colors().editor_wrap_guide
4313 };
4314 window.paint_quad(fill(
4315 Bounds {
4316 origin: point(x, layout.position_map.text_hitbox.origin.y),
4317 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4318 },
4319 color,
4320 ));
4321 }
4322 }
4323 })
4324 }
4325
4326 fn paint_indent_guides(
4327 &mut self,
4328 layout: &mut EditorLayout,
4329 window: &mut Window,
4330 cx: &mut App,
4331 ) {
4332 let Some(indent_guides) = &layout.indent_guides else {
4333 return;
4334 };
4335
4336 let faded_color = |color: Hsla, alpha: f32| {
4337 let mut faded = color;
4338 faded.a = alpha;
4339 faded
4340 };
4341
4342 for indent_guide in indent_guides {
4343 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4344 let settings = indent_guide.settings;
4345
4346 // TODO fixed for now, expose them through themes later
4347 const INDENT_AWARE_ALPHA: f32 = 0.2;
4348 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4349 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4350 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4351
4352 let line_color = match (settings.coloring, indent_guide.active) {
4353 (IndentGuideColoring::Disabled, _) => None,
4354 (IndentGuideColoring::Fixed, false) => {
4355 Some(cx.theme().colors().editor_indent_guide)
4356 }
4357 (IndentGuideColoring::Fixed, true) => {
4358 Some(cx.theme().colors().editor_indent_guide_active)
4359 }
4360 (IndentGuideColoring::IndentAware, false) => {
4361 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4362 }
4363 (IndentGuideColoring::IndentAware, true) => {
4364 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4365 }
4366 };
4367
4368 let background_color = match (settings.background_coloring, indent_guide.active) {
4369 (IndentGuideBackgroundColoring::Disabled, _) => None,
4370 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4371 indent_accent_colors,
4372 INDENT_AWARE_BACKGROUND_ALPHA,
4373 )),
4374 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4375 indent_accent_colors,
4376 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4377 )),
4378 };
4379
4380 let requested_line_width = if indent_guide.active {
4381 settings.active_line_width
4382 } else {
4383 settings.line_width
4384 }
4385 .clamp(1, 10);
4386 let mut line_indicator_width = 0.;
4387 if let Some(color) = line_color {
4388 window.paint_quad(fill(
4389 Bounds {
4390 origin: indent_guide.origin,
4391 size: size(px(requested_line_width as f32), indent_guide.length),
4392 },
4393 color,
4394 ));
4395 line_indicator_width = requested_line_width as f32;
4396 }
4397
4398 if let Some(color) = background_color {
4399 let width = indent_guide.single_indent_width - px(line_indicator_width);
4400 window.paint_quad(fill(
4401 Bounds {
4402 origin: point(
4403 indent_guide.origin.x + px(line_indicator_width),
4404 indent_guide.origin.y,
4405 ),
4406 size: size(width, indent_guide.length),
4407 },
4408 color,
4409 ));
4410 }
4411 }
4412 }
4413
4414 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4415 let is_singleton = self.editor.read(cx).is_singleton(cx);
4416
4417 let line_height = layout.position_map.line_height;
4418 window.set_cursor_style(CursorStyle::Arrow, Some(&layout.gutter_hitbox));
4419
4420 for LineNumberLayout {
4421 shaped_line,
4422 hitbox,
4423 } in layout.line_numbers.values()
4424 {
4425 let Some(hitbox) = hitbox else {
4426 continue;
4427 };
4428
4429 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
4430 let color = cx.theme().colors().editor_hover_line_number;
4431
4432 let Some(line) = self
4433 .shape_line_number(shaped_line.text.clone(), color, window)
4434 .log_err()
4435 else {
4436 continue;
4437 };
4438
4439 line.paint(hitbox.origin, line_height, window, cx).log_err()
4440 } else {
4441 shaped_line
4442 .paint(hitbox.origin, line_height, window, cx)
4443 .log_err()
4444 }) else {
4445 continue;
4446 };
4447
4448 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4449 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4450 if is_singleton {
4451 window.set_cursor_style(CursorStyle::IBeam, Some(&hitbox));
4452 } else {
4453 window.set_cursor_style(CursorStyle::PointingHand, Some(&hitbox));
4454 }
4455 }
4456 }
4457
4458 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4459 if layout.display_hunks.is_empty() {
4460 return;
4461 }
4462
4463 let line_height = layout.position_map.line_height;
4464 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4465 for (hunk, hitbox) in &layout.display_hunks {
4466 let hunk_to_paint = match hunk {
4467 DisplayDiffHunk::Folded { .. } => {
4468 let hunk_bounds = Self::diff_hunk_bounds(
4469 &layout.position_map.snapshot,
4470 line_height,
4471 layout.gutter_hitbox.bounds,
4472 &hunk,
4473 );
4474 Some((
4475 hunk_bounds,
4476 cx.theme().colors().version_control_modified,
4477 Corners::all(px(0.)),
4478 DiffHunkStatus::modified_none(),
4479 ))
4480 }
4481 DisplayDiffHunk::Unfolded {
4482 status,
4483 display_row_range,
4484 ..
4485 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
4486 DiffHunkStatusKind::Added => (
4487 hunk_hitbox.bounds,
4488 cx.theme().colors().version_control_added,
4489 Corners::all(px(0.)),
4490 *status,
4491 ),
4492 DiffHunkStatusKind::Modified => (
4493 hunk_hitbox.bounds,
4494 cx.theme().colors().version_control_modified,
4495 Corners::all(px(0.)),
4496 *status,
4497 ),
4498 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
4499 hunk_hitbox.bounds,
4500 cx.theme().colors().version_control_deleted,
4501 Corners::all(px(0.)),
4502 *status,
4503 ),
4504 DiffHunkStatusKind::Deleted => (
4505 Bounds::new(
4506 point(
4507 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4508 hunk_hitbox.origin.y,
4509 ),
4510 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
4511 ),
4512 cx.theme().colors().version_control_deleted,
4513 Corners::all(1. * line_height),
4514 *status,
4515 ),
4516 }),
4517 };
4518
4519 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
4520 // Flatten the background color with the editor color to prevent
4521 // elements below transparent hunks from showing through
4522 let flattened_background_color = cx
4523 .theme()
4524 .colors()
4525 .editor_background
4526 .blend(background_color);
4527
4528 if !Self::diff_hunk_hollow(status, cx) {
4529 window.paint_quad(quad(
4530 hunk_bounds,
4531 corner_radii,
4532 flattened_background_color,
4533 Edges::default(),
4534 transparent_black(),
4535 BorderStyle::default(),
4536 ));
4537 } else {
4538 let flattened_unstaged_background_color = cx
4539 .theme()
4540 .colors()
4541 .editor_background
4542 .blend(background_color.opacity(0.3));
4543
4544 window.paint_quad(quad(
4545 hunk_bounds,
4546 corner_radii,
4547 flattened_unstaged_background_color,
4548 Edges::all(Pixels(1.0)),
4549 flattened_background_color,
4550 BorderStyle::Solid,
4551 ));
4552 }
4553 }
4554 }
4555 });
4556 }
4557
4558 fn gutter_strip_width(line_height: Pixels) -> Pixels {
4559 (0.275 * line_height).floor()
4560 }
4561
4562 fn diff_hunk_bounds(
4563 snapshot: &EditorSnapshot,
4564 line_height: Pixels,
4565 gutter_bounds: Bounds<Pixels>,
4566 hunk: &DisplayDiffHunk,
4567 ) -> Bounds<Pixels> {
4568 let scroll_position = snapshot.scroll_position();
4569 let scroll_top = scroll_position.y * line_height;
4570 let gutter_strip_width = Self::gutter_strip_width(line_height);
4571
4572 match hunk {
4573 DisplayDiffHunk::Folded { display_row, .. } => {
4574 let start_y = display_row.as_f32() * line_height - scroll_top;
4575 let end_y = start_y + line_height;
4576 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4577 let highlight_size = size(gutter_strip_width, end_y - start_y);
4578 Bounds::new(highlight_origin, highlight_size)
4579 }
4580 DisplayDiffHunk::Unfolded {
4581 display_row_range,
4582 status,
4583 ..
4584 } => {
4585 if status.is_deleted() && display_row_range.is_empty() {
4586 let row = display_row_range.start;
4587
4588 let offset = line_height / 2.;
4589 let start_y = row.as_f32() * line_height - offset - scroll_top;
4590 let end_y = start_y + line_height;
4591
4592 let width = (0.35 * line_height).floor();
4593 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4594 let highlight_size = size(width, end_y - start_y);
4595 Bounds::new(highlight_origin, highlight_size)
4596 } else {
4597 let start_row = display_row_range.start;
4598 let end_row = display_row_range.end;
4599 // If we're in a multibuffer, row range span might include an
4600 // excerpt header, so if we were to draw the marker straight away,
4601 // the hunk might include the rows of that header.
4602 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4603 // Instead, we simply check whether the range we're dealing with includes
4604 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4605 let end_row_in_current_excerpt = snapshot
4606 .blocks_in_range(start_row..end_row)
4607 .find_map(|(start_row, block)| {
4608 if matches!(block, Block::ExcerptBoundary { .. }) {
4609 Some(start_row)
4610 } else {
4611 None
4612 }
4613 })
4614 .unwrap_or(end_row);
4615
4616 let start_y = start_row.as_f32() * line_height - scroll_top;
4617 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4618
4619 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4620 let highlight_size = size(gutter_strip_width, end_y - start_y);
4621 Bounds::new(highlight_origin, highlight_size)
4622 }
4623 }
4624 }
4625 }
4626
4627 fn paint_gutter_indicators(
4628 &self,
4629 layout: &mut EditorLayout,
4630 window: &mut Window,
4631 cx: &mut App,
4632 ) {
4633 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4634 window.with_element_namespace("crease_toggles", |window| {
4635 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4636 crease_toggle.paint(window, cx);
4637 }
4638 });
4639
4640 window.with_element_namespace("expand_toggles", |window| {
4641 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
4642 expand_toggle.paint(window, cx);
4643 }
4644 });
4645
4646 for breakpoint in layout.breakpoints.iter_mut() {
4647 breakpoint.paint(window, cx);
4648 }
4649
4650 for test_indicator in layout.test_indicators.iter_mut() {
4651 test_indicator.paint(window, cx);
4652 }
4653
4654 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4655 indicator.paint(window, cx);
4656 }
4657 });
4658 }
4659
4660 fn paint_gutter_highlights(
4661 &self,
4662 layout: &mut EditorLayout,
4663 window: &mut Window,
4664 cx: &mut App,
4665 ) {
4666 for (_, hunk_hitbox) in &layout.display_hunks {
4667 if let Some(hunk_hitbox) = hunk_hitbox {
4668 if !self
4669 .editor
4670 .read(cx)
4671 .buffer()
4672 .read(cx)
4673 .all_diff_hunks_expanded()
4674 {
4675 window.set_cursor_style(CursorStyle::PointingHand, Some(hunk_hitbox));
4676 }
4677 }
4678 }
4679
4680 let show_git_gutter = layout
4681 .position_map
4682 .snapshot
4683 .show_git_diff_gutter
4684 .unwrap_or_else(|| {
4685 matches!(
4686 ProjectSettings::get_global(cx).git.git_gutter,
4687 Some(GitGutterSetting::TrackedFiles)
4688 )
4689 });
4690 if show_git_gutter {
4691 Self::paint_gutter_diff_hunks(layout, window, cx)
4692 }
4693
4694 let highlight_width = 0.275 * layout.position_map.line_height;
4695 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4696 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4697 for (range, color) in &layout.highlighted_gutter_ranges {
4698 let start_row = if range.start.row() < layout.visible_display_row_range.start {
4699 layout.visible_display_row_range.start - DisplayRow(1)
4700 } else {
4701 range.start.row()
4702 };
4703 let end_row = if range.end.row() > layout.visible_display_row_range.end {
4704 layout.visible_display_row_range.end + DisplayRow(1)
4705 } else {
4706 range.end.row()
4707 };
4708
4709 let start_y = layout.gutter_hitbox.top()
4710 + start_row.0 as f32 * layout.position_map.line_height
4711 - layout.position_map.scroll_pixel_position.y;
4712 let end_y = layout.gutter_hitbox.top()
4713 + (end_row.0 + 1) as f32 * layout.position_map.line_height
4714 - layout.position_map.scroll_pixel_position.y;
4715 let bounds = Bounds::from_corners(
4716 point(layout.gutter_hitbox.left(), start_y),
4717 point(layout.gutter_hitbox.left() + highlight_width, end_y),
4718 );
4719 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4720 }
4721 });
4722 }
4723
4724 fn paint_blamed_display_rows(
4725 &self,
4726 layout: &mut EditorLayout,
4727 window: &mut Window,
4728 cx: &mut App,
4729 ) {
4730 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4731 return;
4732 };
4733
4734 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4735 for mut blame_element in blamed_display_rows.into_iter() {
4736 blame_element.paint(window, cx);
4737 }
4738 })
4739 }
4740
4741 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4742 window.with_content_mask(
4743 Some(ContentMask {
4744 bounds: layout.position_map.text_hitbox.bounds,
4745 }),
4746 |window| {
4747 let editor = self.editor.read(cx);
4748 if editor.mouse_cursor_hidden {
4749 window.set_cursor_style(CursorStyle::None, None);
4750 } else if editor
4751 .hovered_link_state
4752 .as_ref()
4753 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4754 {
4755 window.set_cursor_style(
4756 CursorStyle::PointingHand,
4757 Some(&layout.position_map.text_hitbox),
4758 );
4759 } else {
4760 window.set_cursor_style(
4761 CursorStyle::IBeam,
4762 Some(&layout.position_map.text_hitbox),
4763 );
4764 };
4765
4766 self.paint_lines_background(layout, window, cx);
4767 let invisible_display_ranges = self.paint_highlights(layout, window);
4768 self.paint_lines(&invisible_display_ranges, layout, window, cx);
4769 self.paint_redactions(layout, window);
4770 self.paint_cursors(layout, window, cx);
4771 self.paint_inline_diagnostics(layout, window, cx);
4772 self.paint_inline_blame(layout, window, cx);
4773 self.paint_diff_hunk_controls(layout, window, cx);
4774 window.with_element_namespace("crease_trailers", |window| {
4775 for trailer in layout.crease_trailers.iter_mut().flatten() {
4776 trailer.element.paint(window, cx);
4777 }
4778 });
4779 },
4780 )
4781 }
4782
4783 fn paint_highlights(
4784 &mut self,
4785 layout: &mut EditorLayout,
4786 window: &mut Window,
4787 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4788 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4789 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4790 let line_end_overshoot = 0.15 * layout.position_map.line_height;
4791 for (range, color) in &layout.highlighted_ranges {
4792 self.paint_highlighted_range(
4793 range.clone(),
4794 *color,
4795 Pixels::ZERO,
4796 line_end_overshoot,
4797 layout,
4798 window,
4799 );
4800 }
4801
4802 let corner_radius = 0.15 * layout.position_map.line_height;
4803
4804 for (player_color, selections) in &layout.selections {
4805 for selection in selections.iter() {
4806 self.paint_highlighted_range(
4807 selection.range.clone(),
4808 player_color.selection,
4809 corner_radius,
4810 corner_radius * 2.,
4811 layout,
4812 window,
4813 );
4814
4815 if selection.is_local && !selection.range.is_empty() {
4816 invisible_display_ranges.push(selection.range.clone());
4817 }
4818 }
4819 }
4820 invisible_display_ranges
4821 })
4822 }
4823
4824 fn paint_lines(
4825 &mut self,
4826 invisible_display_ranges: &[Range<DisplayPoint>],
4827 layout: &mut EditorLayout,
4828 window: &mut Window,
4829 cx: &mut App,
4830 ) {
4831 let whitespace_setting = self
4832 .editor
4833 .read(cx)
4834 .buffer
4835 .read(cx)
4836 .language_settings(cx)
4837 .show_whitespaces;
4838
4839 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4840 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4841 line_with_invisibles.draw(
4842 layout,
4843 row,
4844 layout.content_origin,
4845 whitespace_setting,
4846 invisible_display_ranges,
4847 window,
4848 cx,
4849 )
4850 }
4851
4852 for line_element in &mut layout.line_elements {
4853 line_element.paint(window, cx);
4854 }
4855 }
4856
4857 fn paint_lines_background(
4858 &mut self,
4859 layout: &mut EditorLayout,
4860 window: &mut Window,
4861 cx: &mut App,
4862 ) {
4863 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4864 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4865 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
4866 }
4867 }
4868
4869 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4870 if layout.redacted_ranges.is_empty() {
4871 return;
4872 }
4873
4874 let line_end_overshoot = layout.line_end_overshoot();
4875
4876 // A softer than perfect black
4877 let redaction_color = gpui::rgb(0x0e1111);
4878
4879 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4880 for range in layout.redacted_ranges.iter() {
4881 self.paint_highlighted_range(
4882 range.clone(),
4883 redaction_color.into(),
4884 Pixels::ZERO,
4885 line_end_overshoot,
4886 layout,
4887 window,
4888 );
4889 }
4890 });
4891 }
4892
4893 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4894 for cursor in &mut layout.visible_cursors {
4895 cursor.paint(layout.content_origin, window, cx);
4896 }
4897 }
4898
4899 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4900 let Some(scrollbars_layout) = &layout.scrollbars_layout else {
4901 return;
4902 };
4903
4904 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
4905 let hitbox = &scrollbar_layout.hitbox;
4906 let thumb_bounds = scrollbar_layout.thumb_bounds();
4907
4908 if scrollbars_layout.visible {
4909 let scrollbar_edges = match axis {
4910 ScrollbarAxis::Horizontal => Edges {
4911 top: Pixels::ZERO,
4912 right: Pixels::ZERO,
4913 bottom: Pixels::ZERO,
4914 left: Pixels::ZERO,
4915 },
4916 ScrollbarAxis::Vertical => Edges {
4917 top: Pixels::ZERO,
4918 right: Pixels::ZERO,
4919 bottom: Pixels::ZERO,
4920 left: ScrollbarLayout::BORDER_WIDTH,
4921 },
4922 };
4923
4924 window.paint_layer(hitbox.bounds, |window| {
4925 window.paint_quad(quad(
4926 hitbox.bounds,
4927 Corners::default(),
4928 cx.theme().colors().scrollbar_track_background,
4929 scrollbar_edges,
4930 cx.theme().colors().scrollbar_track_border,
4931 BorderStyle::Solid,
4932 ));
4933
4934 if axis == ScrollbarAxis::Vertical {
4935 let fast_markers =
4936 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
4937 // Refresh slow scrollbar markers in the background. Below, we
4938 // paint whatever markers have already been computed.
4939 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
4940
4941 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
4942 for marker in markers.iter().chain(&fast_markers) {
4943 let mut marker = marker.clone();
4944 marker.bounds.origin += hitbox.origin;
4945 window.paint_quad(marker);
4946 }
4947 }
4948
4949 window.paint_quad(quad(
4950 thumb_bounds,
4951 Corners::default(),
4952 cx.theme().colors().scrollbar_thumb_background,
4953 scrollbar_edges,
4954 cx.theme().colors().scrollbar_thumb_border,
4955 BorderStyle::Solid,
4956 ));
4957 })
4958 }
4959 window.set_cursor_style(CursorStyle::Arrow, Some(&hitbox));
4960 }
4961
4962 window.on_mouse_event({
4963 let editor = self.editor.clone();
4964 let scrollbars_layout = scrollbars_layout.clone();
4965
4966 let mut mouse_position = window.mouse_position();
4967 move |event: &MouseMoveEvent, phase, window, cx| {
4968 if phase == DispatchPhase::Capture {
4969 return;
4970 }
4971
4972 editor.update(cx, |editor, cx| {
4973 if let Some((scrollbar_layout, axis)) = event
4974 .pressed_button
4975 .filter(|button| *button == MouseButton::Left)
4976 .and(editor.scroll_manager.dragging_scrollbar_axis())
4977 .and_then(|axis| {
4978 scrollbars_layout
4979 .iter_scrollbars()
4980 .find(|(_, a)| *a == axis)
4981 })
4982 {
4983 let ScrollbarLayout {
4984 hitbox,
4985 text_unit_size,
4986 ..
4987 } = scrollbar_layout;
4988
4989 let old_position = mouse_position.along(axis);
4990 let new_position = event.position.along(axis);
4991 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
4992 .contains(&old_position)
4993 {
4994 let position = editor.scroll_position(cx).apply_along(axis, |p| {
4995 (p + (new_position - old_position) / *text_unit_size).max(0.)
4996 });
4997 editor.set_scroll_position(position, window, cx);
4998 }
4999 cx.stop_propagation();
5000 } else {
5001 editor.scroll_manager.reset_scrollbar_dragging_state(cx);
5002 }
5003
5004 if scrollbars_layout.get_hovered_axis(window).is_some() {
5005 editor.scroll_manager.show_scrollbars(window, cx);
5006 }
5007
5008 mouse_position = event.position;
5009 })
5010 }
5011 });
5012
5013 if self.editor.read(cx).scroll_manager.any_scrollbar_dragged() {
5014 window.on_mouse_event({
5015 let editor = self.editor.clone();
5016 move |_: &MouseUpEvent, phase, _, cx| {
5017 if phase == DispatchPhase::Capture {
5018 return;
5019 }
5020
5021 editor.update(cx, |editor, cx| {
5022 editor.scroll_manager.reset_scrollbar_dragging_state(cx);
5023 cx.stop_propagation();
5024 });
5025 }
5026 });
5027 } else {
5028 window.on_mouse_event({
5029 let editor = self.editor.clone();
5030 let scrollbars_layout = scrollbars_layout.clone();
5031
5032 move |event: &MouseDownEvent, phase, window, cx| {
5033 if phase == DispatchPhase::Capture {
5034 return;
5035 }
5036 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
5037 else {
5038 return;
5039 };
5040
5041 let ScrollbarLayout {
5042 hitbox,
5043 visible_range,
5044 text_unit_size,
5045 ..
5046 } = scrollbar_layout;
5047
5048 let thumb_bounds = scrollbar_layout.thumb_bounds();
5049
5050 editor.update(cx, |editor, cx| {
5051 editor.scroll_manager.set_dragged_scrollbar_axis(axis, cx);
5052
5053 let event_position = event.position.along(axis);
5054
5055 if event_position < thumb_bounds.origin.along(axis)
5056 || thumb_bounds.bottom_right().along(axis) < event_position
5057 {
5058 let center_position = ((event_position - hitbox.origin.along(axis))
5059 / *text_unit_size)
5060 .round() as u32;
5061 let start_position = center_position.saturating_sub(
5062 (visible_range.end - visible_range.start) as u32 / 2,
5063 );
5064
5065 let position = editor
5066 .scroll_position(cx)
5067 .apply_along(axis, |_| start_position as f32);
5068
5069 editor.set_scroll_position(position, window, cx);
5070 } else {
5071 editor.scroll_manager.show_scrollbars(window, cx);
5072 }
5073
5074 cx.stop_propagation();
5075 });
5076 }
5077 });
5078 }
5079 }
5080
5081 fn collect_fast_scrollbar_markers(
5082 &self,
5083 layout: &EditorLayout,
5084 scrollbar_layout: &ScrollbarLayout,
5085 cx: &mut App,
5086 ) -> Vec<PaintQuad> {
5087 const LIMIT: usize = 100;
5088 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5089 return vec![];
5090 }
5091 let cursor_ranges = layout
5092 .cursors
5093 .iter()
5094 .map(|(point, color)| ColoredRange {
5095 start: point.row(),
5096 end: point.row(),
5097 color: *color,
5098 })
5099 .collect_vec();
5100 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5101 }
5102
5103 fn refresh_slow_scrollbar_markers(
5104 &self,
5105 layout: &EditorLayout,
5106 scrollbar_layout: &ScrollbarLayout,
5107 window: &mut Window,
5108 cx: &mut App,
5109 ) {
5110 self.editor.update(cx, |editor, cx| {
5111 if !editor.is_singleton(cx)
5112 || !editor
5113 .scrollbar_marker_state
5114 .should_refresh(scrollbar_layout.hitbox.size)
5115 {
5116 return;
5117 }
5118
5119 let scrollbar_layout = scrollbar_layout.clone();
5120 let background_highlights = editor.background_highlights.clone();
5121 let snapshot = layout.position_map.snapshot.clone();
5122 let theme = cx.theme().clone();
5123 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5124
5125 editor.scrollbar_marker_state.dirty = false;
5126 editor.scrollbar_marker_state.pending_refresh =
5127 Some(cx.spawn_in(window, async move |editor, cx| {
5128 let scrollbar_size = scrollbar_layout.hitbox.size;
5129 let scrollbar_markers = cx
5130 .background_spawn(async move {
5131 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5132 let mut marker_quads = Vec::new();
5133 if scrollbar_settings.git_diff {
5134 let marker_row_ranges =
5135 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5136 let start_display_row =
5137 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5138 .to_display_point(&snapshot.display_snapshot)
5139 .row();
5140 let mut end_display_row =
5141 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5142 .to_display_point(&snapshot.display_snapshot)
5143 .row();
5144 if end_display_row != start_display_row {
5145 end_display_row.0 -= 1;
5146 }
5147 let color = match &hunk.status().kind {
5148 DiffHunkStatusKind::Added => {
5149 theme.colors().version_control_added
5150 }
5151 DiffHunkStatusKind::Modified => {
5152 theme.colors().version_control_modified
5153 }
5154 DiffHunkStatusKind::Deleted => {
5155 theme.colors().version_control_deleted
5156 }
5157 };
5158 ColoredRange {
5159 start: start_display_row,
5160 end: end_display_row,
5161 color,
5162 }
5163 });
5164
5165 marker_quads.extend(
5166 scrollbar_layout
5167 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5168 );
5169 }
5170
5171 for (background_highlight_id, (_, background_ranges)) in
5172 background_highlights.iter()
5173 {
5174 let is_search_highlights = *background_highlight_id
5175 == TypeId::of::<BufferSearchHighlights>();
5176 let is_text_highlights = *background_highlight_id
5177 == TypeId::of::<SelectedTextHighlight>();
5178 let is_symbol_occurrences = *background_highlight_id
5179 == TypeId::of::<DocumentHighlightRead>()
5180 || *background_highlight_id
5181 == TypeId::of::<DocumentHighlightWrite>();
5182 if (is_search_highlights && scrollbar_settings.search_results)
5183 || (is_text_highlights && scrollbar_settings.selected_text)
5184 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5185 {
5186 let mut color = theme.status().info;
5187 if is_symbol_occurrences {
5188 color.fade_out(0.5);
5189 }
5190 let marker_row_ranges = background_ranges.iter().map(|range| {
5191 let display_start = range
5192 .start
5193 .to_display_point(&snapshot.display_snapshot);
5194 let display_end =
5195 range.end.to_display_point(&snapshot.display_snapshot);
5196 ColoredRange {
5197 start: display_start.row(),
5198 end: display_end.row(),
5199 color,
5200 }
5201 });
5202 marker_quads.extend(
5203 scrollbar_layout
5204 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5205 );
5206 }
5207 }
5208
5209 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5210 let diagnostics = snapshot
5211 .buffer_snapshot
5212 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5213 // Don't show diagnostics the user doesn't care about
5214 .filter(|diagnostic| {
5215 match (
5216 scrollbar_settings.diagnostics,
5217 diagnostic.diagnostic.severity,
5218 ) {
5219 (ScrollbarDiagnostics::All, _) => true,
5220 (
5221 ScrollbarDiagnostics::Error,
5222 DiagnosticSeverity::ERROR,
5223 ) => true,
5224 (
5225 ScrollbarDiagnostics::Warning,
5226 DiagnosticSeverity::ERROR
5227 | DiagnosticSeverity::WARNING,
5228 ) => true,
5229 (
5230 ScrollbarDiagnostics::Information,
5231 DiagnosticSeverity::ERROR
5232 | DiagnosticSeverity::WARNING
5233 | DiagnosticSeverity::INFORMATION,
5234 ) => true,
5235 (_, _) => false,
5236 }
5237 })
5238 // We want to sort by severity, in order to paint the most severe diagnostics last.
5239 .sorted_by_key(|diagnostic| {
5240 std::cmp::Reverse(diagnostic.diagnostic.severity)
5241 });
5242
5243 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5244 let start_display = diagnostic
5245 .range
5246 .start
5247 .to_display_point(&snapshot.display_snapshot);
5248 let end_display = diagnostic
5249 .range
5250 .end
5251 .to_display_point(&snapshot.display_snapshot);
5252 let color = match diagnostic.diagnostic.severity {
5253 DiagnosticSeverity::ERROR => theme.status().error,
5254 DiagnosticSeverity::WARNING => theme.status().warning,
5255 DiagnosticSeverity::INFORMATION => theme.status().info,
5256 _ => theme.status().hint,
5257 };
5258 ColoredRange {
5259 start: start_display.row(),
5260 end: end_display.row(),
5261 color,
5262 }
5263 });
5264 marker_quads.extend(
5265 scrollbar_layout
5266 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5267 );
5268 }
5269
5270 Arc::from(marker_quads)
5271 })
5272 .await;
5273
5274 editor.update(cx, |editor, cx| {
5275 editor.scrollbar_marker_state.markers = scrollbar_markers;
5276 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5277 editor.scrollbar_marker_state.pending_refresh = None;
5278 cx.notify();
5279 })?;
5280
5281 Ok(())
5282 }));
5283 });
5284 }
5285
5286 fn paint_highlighted_range(
5287 &self,
5288 range: Range<DisplayPoint>,
5289 color: Hsla,
5290 corner_radius: Pixels,
5291 line_end_overshoot: Pixels,
5292 layout: &EditorLayout,
5293 window: &mut Window,
5294 ) {
5295 let start_row = layout.visible_display_row_range.start;
5296 let end_row = layout.visible_display_row_range.end;
5297 if range.start != range.end {
5298 let row_range = if range.end.column() == 0 {
5299 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5300 } else {
5301 cmp::max(range.start.row(), start_row)
5302 ..cmp::min(range.end.row().next_row(), end_row)
5303 };
5304
5305 let highlighted_range = HighlightedRange {
5306 color,
5307 line_height: layout.position_map.line_height,
5308 corner_radius,
5309 start_y: layout.content_origin.y
5310 + row_range.start.as_f32() * layout.position_map.line_height
5311 - layout.position_map.scroll_pixel_position.y,
5312 lines: row_range
5313 .iter_rows()
5314 .map(|row| {
5315 let line_layout =
5316 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5317 HighlightedRangeLine {
5318 start_x: if row == range.start.row() {
5319 layout.content_origin.x
5320 + line_layout.x_for_index(range.start.column() as usize)
5321 - layout.position_map.scroll_pixel_position.x
5322 } else {
5323 layout.content_origin.x
5324 - layout.position_map.scroll_pixel_position.x
5325 },
5326 end_x: if row == range.end.row() {
5327 layout.content_origin.x
5328 + line_layout.x_for_index(range.end.column() as usize)
5329 - layout.position_map.scroll_pixel_position.x
5330 } else {
5331 layout.content_origin.x + line_layout.width + line_end_overshoot
5332 - layout.position_map.scroll_pixel_position.x
5333 },
5334 }
5335 })
5336 .collect(),
5337 };
5338
5339 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5340 }
5341 }
5342
5343 fn paint_inline_diagnostics(
5344 &mut self,
5345 layout: &mut EditorLayout,
5346 window: &mut Window,
5347 cx: &mut App,
5348 ) {
5349 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
5350 inline_diagnostic.1.paint(window, cx);
5351 }
5352 }
5353
5354 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5355 if let Some(mut inline_blame) = layout.inline_blame.take() {
5356 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5357 inline_blame.paint(window, cx);
5358 })
5359 }
5360 }
5361
5362 fn paint_diff_hunk_controls(
5363 &mut self,
5364 layout: &mut EditorLayout,
5365 window: &mut Window,
5366 cx: &mut App,
5367 ) {
5368 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5369 diff_hunk_control.paint(window, cx);
5370 }
5371 }
5372
5373 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5374 for mut block in layout.blocks.drain(..) {
5375 if block.overlaps_gutter {
5376 block.element.paint(window, cx);
5377 } else {
5378 let mut bounds = layout.hitbox.bounds;
5379 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
5380 window.with_content_mask(Some(ContentMask { bounds }), |window| {
5381 block.element.paint(window, cx);
5382 })
5383 }
5384 }
5385 }
5386
5387 fn paint_inline_completion_popover(
5388 &mut self,
5389 layout: &mut EditorLayout,
5390 window: &mut Window,
5391 cx: &mut App,
5392 ) {
5393 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5394 inline_completion_popover.paint(window, cx);
5395 }
5396 }
5397
5398 fn paint_mouse_context_menu(
5399 &mut self,
5400 layout: &mut EditorLayout,
5401 window: &mut Window,
5402 cx: &mut App,
5403 ) {
5404 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5405 mouse_context_menu.paint(window, cx);
5406 }
5407 }
5408
5409 fn paint_scroll_wheel_listener(
5410 &mut self,
5411 layout: &EditorLayout,
5412 window: &mut Window,
5413 cx: &mut App,
5414 ) {
5415 window.on_mouse_event({
5416 let position_map = layout.position_map.clone();
5417 let editor = self.editor.clone();
5418 let hitbox = layout.hitbox.clone();
5419 let mut delta = ScrollDelta::default();
5420
5421 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5422 // accidentally turn off their scrolling.
5423 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5424
5425 move |event: &ScrollWheelEvent, phase, window, cx| {
5426 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5427 delta = delta.coalesce(event.delta);
5428 editor.update(cx, |editor, cx| {
5429 let position_map: &PositionMap = &position_map;
5430
5431 let line_height = position_map.line_height;
5432 let max_glyph_width = position_map.em_width;
5433 let (delta, axis) = match delta {
5434 gpui::ScrollDelta::Pixels(mut pixels) => {
5435 //Trackpad
5436 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5437 (pixels, axis)
5438 }
5439
5440 gpui::ScrollDelta::Lines(lines) => {
5441 //Not trackpad
5442 let pixels =
5443 point(lines.x * max_glyph_width, lines.y * line_height);
5444 (pixels, None)
5445 }
5446 };
5447
5448 let current_scroll_position = position_map.snapshot.scroll_position();
5449 let x = (current_scroll_position.x * max_glyph_width
5450 - (delta.x * scroll_sensitivity))
5451 / max_glyph_width;
5452 let y = (current_scroll_position.y * line_height
5453 - (delta.y * scroll_sensitivity))
5454 / line_height;
5455 let mut scroll_position =
5456 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5457 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5458 if forbid_vertical_scroll {
5459 scroll_position.y = current_scroll_position.y;
5460 }
5461
5462 if scroll_position != current_scroll_position {
5463 editor.scroll(scroll_position, axis, window, cx);
5464 cx.stop_propagation();
5465 } else if y < 0. {
5466 // Due to clamping, we may fail to detect cases of overscroll to the top;
5467 // We want the scroll manager to get an update in such cases and detect the change of direction
5468 // on the next frame.
5469 cx.notify();
5470 }
5471 });
5472 }
5473 }
5474 });
5475 }
5476
5477 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5478 self.paint_scroll_wheel_listener(layout, window, cx);
5479
5480 window.on_mouse_event({
5481 let position_map = layout.position_map.clone();
5482 let editor = self.editor.clone();
5483 let diff_hunk_range =
5484 layout
5485 .display_hunks
5486 .iter()
5487 .find_map(|(hunk, hunk_hitbox)| match hunk {
5488 DisplayDiffHunk::Folded { .. } => None,
5489 DisplayDiffHunk::Unfolded {
5490 multi_buffer_range, ..
5491 } => {
5492 if hunk_hitbox
5493 .as_ref()
5494 .map(|hitbox| hitbox.is_hovered(window))
5495 .unwrap_or(false)
5496 {
5497 Some(multi_buffer_range.clone())
5498 } else {
5499 None
5500 }
5501 }
5502 });
5503 let line_numbers = layout.line_numbers.clone();
5504
5505 move |event: &MouseDownEvent, phase, window, cx| {
5506 if phase == DispatchPhase::Bubble {
5507 match event.button {
5508 MouseButton::Left => editor.update(cx, |editor, cx| {
5509 let pending_mouse_down = editor
5510 .pending_mouse_down
5511 .get_or_insert_with(Default::default)
5512 .clone();
5513
5514 *pending_mouse_down.borrow_mut() = Some(event.clone());
5515
5516 Self::mouse_left_down(
5517 editor,
5518 event,
5519 diff_hunk_range.clone(),
5520 &position_map,
5521 line_numbers.as_ref(),
5522 window,
5523 cx,
5524 );
5525 }),
5526 MouseButton::Right => editor.update(cx, |editor, cx| {
5527 Self::mouse_right_down(editor, event, &position_map, window, cx);
5528 }),
5529 MouseButton::Middle => editor.update(cx, |editor, cx| {
5530 Self::mouse_middle_down(editor, event, &position_map, window, cx);
5531 }),
5532 _ => {}
5533 };
5534 }
5535 }
5536 });
5537
5538 window.on_mouse_event({
5539 let editor = self.editor.clone();
5540 let position_map = layout.position_map.clone();
5541
5542 move |event: &MouseUpEvent, phase, window, cx| {
5543 if phase == DispatchPhase::Bubble {
5544 editor.update(cx, |editor, cx| {
5545 Self::mouse_up(editor, event, &position_map, window, cx)
5546 });
5547 }
5548 }
5549 });
5550
5551 window.on_mouse_event({
5552 let editor = self.editor.clone();
5553 let position_map = layout.position_map.clone();
5554 let mut captured_mouse_down = None;
5555
5556 move |event: &MouseUpEvent, phase, window, cx| match phase {
5557 // Clear the pending mouse down during the capture phase,
5558 // so that it happens even if another event handler stops
5559 // propagation.
5560 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5561 let pending_mouse_down = editor
5562 .pending_mouse_down
5563 .get_or_insert_with(Default::default)
5564 .clone();
5565
5566 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5567 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5568 captured_mouse_down = pending_mouse_down.take();
5569 window.refresh();
5570 }
5571 }),
5572 // Fire click handlers during the bubble phase.
5573 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5574 if let Some(mouse_down) = captured_mouse_down.take() {
5575 let event = ClickEvent {
5576 down: mouse_down,
5577 up: event.clone(),
5578 };
5579 Self::click(editor, &event, &position_map, window, cx);
5580 }
5581 }),
5582 }
5583 });
5584
5585 window.on_mouse_event({
5586 let position_map = layout.position_map.clone();
5587 let editor = self.editor.clone();
5588
5589 move |event: &MouseMoveEvent, phase, window, cx| {
5590 if phase == DispatchPhase::Bubble {
5591 editor.update(cx, |editor, cx| {
5592 if editor.hover_state.focused(window, cx) {
5593 return;
5594 }
5595 if event.pressed_button == Some(MouseButton::Left)
5596 || event.pressed_button == Some(MouseButton::Middle)
5597 {
5598 Self::mouse_dragged(editor, event, &position_map, window, cx)
5599 }
5600
5601 Self::mouse_moved(editor, event, &position_map, window, cx)
5602 });
5603 }
5604 }
5605 });
5606 }
5607
5608 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5609 bounds.top_right().x - self.style.scrollbar_width
5610 }
5611
5612 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5613 let style = &self.style;
5614 let font_size = style.text.font_size.to_pixels(window.rem_size());
5615 let layout = window
5616 .text_system()
5617 .shape_line(
5618 SharedString::from(" ".repeat(column)),
5619 font_size,
5620 &[TextRun {
5621 len: column,
5622 font: style.text.font(),
5623 color: Hsla::default(),
5624 background_color: None,
5625 underline: None,
5626 strikethrough: None,
5627 }],
5628 )
5629 .unwrap();
5630
5631 layout.width
5632 }
5633
5634 fn max_line_number_width(
5635 &self,
5636 snapshot: &EditorSnapshot,
5637 window: &mut Window,
5638 cx: &mut App,
5639 ) -> Pixels {
5640 let digit_count = snapshot.widest_line_number().ilog10() + 1;
5641 self.column_pixels(digit_count as usize, window, cx)
5642 }
5643
5644 fn shape_line_number(
5645 &self,
5646 text: SharedString,
5647 color: Hsla,
5648 window: &mut Window,
5649 ) -> anyhow::Result<ShapedLine> {
5650 let run = TextRun {
5651 len: text.len(),
5652 font: self.style.text.font(),
5653 color,
5654 background_color: None,
5655 underline: None,
5656 strikethrough: None,
5657 };
5658 window.text_system().shape_line(
5659 text,
5660 self.style.text.font_size.to_pixels(window.rem_size()),
5661 &[run],
5662 )
5663 }
5664
5665 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
5666 let unstaged = status.has_secondary_hunk();
5667 let unstaged_hollow = ProjectSettings::get_global(cx)
5668 .git
5669 .hunk_style
5670 .map_or(false, |style| {
5671 matches!(style, GitHunkStyleSetting::UnstagedHollow)
5672 });
5673
5674 unstaged == unstaged_hollow
5675 }
5676}
5677
5678fn header_jump_data(
5679 snapshot: &EditorSnapshot,
5680 block_row_start: DisplayRow,
5681 height: u32,
5682 for_excerpt: &ExcerptInfo,
5683) -> JumpData {
5684 let range = &for_excerpt.range;
5685 let buffer = &for_excerpt.buffer;
5686 let jump_anchor = range.primary.start;
5687
5688 let excerpt_start = range.context.start;
5689 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5690 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5691 0
5692 } else {
5693 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5694 jump_position.row.saturating_sub(excerpt_start_point.row)
5695 };
5696
5697 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5698 .saturating_sub(
5699 snapshot
5700 .scroll_anchor
5701 .scroll_position(&snapshot.display_snapshot)
5702 .y as u32,
5703 );
5704
5705 JumpData::MultiBufferPoint {
5706 excerpt_id: for_excerpt.id,
5707 anchor: jump_anchor,
5708 position: jump_position,
5709 line_offset_from_top,
5710 }
5711}
5712
5713pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5714
5715impl AcceptEditPredictionBinding {
5716 pub fn keystroke(&self) -> Option<&Keystroke> {
5717 if let Some(binding) = self.0.as_ref() {
5718 match &binding.keystrokes() {
5719 [keystroke] => Some(keystroke),
5720 _ => None,
5721 }
5722 } else {
5723 None
5724 }
5725 }
5726}
5727
5728fn prepaint_gutter_button(
5729 button: IconButton,
5730 row: DisplayRow,
5731 line_height: Pixels,
5732 gutter_dimensions: &GutterDimensions,
5733 scroll_pixel_position: gpui::Point<Pixels>,
5734 gutter_hitbox: &Hitbox,
5735 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5736 window: &mut Window,
5737 cx: &mut App,
5738) -> AnyElement {
5739 let mut button = button.into_any_element();
5740
5741 let available_space = size(
5742 AvailableSpace::MinContent,
5743 AvailableSpace::Definite(line_height),
5744 );
5745 let indicator_size = button.layout_as_root(available_space, window, cx);
5746
5747 let blame_width = gutter_dimensions.git_blame_entries_width;
5748 let gutter_width = display_hunks
5749 .binary_search_by(|(hunk, _)| match hunk {
5750 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
5751 DisplayDiffHunk::Unfolded {
5752 display_row_range, ..
5753 } => {
5754 if display_row_range.end <= row {
5755 Ordering::Less
5756 } else if display_row_range.start > row {
5757 Ordering::Greater
5758 } else {
5759 Ordering::Equal
5760 }
5761 }
5762 })
5763 .ok()
5764 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
5765 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5766
5767 let mut x = left_offset;
5768 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5769 - indicator_size.width
5770 - left_offset;
5771 x += available_width / 2.;
5772
5773 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5774 y += (line_height - indicator_size.height) / 2.;
5775
5776 button.prepaint_as_root(
5777 gutter_hitbox.origin + point(x, y),
5778 available_space,
5779 window,
5780 cx,
5781 );
5782 button
5783}
5784
5785fn render_inline_blame_entry(
5786 editor: Entity<Editor>,
5787 workspace: WeakEntity<Workspace>,
5788 blame: &Entity<GitBlame>,
5789 blame_entry: BlameEntry,
5790 style: &EditorStyle,
5791 cx: &mut App,
5792) -> Option<AnyElement> {
5793 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
5794 let blame = blame.read(cx);
5795 let details = blame.details_for_entry(&blame_entry);
5796 let repository = blame.repository(cx)?.clone();
5797 renderer.render_inline_blame_entry(
5798 &style.text,
5799 blame_entry,
5800 details,
5801 repository,
5802 workspace,
5803 editor,
5804 cx,
5805 )
5806}
5807
5808fn render_blame_entry(
5809 ix: usize,
5810 blame: &Entity<GitBlame>,
5811 blame_entry: BlameEntry,
5812 style: &EditorStyle,
5813 last_used_color: &mut Option<(PlayerColor, Oid)>,
5814 editor: Entity<Editor>,
5815 workspace: Entity<Workspace>,
5816 renderer: Arc<dyn BlameRenderer>,
5817 cx: &mut App,
5818) -> Option<AnyElement> {
5819 let mut sha_color = cx
5820 .theme()
5821 .players()
5822 .color_for_participant(blame_entry.sha.into());
5823
5824 // If the last color we used is the same as the one we get for this line, but
5825 // the commit SHAs are different, then we try again to get a different color.
5826 match *last_used_color {
5827 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5828 let index: u32 = blame_entry.sha.into();
5829 sha_color = cx.theme().players().color_for_participant(index + 1);
5830 }
5831 _ => {}
5832 };
5833 last_used_color.replace((sha_color, blame_entry.sha));
5834
5835 let blame = blame.read(cx);
5836 let details = blame.details_for_entry(&blame_entry);
5837 let repository = blame.repository(cx)?;
5838 renderer.render_blame_entry(
5839 &style.text,
5840 blame_entry,
5841 details,
5842 repository,
5843 workspace.downgrade(),
5844 editor,
5845 ix,
5846 sha_color.cursor,
5847 cx,
5848 )
5849}
5850
5851#[derive(Debug)]
5852pub(crate) struct LineWithInvisibles {
5853 fragments: SmallVec<[LineFragment; 1]>,
5854 invisibles: Vec<Invisible>,
5855 len: usize,
5856 pub(crate) width: Pixels,
5857 font_size: Pixels,
5858}
5859
5860#[allow(clippy::large_enum_variant)]
5861enum LineFragment {
5862 Text(ShapedLine),
5863 Element {
5864 id: FoldId,
5865 element: Option<AnyElement>,
5866 size: Size<Pixels>,
5867 len: usize,
5868 },
5869}
5870
5871impl fmt::Debug for LineFragment {
5872 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5873 match self {
5874 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
5875 LineFragment::Element { size, len, .. } => f
5876 .debug_struct("Element")
5877 .field("size", size)
5878 .field("len", len)
5879 .finish(),
5880 }
5881 }
5882}
5883
5884impl LineWithInvisibles {
5885 fn from_chunks<'a>(
5886 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
5887 editor_style: &EditorStyle,
5888 max_line_len: usize,
5889 max_line_count: usize,
5890 editor_mode: EditorMode,
5891 text_width: Pixels,
5892 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
5893 window: &mut Window,
5894 cx: &mut App,
5895 ) -> Vec<Self> {
5896 let text_style = &editor_style.text;
5897 let mut layouts = Vec::with_capacity(max_line_count);
5898 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
5899 let mut line = String::new();
5900 let mut invisibles = Vec::new();
5901 let mut width = Pixels::ZERO;
5902 let mut len = 0;
5903 let mut styles = Vec::new();
5904 let mut non_whitespace_added = false;
5905 let mut row = 0;
5906 let mut line_exceeded_max_len = false;
5907 let font_size = text_style.font_size.to_pixels(window.rem_size());
5908
5909 let ellipsis = SharedString::from("⋯");
5910
5911 for highlighted_chunk in chunks.chain([HighlightedChunk {
5912 text: "\n",
5913 style: None,
5914 is_tab: false,
5915 replacement: None,
5916 }]) {
5917 if let Some(replacement) = highlighted_chunk.replacement {
5918 if !line.is_empty() {
5919 let shaped_line = window
5920 .text_system()
5921 .shape_line(line.clone().into(), font_size, &styles)
5922 .unwrap();
5923 width += shaped_line.width;
5924 len += shaped_line.len;
5925 fragments.push(LineFragment::Text(shaped_line));
5926 line.clear();
5927 styles.clear();
5928 }
5929
5930 match replacement {
5931 ChunkReplacement::Renderer(renderer) => {
5932 let available_width = if renderer.constrain_width {
5933 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
5934 ellipsis.clone()
5935 } else {
5936 SharedString::from(Arc::from(highlighted_chunk.text))
5937 };
5938 let shaped_line = window
5939 .text_system()
5940 .shape_line(
5941 chunk,
5942 font_size,
5943 &[text_style.to_run(highlighted_chunk.text.len())],
5944 )
5945 .unwrap();
5946 AvailableSpace::Definite(shaped_line.width)
5947 } else {
5948 AvailableSpace::MinContent
5949 };
5950
5951 let mut element = (renderer.render)(&mut ChunkRendererContext {
5952 context: cx,
5953 window,
5954 max_width: text_width,
5955 });
5956 let line_height = text_style.line_height_in_pixels(window.rem_size());
5957 let size = element.layout_as_root(
5958 size(available_width, AvailableSpace::Definite(line_height)),
5959 window,
5960 cx,
5961 );
5962
5963 width += size.width;
5964 len += highlighted_chunk.text.len();
5965 fragments.push(LineFragment::Element {
5966 id: renderer.id,
5967 element: Some(element),
5968 size,
5969 len: highlighted_chunk.text.len(),
5970 });
5971 }
5972 ChunkReplacement::Str(x) => {
5973 let text_style = if let Some(style) = highlighted_chunk.style {
5974 Cow::Owned(text_style.clone().highlight(style))
5975 } else {
5976 Cow::Borrowed(text_style)
5977 };
5978
5979 let run = TextRun {
5980 len: x.len(),
5981 font: text_style.font(),
5982 color: text_style.color,
5983 background_color: text_style.background_color,
5984 underline: text_style.underline,
5985 strikethrough: text_style.strikethrough,
5986 };
5987 let line_layout = window
5988 .text_system()
5989 .shape_line(x, font_size, &[run])
5990 .unwrap()
5991 .with_len(highlighted_chunk.text.len());
5992
5993 width += line_layout.width;
5994 len += highlighted_chunk.text.len();
5995 fragments.push(LineFragment::Text(line_layout))
5996 }
5997 }
5998 } else {
5999 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6000 if ix > 0 {
6001 let shaped_line = window
6002 .text_system()
6003 .shape_line(line.clone().into(), font_size, &styles)
6004 .unwrap();
6005 width += shaped_line.width;
6006 len += shaped_line.len;
6007 fragments.push(LineFragment::Text(shaped_line));
6008 layouts.push(Self {
6009 width: mem::take(&mut width),
6010 len: mem::take(&mut len),
6011 fragments: mem::take(&mut fragments),
6012 invisibles: std::mem::take(&mut invisibles),
6013 font_size,
6014 });
6015
6016 line.clear();
6017 styles.clear();
6018 row += 1;
6019 line_exceeded_max_len = false;
6020 non_whitespace_added = false;
6021 if row == max_line_count {
6022 return layouts;
6023 }
6024 }
6025
6026 if !line_chunk.is_empty() && !line_exceeded_max_len {
6027 let text_style = if let Some(style) = highlighted_chunk.style {
6028 Cow::Owned(text_style.clone().highlight(style))
6029 } else {
6030 Cow::Borrowed(text_style)
6031 };
6032
6033 if line.len() + line_chunk.len() > max_line_len {
6034 let mut chunk_len = max_line_len - line.len();
6035 while !line_chunk.is_char_boundary(chunk_len) {
6036 chunk_len -= 1;
6037 }
6038 line_chunk = &line_chunk[..chunk_len];
6039 line_exceeded_max_len = true;
6040 }
6041
6042 styles.push(TextRun {
6043 len: line_chunk.len(),
6044 font: text_style.font(),
6045 color: text_style.color,
6046 background_color: text_style.background_color,
6047 underline: text_style.underline,
6048 strikethrough: text_style.strikethrough,
6049 });
6050
6051 if editor_mode == EditorMode::Full {
6052 // Line wrap pads its contents with fake whitespaces,
6053 // avoid printing them
6054 let is_soft_wrapped = is_row_soft_wrapped(row);
6055 if highlighted_chunk.is_tab {
6056 if non_whitespace_added || !is_soft_wrapped {
6057 invisibles.push(Invisible::Tab {
6058 line_start_offset: line.len(),
6059 line_end_offset: line.len() + line_chunk.len(),
6060 });
6061 }
6062 } else {
6063 invisibles.extend(line_chunk.char_indices().filter_map(
6064 |(index, c)| {
6065 let is_whitespace = c.is_whitespace();
6066 non_whitespace_added |= !is_whitespace;
6067 if is_whitespace
6068 && (non_whitespace_added || !is_soft_wrapped)
6069 {
6070 Some(Invisible::Whitespace {
6071 line_offset: line.len() + index,
6072 })
6073 } else {
6074 None
6075 }
6076 },
6077 ))
6078 }
6079 }
6080
6081 line.push_str(line_chunk);
6082 }
6083 }
6084 }
6085 }
6086
6087 layouts
6088 }
6089
6090 fn prepaint(
6091 &mut self,
6092 line_height: Pixels,
6093 scroll_pixel_position: gpui::Point<Pixels>,
6094 row: DisplayRow,
6095 content_origin: gpui::Point<Pixels>,
6096 line_elements: &mut SmallVec<[AnyElement; 1]>,
6097 window: &mut Window,
6098 cx: &mut App,
6099 ) {
6100 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6101 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6102 for fragment in &mut self.fragments {
6103 match fragment {
6104 LineFragment::Text(line) => {
6105 fragment_origin.x += line.width;
6106 }
6107 LineFragment::Element { element, size, .. } => {
6108 let mut element = element
6109 .take()
6110 .expect("you can't prepaint LineWithInvisibles twice");
6111
6112 // Center the element vertically within the line.
6113 let mut element_origin = fragment_origin;
6114 element_origin.y += (line_height - size.height) / 2.;
6115 element.prepaint_at(element_origin, window, cx);
6116 line_elements.push(element);
6117
6118 fragment_origin.x += size.width;
6119 }
6120 }
6121 }
6122 }
6123
6124 fn draw(
6125 &self,
6126 layout: &EditorLayout,
6127 row: DisplayRow,
6128 content_origin: gpui::Point<Pixels>,
6129 whitespace_setting: ShowWhitespaceSetting,
6130 selection_ranges: &[Range<DisplayPoint>],
6131 window: &mut Window,
6132 cx: &mut App,
6133 ) {
6134 let line_height = layout.position_map.line_height;
6135 let line_y = line_height
6136 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6137
6138 let mut fragment_origin =
6139 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6140
6141 for fragment in &self.fragments {
6142 match fragment {
6143 LineFragment::Text(line) => {
6144 line.paint(fragment_origin, line_height, window, cx)
6145 .log_err();
6146 fragment_origin.x += line.width;
6147 }
6148 LineFragment::Element { size, .. } => {
6149 fragment_origin.x += size.width;
6150 }
6151 }
6152 }
6153
6154 self.draw_invisibles(
6155 selection_ranges,
6156 layout,
6157 content_origin,
6158 line_y,
6159 row,
6160 line_height,
6161 whitespace_setting,
6162 window,
6163 cx,
6164 );
6165 }
6166
6167 fn draw_background(
6168 &self,
6169 layout: &EditorLayout,
6170 row: DisplayRow,
6171 content_origin: gpui::Point<Pixels>,
6172 window: &mut Window,
6173 cx: &mut App,
6174 ) {
6175 let line_height = layout.position_map.line_height;
6176 let line_y = line_height
6177 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6178
6179 let mut fragment_origin =
6180 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6181
6182 for fragment in &self.fragments {
6183 match fragment {
6184 LineFragment::Text(line) => {
6185 line.paint_background(fragment_origin, line_height, window, cx)
6186 .log_err();
6187 fragment_origin.x += line.width;
6188 }
6189 LineFragment::Element { size, .. } => {
6190 fragment_origin.x += size.width;
6191 }
6192 }
6193 }
6194 }
6195
6196 fn draw_invisibles(
6197 &self,
6198 selection_ranges: &[Range<DisplayPoint>],
6199 layout: &EditorLayout,
6200 content_origin: gpui::Point<Pixels>,
6201 line_y: Pixels,
6202 row: DisplayRow,
6203 line_height: Pixels,
6204 whitespace_setting: ShowWhitespaceSetting,
6205 window: &mut Window,
6206 cx: &mut App,
6207 ) {
6208 let extract_whitespace_info = |invisible: &Invisible| {
6209 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6210 Invisible::Tab {
6211 line_start_offset,
6212 line_end_offset,
6213 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6214 Invisible::Whitespace { line_offset } => {
6215 (*line_offset, line_offset + 1, &layout.space_invisible)
6216 }
6217 };
6218
6219 let x_offset = self.x_for_index(token_offset);
6220 let invisible_offset =
6221 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6222 let origin = content_origin
6223 + gpui::point(
6224 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6225 line_y,
6226 );
6227
6228 (
6229 [token_offset, token_end_offset],
6230 Box::new(move |window: &mut Window, cx: &mut App| {
6231 invisible_symbol
6232 .paint(origin, line_height, window, cx)
6233 .log_err();
6234 }),
6235 )
6236 };
6237
6238 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6239 match whitespace_setting {
6240 ShowWhitespaceSetting::None => (),
6241 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6242 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6243 let invisible_point = DisplayPoint::new(row, start as u32);
6244 if !selection_ranges
6245 .iter()
6246 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6247 {
6248 return;
6249 }
6250
6251 paint(window, cx);
6252 }),
6253
6254 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6255 // - It is a tab
6256 // - It is adjacent to an edge (start or end)
6257 // - It is adjacent to a whitespace (left or right)
6258 ShowWhitespaceSetting::Boundary => {
6259 // 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
6260 // the above cases.
6261 // Note: We zip in the original `invisibles` to check for tab equality
6262 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6263 for (([start, end], paint), invisible) in
6264 invisible_iter.zip_eq(self.invisibles.iter())
6265 {
6266 let should_render = match (&last_seen, invisible) {
6267 (_, Invisible::Tab { .. }) => true,
6268 (Some((_, last_end, _)), _) => *last_end == start,
6269 _ => false,
6270 };
6271
6272 if should_render || start == 0 || end == self.len {
6273 paint(window, cx);
6274
6275 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6276 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6277 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6278 // Note that we need to make sure that the last one is actually adjacent
6279 if !should_render_last && last_end == start {
6280 paint_last(window, cx);
6281 }
6282 }
6283 }
6284
6285 // Manually render anything within a selection
6286 let invisible_point = DisplayPoint::new(row, start as u32);
6287 if selection_ranges.iter().any(|region| {
6288 region.start <= invisible_point && invisible_point < region.end
6289 }) {
6290 paint(window, cx);
6291 }
6292
6293 last_seen = Some((should_render, end, paint));
6294 }
6295 }
6296 }
6297 }
6298
6299 pub fn x_for_index(&self, index: usize) -> Pixels {
6300 let mut fragment_start_x = Pixels::ZERO;
6301 let mut fragment_start_index = 0;
6302
6303 for fragment in &self.fragments {
6304 match fragment {
6305 LineFragment::Text(shaped_line) => {
6306 let fragment_end_index = fragment_start_index + shaped_line.len;
6307 if index < fragment_end_index {
6308 return fragment_start_x
6309 + shaped_line.x_for_index(index - fragment_start_index);
6310 }
6311 fragment_start_x += shaped_line.width;
6312 fragment_start_index = fragment_end_index;
6313 }
6314 LineFragment::Element { len, size, .. } => {
6315 let fragment_end_index = fragment_start_index + len;
6316 if index < fragment_end_index {
6317 return fragment_start_x;
6318 }
6319 fragment_start_x += size.width;
6320 fragment_start_index = fragment_end_index;
6321 }
6322 }
6323 }
6324
6325 fragment_start_x
6326 }
6327
6328 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6329 let mut fragment_start_x = Pixels::ZERO;
6330 let mut fragment_start_index = 0;
6331
6332 for fragment in &self.fragments {
6333 match fragment {
6334 LineFragment::Text(shaped_line) => {
6335 let fragment_end_x = fragment_start_x + shaped_line.width;
6336 if x < fragment_end_x {
6337 return Some(
6338 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6339 );
6340 }
6341 fragment_start_x = fragment_end_x;
6342 fragment_start_index += shaped_line.len;
6343 }
6344 LineFragment::Element { len, size, .. } => {
6345 let fragment_end_x = fragment_start_x + size.width;
6346 if x < fragment_end_x {
6347 return Some(fragment_start_index);
6348 }
6349 fragment_start_index += len;
6350 fragment_start_x = fragment_end_x;
6351 }
6352 }
6353 }
6354
6355 None
6356 }
6357
6358 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6359 let mut fragment_start_index = 0;
6360
6361 for fragment in &self.fragments {
6362 match fragment {
6363 LineFragment::Text(shaped_line) => {
6364 let fragment_end_index = fragment_start_index + shaped_line.len;
6365 if index < fragment_end_index {
6366 return shaped_line.font_id_for_index(index - fragment_start_index);
6367 }
6368 fragment_start_index = fragment_end_index;
6369 }
6370 LineFragment::Element { len, .. } => {
6371 let fragment_end_index = fragment_start_index + len;
6372 if index < fragment_end_index {
6373 return None;
6374 }
6375 fragment_start_index = fragment_end_index;
6376 }
6377 }
6378 }
6379
6380 None
6381 }
6382}
6383
6384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6385enum Invisible {
6386 /// A tab character
6387 ///
6388 /// A tab character is internally represented by spaces (configured by the user's tab width)
6389 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6390 /// adjacency checks.
6391 Tab {
6392 line_start_offset: usize,
6393 line_end_offset: usize,
6394 },
6395 Whitespace {
6396 line_offset: usize,
6397 },
6398}
6399
6400impl EditorElement {
6401 /// Returns the rem size to use when rendering the [`EditorElement`].
6402 ///
6403 /// This allows UI elements to scale based on the `buffer_font_size`.
6404 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6405 match self.editor.read(cx).mode {
6406 EditorMode::Full => {
6407 let buffer_font_size = self.style.text.font_size;
6408 match buffer_font_size {
6409 AbsoluteLength::Pixels(pixels) => {
6410 let rem_size_scale = {
6411 // Our default UI font size is 14px on a 16px base scale.
6412 // This means the default UI font size is 0.875rems.
6413 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6414
6415 // We then determine the delta between a single rem and the default font
6416 // size scale.
6417 let default_font_size_delta = 1. - default_font_size_scale;
6418
6419 // Finally, we add this delta to 1rem to get the scale factor that
6420 // should be used to scale up the UI.
6421 1. + default_font_size_delta
6422 };
6423
6424 Some(pixels * rem_size_scale)
6425 }
6426 AbsoluteLength::Rems(rems) => {
6427 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6428 }
6429 }
6430 }
6431 // We currently use single-line and auto-height editors in UI contexts,
6432 // so we don't want to scale everything with the buffer font size, as it
6433 // ends up looking off.
6434 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6435 }
6436 }
6437}
6438
6439impl Element for EditorElement {
6440 type RequestLayoutState = ();
6441 type PrepaintState = EditorLayout;
6442
6443 fn id(&self) -> Option<ElementId> {
6444 None
6445 }
6446
6447 fn request_layout(
6448 &mut self,
6449 _: Option<&GlobalElementId>,
6450 window: &mut Window,
6451 cx: &mut App,
6452 ) -> (gpui::LayoutId, ()) {
6453 let rem_size = self.rem_size(cx);
6454 window.with_rem_size(rem_size, |window| {
6455 self.editor.update(cx, |editor, cx| {
6456 editor.set_style(self.style.clone(), window, cx);
6457
6458 let layout_id = match editor.mode {
6459 EditorMode::SingleLine { auto_width } => {
6460 let rem_size = window.rem_size();
6461
6462 let height = self.style.text.line_height_in_pixels(rem_size);
6463 if auto_width {
6464 let editor_handle = cx.entity().clone();
6465 let style = self.style.clone();
6466 window.request_measured_layout(
6467 Style::default(),
6468 move |_, _, window, cx| {
6469 let editor_snapshot = editor_handle
6470 .update(cx, |editor, cx| editor.snapshot(window, cx));
6471 let line = Self::layout_lines(
6472 DisplayRow(0)..DisplayRow(1),
6473 &editor_snapshot,
6474 &style,
6475 px(f32::MAX),
6476 |_| false, // Single lines never soft wrap
6477 window,
6478 cx,
6479 )
6480 .pop()
6481 .unwrap();
6482
6483 let font_id =
6484 window.text_system().resolve_font(&style.text.font());
6485 let font_size =
6486 style.text.font_size.to_pixels(window.rem_size());
6487 let em_width =
6488 window.text_system().em_width(font_id, font_size).unwrap();
6489
6490 size(line.width + em_width, height)
6491 },
6492 )
6493 } else {
6494 let mut style = Style::default();
6495 style.size.height = height.into();
6496 style.size.width = relative(1.).into();
6497 window.request_layout(style, None, cx)
6498 }
6499 }
6500 EditorMode::AutoHeight { max_lines } => {
6501 let editor_handle = cx.entity().clone();
6502 let max_line_number_width =
6503 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6504 window.request_measured_layout(
6505 Style::default(),
6506 move |known_dimensions, available_space, window, cx| {
6507 editor_handle
6508 .update(cx, |editor, cx| {
6509 compute_auto_height_layout(
6510 editor,
6511 max_lines,
6512 max_line_number_width,
6513 known_dimensions,
6514 available_space.width,
6515 window,
6516 cx,
6517 )
6518 })
6519 .unwrap_or_default()
6520 },
6521 )
6522 }
6523 EditorMode::Full => {
6524 let mut style = Style::default();
6525 style.size.width = relative(1.).into();
6526 style.size.height = relative(1.).into();
6527 window.request_layout(style, None, cx)
6528 }
6529 };
6530
6531 (layout_id, ())
6532 })
6533 })
6534 }
6535
6536 fn prepaint(
6537 &mut self,
6538 _: Option<&GlobalElementId>,
6539 bounds: Bounds<Pixels>,
6540 _: &mut Self::RequestLayoutState,
6541 window: &mut Window,
6542 cx: &mut App,
6543 ) -> Self::PrepaintState {
6544 let text_style = TextStyleRefinement {
6545 font_size: Some(self.style.text.font_size),
6546 line_height: Some(self.style.text.line_height),
6547 ..Default::default()
6548 };
6549 let focus_handle = self.editor.focus_handle(cx);
6550 window.set_view_id(self.editor.entity_id());
6551 window.set_focus_handle(&focus_handle, cx);
6552
6553 let rem_size = self.rem_size(cx);
6554 window.with_rem_size(rem_size, |window| {
6555 window.with_text_style(Some(text_style), |window| {
6556 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6557 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
6558 (editor.snapshot(window, cx), editor.read_only(cx))
6559 });
6560 let style = self.style.clone();
6561
6562 let font_id = window.text_system().resolve_font(&style.text.font());
6563 let font_size = style.text.font_size.to_pixels(window.rem_size());
6564 let line_height = style.text.line_height_in_pixels(window.rem_size());
6565 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6566 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6567
6568 let glyph_grid_cell = size(em_width, line_height);
6569
6570 let gutter_dimensions = snapshot
6571 .gutter_dimensions(
6572 font_id,
6573 font_size,
6574 self.max_line_number_width(&snapshot, window, cx),
6575 cx,
6576 )
6577 .unwrap_or_default();
6578 let text_width = bounds.size.width - gutter_dimensions.width;
6579
6580 let editor_width =
6581 text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6582
6583 snapshot = self.editor.update(cx, |editor, cx| {
6584 editor.last_bounds = Some(bounds);
6585 editor.gutter_dimensions = gutter_dimensions;
6586 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6587
6588 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6589 snapshot
6590 } else {
6591 let wrap_width = match editor.soft_wrap_mode(cx) {
6592 SoftWrap::GitDiff => None,
6593 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6594 SoftWrap::EditorWidth => Some(editor_width),
6595 SoftWrap::Column(column) => Some(column as f32 * em_advance),
6596 SoftWrap::Bounded(column) => {
6597 Some(editor_width.min(column as f32 * em_advance))
6598 }
6599 };
6600
6601 if editor.set_wrap_width(wrap_width, cx) {
6602 editor.snapshot(window, cx)
6603 } else {
6604 snapshot
6605 }
6606 }
6607 });
6608
6609 let wrap_guides = self
6610 .editor
6611 .read(cx)
6612 .wrap_guides(cx)
6613 .iter()
6614 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6615 .collect::<SmallVec<[_; 2]>>();
6616
6617 let hitbox = window.insert_hitbox(bounds, false);
6618 let gutter_hitbox =
6619 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6620 let text_hitbox = window.insert_hitbox(
6621 Bounds {
6622 origin: gutter_hitbox.top_right(),
6623 size: size(text_width, bounds.size.height),
6624 },
6625 false,
6626 );
6627
6628 // Offset the content_bounds from the text_bounds by the gutter margin (which
6629 // is roughly half a character wide) to make hit testing work more like how we want.
6630 let content_offset = point(gutter_dimensions.margin, Pixels::ZERO);
6631 let content_origin = text_hitbox.origin + content_offset;
6632
6633 let editor_text_bounds =
6634 Bounds::from_corners(content_origin, bounds.bottom_right());
6635
6636 let height_in_lines = editor_text_bounds.size.height / line_height;
6637
6638 let max_row = snapshot.max_point().row().as_f32();
6639
6640 // The max scroll position for the top of the window
6641 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6642 (max_row - height_in_lines + 1.).max(0.)
6643 } else {
6644 let settings = EditorSettings::get_global(cx);
6645 match settings.scroll_beyond_last_line {
6646 ScrollBeyondLastLine::OnePage => max_row,
6647 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6648 ScrollBeyondLastLine::VerticalScrollMargin => {
6649 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6650 .max(0.)
6651 }
6652 }
6653 };
6654
6655 // TODO: Autoscrolling for both axes
6656 let mut autoscroll_request = None;
6657 let mut autoscroll_containing_element = false;
6658 let mut autoscroll_horizontally = false;
6659 self.editor.update(cx, |editor, cx| {
6660 autoscroll_request = editor.autoscroll_request();
6661 autoscroll_containing_element =
6662 autoscroll_request.is_some() || editor.has_pending_selection();
6663 // TODO: Is this horizontal or vertical?!
6664 autoscroll_horizontally = editor.autoscroll_vertically(
6665 bounds,
6666 line_height,
6667 max_scroll_top,
6668 window,
6669 cx,
6670 );
6671 snapshot = editor.snapshot(window, cx);
6672 });
6673
6674 let mut scroll_position = snapshot.scroll_position();
6675 // The scroll position is a fractional point, the whole number of which represents
6676 // the top of the window in terms of display rows.
6677 let start_row = DisplayRow(scroll_position.y as u32);
6678 let max_row = snapshot.max_point().row();
6679 let end_row = cmp::min(
6680 (scroll_position.y + height_in_lines).ceil() as u32,
6681 max_row.next_row().0,
6682 );
6683 let end_row = DisplayRow(end_row);
6684
6685 let row_infos = snapshot
6686 .row_infos(start_row)
6687 .take((start_row..end_row).len())
6688 .collect::<Vec<RowInfo>>();
6689 let is_row_soft_wrapped = |row: usize| {
6690 row_infos
6691 .get(row)
6692 .map_or(true, |info| info.buffer_row.is_none())
6693 };
6694
6695 let start_anchor = if start_row == Default::default() {
6696 Anchor::min()
6697 } else {
6698 snapshot.buffer_snapshot.anchor_before(
6699 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6700 )
6701 };
6702 let end_anchor = if end_row > max_row {
6703 Anchor::max()
6704 } else {
6705 snapshot.buffer_snapshot.anchor_before(
6706 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6707 )
6708 };
6709
6710 let mut highlighted_rows = self
6711 .editor
6712 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6713
6714 let is_light = cx.theme().appearance().is_light();
6715
6716 for (ix, row_info) in row_infos.iter().enumerate() {
6717 let Some(diff_status) = row_info.diff_status else {
6718 continue;
6719 };
6720
6721 let background_color = match diff_status.kind {
6722 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
6723 DiffHunkStatusKind::Deleted => {
6724 cx.theme().colors().version_control_deleted
6725 }
6726 DiffHunkStatusKind::Modified => {
6727 debug_panic!("modified diff status for row info");
6728 continue;
6729 }
6730 };
6731
6732 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
6733
6734 let hollow_highlight = LineHighlight {
6735 background: (background_color.opacity(if is_light {
6736 0.08
6737 } else {
6738 0.06
6739 }))
6740 .into(),
6741 border: Some(if is_light {
6742 background_color.opacity(0.48)
6743 } else {
6744 background_color.opacity(0.36)
6745 }),
6746 };
6747
6748 let filled_highlight =
6749 solid_background(background_color.opacity(hunk_opacity)).into();
6750
6751 let background = if Self::diff_hunk_hollow(diff_status, cx) {
6752 hollow_highlight
6753 } else {
6754 filled_highlight
6755 };
6756
6757 highlighted_rows
6758 .entry(start_row + DisplayRow(ix as u32))
6759 .or_insert(background);
6760 }
6761
6762 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6763 start_anchor..end_anchor,
6764 &snapshot.display_snapshot,
6765 cx.theme().colors(),
6766 );
6767 let highlighted_gutter_ranges =
6768 self.editor.read(cx).gutter_highlights_in_range(
6769 start_anchor..end_anchor,
6770 &snapshot.display_snapshot,
6771 cx,
6772 );
6773
6774 let redacted_ranges = self.editor.read(cx).redacted_ranges(
6775 start_anchor..end_anchor,
6776 &snapshot.display_snapshot,
6777 cx,
6778 );
6779
6780 let (local_selections, selected_buffer_ids): (
6781 Vec<Selection<Point>>,
6782 Vec<BufferId>,
6783 ) = self.editor.update(cx, |editor, cx| {
6784 let all_selections = editor.selections.all::<Point>(cx);
6785 let selected_buffer_ids = if editor.is_singleton(cx) {
6786 Vec::new()
6787 } else {
6788 let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6789
6790 for selection in all_selections {
6791 for buffer_id in snapshot
6792 .buffer_snapshot
6793 .buffer_ids_for_range(selection.range())
6794 {
6795 if selected_buffer_ids.last() != Some(&buffer_id) {
6796 selected_buffer_ids.push(buffer_id);
6797 }
6798 }
6799 }
6800
6801 selected_buffer_ids
6802 };
6803
6804 let mut selections = editor
6805 .selections
6806 .disjoint_in_range(start_anchor..end_anchor, cx);
6807 selections.extend(editor.selections.pending(cx));
6808
6809 (selections, selected_buffer_ids)
6810 });
6811
6812 let (selections, mut active_rows, newest_selection_head) = self
6813 .layout_selections(
6814 start_anchor,
6815 end_anchor,
6816 &local_selections,
6817 &snapshot,
6818 start_row,
6819 end_row,
6820 window,
6821 cx,
6822 );
6823 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
6824 editor.active_breakpoints(start_row..end_row, window, cx)
6825 });
6826 if cx.has_flag::<Debugger>() {
6827 for display_row in breakpoint_rows.keys() {
6828 active_rows.entry(*display_row).or_default().breakpoint = true;
6829 }
6830 }
6831
6832 let line_numbers = self.layout_line_numbers(
6833 Some(&gutter_hitbox),
6834 gutter_dimensions,
6835 line_height,
6836 scroll_position,
6837 start_row..end_row,
6838 &row_infos,
6839 &active_rows,
6840 newest_selection_head,
6841 &snapshot,
6842 window,
6843 cx,
6844 );
6845
6846 // We add the gutter breakpoint indicator to breakpoint_rows after painting
6847 // line numbers so we don't paint a line number debug accent color if a user
6848 // has their mouse over that line when a breakpoint isn't there
6849 if cx.has_flag::<Debugger>() {
6850 let gutter_breakpoint_indicator =
6851 self.editor.read(cx).gutter_breakpoint_indicator.0;
6852 if let Some((gutter_breakpoint_point, _)) =
6853 gutter_breakpoint_indicator.filter(|(_, is_active)| *is_active)
6854 {
6855 breakpoint_rows
6856 .entry(gutter_breakpoint_point.row())
6857 .or_insert_with(|| {
6858 let position = snapshot.display_point_to_anchor(
6859 gutter_breakpoint_point,
6860 Bias::Right,
6861 );
6862 let breakpoint = Breakpoint::new_standard();
6863
6864 (position, breakpoint)
6865 });
6866 }
6867 }
6868
6869 let mut expand_toggles =
6870 window.with_element_namespace("expand_toggles", |window| {
6871 self.layout_expand_toggles(
6872 &gutter_hitbox,
6873 gutter_dimensions,
6874 em_width,
6875 line_height,
6876 scroll_position,
6877 &row_infos,
6878 window,
6879 cx,
6880 )
6881 });
6882
6883 let mut crease_toggles =
6884 window.with_element_namespace("crease_toggles", |window| {
6885 self.layout_crease_toggles(
6886 start_row..end_row,
6887 &row_infos,
6888 &active_rows,
6889 &snapshot,
6890 window,
6891 cx,
6892 )
6893 });
6894 let crease_trailers =
6895 window.with_element_namespace("crease_trailers", |window| {
6896 self.layout_crease_trailers(
6897 row_infos.iter().copied(),
6898 &snapshot,
6899 window,
6900 cx,
6901 )
6902 });
6903
6904 let display_hunks = self.layout_gutter_diff_hunks(
6905 line_height,
6906 &gutter_hitbox,
6907 start_row..end_row,
6908 &snapshot,
6909 window,
6910 cx,
6911 );
6912
6913 let mut line_layouts = Self::layout_lines(
6914 start_row..end_row,
6915 &snapshot,
6916 &self.style,
6917 editor_width,
6918 is_row_soft_wrapped,
6919 window,
6920 cx,
6921 );
6922 let new_fold_widths = line_layouts
6923 .iter()
6924 .flat_map(|layout| &layout.fragments)
6925 .filter_map(|fragment| {
6926 if let LineFragment::Element { id, size, .. } = fragment {
6927 Some((*id, size.width))
6928 } else {
6929 None
6930 }
6931 });
6932 if self.editor.update(cx, |editor, cx| {
6933 editor.update_fold_widths(new_fold_widths, cx)
6934 }) {
6935 // If the fold widths have changed, we need to prepaint
6936 // the element again to account for any changes in
6937 // wrapping.
6938 return self.prepaint(None, bounds, &mut (), window, cx);
6939 }
6940
6941 let longest_line_blame_width = self
6942 .editor
6943 .update(cx, |editor, cx| {
6944 if !editor.show_git_blame_inline {
6945 return None;
6946 }
6947 let blame = editor.blame.as_ref()?;
6948 let blame_entry = blame
6949 .update(cx, |blame, cx| {
6950 let row_infos =
6951 snapshot.row_infos(snapshot.longest_row()).next()?;
6952 blame.blame_for_rows(&[row_infos], cx).next()
6953 })
6954 .flatten()?;
6955 let mut element = render_inline_blame_entry(
6956 self.editor.clone(),
6957 editor.workspace()?.downgrade(),
6958 blame,
6959 blame_entry,
6960 &style,
6961 cx,
6962 )?;
6963 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
6964 Some(
6965 element
6966 .layout_as_root(AvailableSpace::min_size(), window, cx)
6967 .width
6968 + inline_blame_padding,
6969 )
6970 })
6971 .unwrap_or(Pixels::ZERO);
6972
6973 let longest_line_width = layout_line(
6974 snapshot.longest_row(),
6975 &snapshot,
6976 &style,
6977 editor_width,
6978 is_row_soft_wrapped,
6979 window,
6980 cx,
6981 )
6982 .width;
6983
6984 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
6985 text_hitbox.bounds,
6986 glyph_grid_cell,
6987 size(longest_line_width, max_row.as_f32() * line_height),
6988 longest_line_blame_width,
6989 style.scrollbar_width,
6990 editor_width,
6991 EditorSettings::get_global(cx),
6992 );
6993
6994 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
6995
6996 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
6997 snapshot.sticky_header_excerpt(scroll_position.y)
6998 } else {
6999 None
7000 };
7001 let sticky_header_excerpt_id =
7002 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7003
7004 let blocks = window.with_element_namespace("blocks", |window| {
7005 self.render_blocks(
7006 start_row..end_row,
7007 &snapshot,
7008 &hitbox,
7009 &text_hitbox,
7010 editor_width,
7011 &mut scroll_width,
7012 &gutter_dimensions,
7013 em_width,
7014 gutter_dimensions.full_width(),
7015 line_height,
7016 &mut line_layouts,
7017 &local_selections,
7018 &selected_buffer_ids,
7019 is_row_soft_wrapped,
7020 sticky_header_excerpt_id,
7021 window,
7022 cx,
7023 )
7024 });
7025 let (mut blocks, row_block_types) = match blocks {
7026 Ok(blocks) => blocks,
7027 Err(resized_blocks) => {
7028 self.editor.update(cx, |editor, cx| {
7029 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7030 });
7031 return self.prepaint(None, bounds, &mut (), window, cx);
7032 }
7033 };
7034
7035 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7036 window.with_element_namespace("blocks", |window| {
7037 self.layout_sticky_buffer_header(
7038 sticky_header_excerpt,
7039 scroll_position.y,
7040 line_height,
7041 &snapshot,
7042 &hitbox,
7043 &selected_buffer_ids,
7044 &blocks,
7045 window,
7046 cx,
7047 )
7048 })
7049 });
7050
7051 let start_buffer_row =
7052 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7053 let end_buffer_row =
7054 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7055
7056 let scroll_max = point(
7057 ((scroll_width - editor_text_bounds.size.width) / em_width).max(0.0),
7058 max_scroll_top,
7059 );
7060
7061 self.editor.update(cx, |editor, cx| {
7062 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7063
7064 let autoscrolled = if autoscroll_horizontally {
7065 editor.autoscroll_horizontally(
7066 start_row,
7067 editor_width - (glyph_grid_cell.width / 2.0)
7068 + style.scrollbar_width,
7069 scroll_width,
7070 em_width,
7071 &line_layouts,
7072 cx,
7073 )
7074 } else {
7075 false
7076 };
7077
7078 if clamped || autoscrolled {
7079 snapshot = editor.snapshot(window, cx);
7080 scroll_position = snapshot.scroll_position();
7081 }
7082 });
7083
7084 let scroll_pixel_position = point(
7085 scroll_position.x * em_width,
7086 scroll_position.y * line_height,
7087 );
7088
7089 let indent_guides = self.layout_indent_guides(
7090 content_origin,
7091 text_hitbox.origin,
7092 start_buffer_row..end_buffer_row,
7093 scroll_pixel_position,
7094 line_height,
7095 &snapshot,
7096 window,
7097 cx,
7098 );
7099
7100 let crease_trailers =
7101 window.with_element_namespace("crease_trailers", |window| {
7102 self.prepaint_crease_trailers(
7103 crease_trailers,
7104 &line_layouts,
7105 line_height,
7106 content_origin,
7107 scroll_pixel_position,
7108 em_width,
7109 window,
7110 cx,
7111 )
7112 });
7113
7114 let (inline_completion_popover, inline_completion_popover_origin) = self
7115 .editor
7116 .update(cx, |editor, cx| {
7117 editor.render_edit_prediction_popover(
7118 &text_hitbox.bounds,
7119 content_origin,
7120 &snapshot,
7121 start_row..end_row,
7122 scroll_position.y,
7123 scroll_position.y + height_in_lines,
7124 &line_layouts,
7125 line_height,
7126 scroll_pixel_position,
7127 newest_selection_head,
7128 editor_width,
7129 &style,
7130 window,
7131 cx,
7132 )
7133 })
7134 .unzip();
7135
7136 let mut inline_diagnostics = self.layout_inline_diagnostics(
7137 &line_layouts,
7138 &crease_trailers,
7139 &row_block_types,
7140 content_origin,
7141 scroll_pixel_position,
7142 inline_completion_popover_origin,
7143 start_row,
7144 end_row,
7145 line_height,
7146 em_width,
7147 &style,
7148 window,
7149 cx,
7150 );
7151
7152 let mut inline_blame = None;
7153 if let Some(newest_selection_head) = newest_selection_head {
7154 let display_row = newest_selection_head.row();
7155 if (start_row..end_row).contains(&display_row)
7156 && !row_block_types.contains_key(&display_row)
7157 {
7158 let line_ix = display_row.minus(start_row) as usize;
7159 let row_info = &row_infos[line_ix];
7160 let line_layout = &line_layouts[line_ix];
7161 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7162 inline_blame = self.layout_inline_blame(
7163 display_row,
7164 row_info,
7165 line_layout,
7166 crease_trailer_layout,
7167 em_width,
7168 content_origin,
7169 scroll_pixel_position,
7170 line_height,
7171 window,
7172 cx,
7173 );
7174 if inline_blame.is_some() {
7175 // Blame overrides inline diagnostics
7176 inline_diagnostics.remove(&display_row);
7177 }
7178 }
7179 }
7180
7181 let blamed_display_rows = self.layout_blame_entries(
7182 &row_infos,
7183 em_width,
7184 scroll_position,
7185 line_height,
7186 &gutter_hitbox,
7187 gutter_dimensions.git_blame_entries_width,
7188 window,
7189 cx,
7190 );
7191
7192 self.editor.update(cx, |editor, cx| {
7193 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7194
7195 let autoscrolled = if autoscroll_horizontally {
7196 editor.autoscroll_horizontally(
7197 start_row,
7198 editor_width - (glyph_grid_cell.width / 2.0)
7199 + style.scrollbar_width,
7200 scroll_width,
7201 em_width,
7202 &line_layouts,
7203 cx,
7204 )
7205 } else {
7206 false
7207 };
7208
7209 if clamped || autoscrolled {
7210 snapshot = editor.snapshot(window, cx);
7211 scroll_position = snapshot.scroll_position();
7212 }
7213 });
7214
7215 let line_elements = self.prepaint_lines(
7216 start_row,
7217 &mut line_layouts,
7218 line_height,
7219 scroll_pixel_position,
7220 content_origin,
7221 window,
7222 cx,
7223 );
7224
7225 window.with_element_namespace("blocks", |window| {
7226 self.layout_blocks(
7227 &mut blocks,
7228 &hitbox,
7229 line_height,
7230 scroll_pixel_position,
7231 window,
7232 cx,
7233 );
7234 });
7235
7236 let cursors = self.collect_cursors(&snapshot, cx);
7237 let visible_row_range = start_row..end_row;
7238 let non_visible_cursors = cursors
7239 .iter()
7240 .any(|c| !visible_row_range.contains(&c.0.row()));
7241
7242 let visible_cursors = self.layout_visible_cursors(
7243 &snapshot,
7244 &selections,
7245 &row_block_types,
7246 start_row..end_row,
7247 &line_layouts,
7248 &text_hitbox,
7249 content_origin,
7250 scroll_position,
7251 scroll_pixel_position,
7252 line_height,
7253 em_width,
7254 em_advance,
7255 autoscroll_containing_element,
7256 window,
7257 cx,
7258 );
7259
7260 let scrollbars_layout = self.layout_scrollbars(
7261 &snapshot,
7262 scrollbar_layout_information,
7263 content_offset,
7264 scroll_position,
7265 non_visible_cursors,
7266 window,
7267 cx,
7268 );
7269
7270 let gutter_settings = EditorSettings::get_global(cx).gutter;
7271
7272 let mut code_actions_indicator = None;
7273 if let Some(newest_selection_head) = newest_selection_head {
7274 let newest_selection_point =
7275 newest_selection_head.to_point(&snapshot.display_snapshot);
7276
7277 if (start_row..end_row).contains(&newest_selection_head.row()) {
7278 self.layout_cursor_popovers(
7279 line_height,
7280 &text_hitbox,
7281 content_origin,
7282 start_row,
7283 scroll_pixel_position,
7284 &line_layouts,
7285 newest_selection_head,
7286 newest_selection_point,
7287 &style,
7288 window,
7289 cx,
7290 );
7291
7292 let show_code_actions = snapshot
7293 .show_code_actions
7294 .unwrap_or(gutter_settings.code_actions);
7295 if show_code_actions {
7296 let newest_selection_point =
7297 newest_selection_head.to_point(&snapshot.display_snapshot);
7298 if !snapshot
7299 .is_line_folded(MultiBufferRow(newest_selection_point.row))
7300 {
7301 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7302 MultiBufferRow(newest_selection_point.row),
7303 );
7304 if let Some((buffer, range)) = buffer {
7305 let buffer_id = buffer.remote_id();
7306 let row = range.start.row;
7307 let has_test_indicator = self
7308 .editor
7309 .read(cx)
7310 .tasks
7311 .contains_key(&(buffer_id, row));
7312
7313 let has_expand_indicator = row_infos
7314 .get(
7315 (newest_selection_head.row() - start_row).0
7316 as usize,
7317 )
7318 .is_some_and(|row_info| row_info.expand_info.is_some());
7319
7320 if !has_test_indicator && !has_expand_indicator {
7321 code_actions_indicator = self
7322 .layout_code_actions_indicator(
7323 line_height,
7324 newest_selection_head,
7325 scroll_pixel_position,
7326 &gutter_dimensions,
7327 &gutter_hitbox,
7328 &mut breakpoint_rows,
7329 &display_hunks,
7330 window,
7331 cx,
7332 );
7333 }
7334 }
7335 }
7336 }
7337 }
7338 }
7339
7340 self.layout_gutter_menu(
7341 line_height,
7342 &text_hitbox,
7343 content_origin,
7344 scroll_pixel_position,
7345 gutter_dimensions.width - gutter_dimensions.left_padding,
7346 window,
7347 cx,
7348 );
7349
7350 let test_indicators = if gutter_settings.runnables {
7351 self.layout_run_indicators(
7352 line_height,
7353 start_row..end_row,
7354 &row_infos,
7355 scroll_pixel_position,
7356 &gutter_dimensions,
7357 &gutter_hitbox,
7358 &display_hunks,
7359 &snapshot,
7360 &mut breakpoint_rows,
7361 window,
7362 cx,
7363 )
7364 } else {
7365 Vec::new()
7366 };
7367
7368 let show_breakpoints = snapshot
7369 .show_breakpoints
7370 .unwrap_or(gutter_settings.breakpoints);
7371 let breakpoints = if cx.has_flag::<Debugger>() && show_breakpoints {
7372 self.layout_breakpoints(
7373 line_height,
7374 start_row..end_row,
7375 scroll_pixel_position,
7376 &gutter_dimensions,
7377 &gutter_hitbox,
7378 &display_hunks,
7379 &snapshot,
7380 breakpoint_rows,
7381 &row_infos,
7382 window,
7383 cx,
7384 )
7385 } else {
7386 vec![]
7387 };
7388
7389 self.layout_signature_help(
7390 &hitbox,
7391 content_origin,
7392 scroll_pixel_position,
7393 newest_selection_head,
7394 start_row,
7395 &line_layouts,
7396 line_height,
7397 em_width,
7398 window,
7399 cx,
7400 );
7401
7402 if !cx.has_active_drag() {
7403 self.layout_hover_popovers(
7404 &snapshot,
7405 &hitbox,
7406 &text_hitbox,
7407 start_row..end_row,
7408 content_origin,
7409 scroll_pixel_position,
7410 &line_layouts,
7411 line_height,
7412 em_width,
7413 window,
7414 cx,
7415 );
7416 }
7417
7418 let mouse_context_menu = self.layout_mouse_context_menu(
7419 &snapshot,
7420 start_row..end_row,
7421 content_origin,
7422 window,
7423 cx,
7424 );
7425
7426 window.with_element_namespace("crease_toggles", |window| {
7427 self.prepaint_crease_toggles(
7428 &mut crease_toggles,
7429 line_height,
7430 &gutter_dimensions,
7431 gutter_settings,
7432 scroll_pixel_position,
7433 &gutter_hitbox,
7434 window,
7435 cx,
7436 )
7437 });
7438
7439 window.with_element_namespace("expand_toggles", |window| {
7440 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
7441 });
7442
7443 let invisible_symbol_font_size = font_size / 2.;
7444 let tab_invisible = window
7445 .text_system()
7446 .shape_line(
7447 "→".into(),
7448 invisible_symbol_font_size,
7449 &[TextRun {
7450 len: "→".len(),
7451 font: self.style.text.font(),
7452 color: cx.theme().colors().editor_invisible,
7453 background_color: None,
7454 underline: None,
7455 strikethrough: None,
7456 }],
7457 )
7458 .unwrap();
7459 let space_invisible = window
7460 .text_system()
7461 .shape_line(
7462 "•".into(),
7463 invisible_symbol_font_size,
7464 &[TextRun {
7465 len: "•".len(),
7466 font: self.style.text.font(),
7467 color: cx.theme().colors().editor_invisible,
7468 background_color: None,
7469 underline: None,
7470 strikethrough: None,
7471 }],
7472 )
7473 .unwrap();
7474
7475 let mode = snapshot.mode;
7476
7477 let position_map = Rc::new(PositionMap {
7478 size: bounds.size,
7479 visible_row_range,
7480 scroll_pixel_position,
7481 scroll_max,
7482 line_layouts,
7483 line_height,
7484 em_width,
7485 em_advance,
7486 snapshot,
7487 gutter_hitbox: gutter_hitbox.clone(),
7488 text_hitbox: text_hitbox.clone(),
7489 });
7490
7491 self.editor.update(cx, |editor, _| {
7492 editor.last_position_map = Some(position_map.clone())
7493 });
7494
7495 let diff_hunk_controls = if is_read_only {
7496 vec![]
7497 } else {
7498 self.layout_diff_hunk_controls(
7499 start_row..end_row,
7500 &row_infos,
7501 &text_hitbox,
7502 &position_map,
7503 newest_selection_head,
7504 line_height,
7505 scroll_pixel_position,
7506 &display_hunks,
7507 self.editor.clone(),
7508 window,
7509 cx,
7510 )
7511 };
7512
7513 EditorLayout {
7514 mode,
7515 position_map,
7516 visible_display_row_range: start_row..end_row,
7517 wrap_guides,
7518 indent_guides,
7519 hitbox,
7520 gutter_hitbox,
7521 display_hunks,
7522 content_origin,
7523 scrollbars_layout,
7524 active_rows,
7525 highlighted_rows,
7526 highlighted_ranges,
7527 highlighted_gutter_ranges,
7528 redacted_ranges,
7529 line_elements,
7530 line_numbers,
7531 blamed_display_rows,
7532 inline_diagnostics,
7533 inline_blame,
7534 blocks,
7535 cursors,
7536 visible_cursors,
7537 selections,
7538 inline_completion_popover,
7539 diff_hunk_controls,
7540 mouse_context_menu,
7541 test_indicators,
7542 breakpoints,
7543 code_actions_indicator,
7544 crease_toggles,
7545 crease_trailers,
7546 tab_invisible,
7547 space_invisible,
7548 sticky_buffer_header,
7549 expand_toggles,
7550 }
7551 })
7552 })
7553 })
7554 }
7555
7556 fn paint(
7557 &mut self,
7558 _: Option<&GlobalElementId>,
7559 bounds: Bounds<gpui::Pixels>,
7560 _: &mut Self::RequestLayoutState,
7561 layout: &mut Self::PrepaintState,
7562 window: &mut Window,
7563 cx: &mut App,
7564 ) {
7565 let focus_handle = self.editor.focus_handle(cx);
7566 let key_context = self
7567 .editor
7568 .update(cx, |editor, cx| editor.key_context(window, cx));
7569
7570 window.set_key_context(key_context);
7571 window.handle_input(
7572 &focus_handle,
7573 ElementInputHandler::new(bounds, self.editor.clone()),
7574 cx,
7575 );
7576 self.register_actions(window, cx);
7577 self.register_key_listeners(window, cx, layout);
7578
7579 let text_style = TextStyleRefinement {
7580 font_size: Some(self.style.text.font_size),
7581 line_height: Some(self.style.text.line_height),
7582 ..Default::default()
7583 };
7584 let rem_size = self.rem_size(cx);
7585 window.with_rem_size(rem_size, |window| {
7586 window.with_text_style(Some(text_style), |window| {
7587 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7588 self.paint_mouse_listeners(layout, window, cx);
7589 self.paint_background(layout, window, cx);
7590 self.paint_indent_guides(layout, window, cx);
7591
7592 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7593 self.paint_blamed_display_rows(layout, window, cx);
7594 self.paint_line_numbers(layout, window, cx);
7595 }
7596
7597 self.paint_text(layout, window, cx);
7598
7599 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7600 self.paint_gutter_highlights(layout, window, cx);
7601 self.paint_gutter_indicators(layout, window, cx);
7602 }
7603
7604 if !layout.blocks.is_empty() {
7605 window.with_element_namespace("blocks", |window| {
7606 self.paint_blocks(layout, window, cx);
7607 });
7608 }
7609
7610 window.with_element_namespace("blocks", |window| {
7611 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7612 sticky_header.paint(window, cx)
7613 }
7614 });
7615
7616 self.paint_scrollbars(layout, window, cx);
7617 self.paint_inline_completion_popover(layout, window, cx);
7618 self.paint_mouse_context_menu(layout, window, cx);
7619 });
7620 })
7621 })
7622 }
7623}
7624
7625pub(super) fn gutter_bounds(
7626 editor_bounds: Bounds<Pixels>,
7627 gutter_dimensions: GutterDimensions,
7628) -> Bounds<Pixels> {
7629 Bounds {
7630 origin: editor_bounds.origin,
7631 size: size(gutter_dimensions.width, editor_bounds.size.height),
7632 }
7633}
7634
7635/// Holds information required for layouting the editor scrollbars.
7636struct ScrollbarLayoutInformation {
7637 /// The bounds of the editor area (excluding the content offset).
7638 editor_bounds: Bounds<Pixels>,
7639 /// The available range to scroll within the document.
7640 scroll_range: Size<Pixels>,
7641 /// The space available for one glyph in the editor.
7642 glyph_grid_cell: Size<Pixels>,
7643}
7644
7645impl ScrollbarLayoutInformation {
7646 pub fn new(
7647 editor_bounds: Bounds<Pixels>,
7648 glyph_grid_cell: Size<Pixels>,
7649 document_size: Size<Pixels>,
7650 longest_line_blame_width: Pixels,
7651 scrollbar_width: Pixels,
7652 editor_width: Pixels,
7653 settings: &EditorSettings,
7654 ) -> Self {
7655 let vertical_overscroll = match settings.scroll_beyond_last_line {
7656 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
7657 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
7658 ScrollBeyondLastLine::VerticalScrollMargin => {
7659 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
7660 }
7661 };
7662
7663 let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
7664 glyph_grid_cell.width + scrollbar_width
7665 } else {
7666 px(0.0)
7667 };
7668
7669 let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
7670
7671 let scroll_range = document_size + overscroll;
7672
7673 ScrollbarLayoutInformation {
7674 editor_bounds,
7675 scroll_range,
7676 glyph_grid_cell,
7677 }
7678 }
7679}
7680
7681impl IntoElement for EditorElement {
7682 type Element = Self;
7683
7684 fn into_element(self) -> Self::Element {
7685 self
7686 }
7687}
7688
7689pub struct EditorLayout {
7690 position_map: Rc<PositionMap>,
7691 hitbox: Hitbox,
7692 gutter_hitbox: Hitbox,
7693 content_origin: gpui::Point<Pixels>,
7694 scrollbars_layout: Option<EditorScrollbars>,
7695 mode: EditorMode,
7696 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7697 indent_guides: Option<Vec<IndentGuideLayout>>,
7698 visible_display_row_range: Range<DisplayRow>,
7699 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
7700 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
7701 line_elements: SmallVec<[AnyElement; 1]>,
7702 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7703 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7704 blamed_display_rows: Option<Vec<AnyElement>>,
7705 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
7706 inline_blame: Option<AnyElement>,
7707 blocks: Vec<BlockLayout>,
7708 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7709 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7710 redacted_ranges: Vec<Range<DisplayPoint>>,
7711 cursors: Vec<(DisplayPoint, Hsla)>,
7712 visible_cursors: Vec<CursorLayout>,
7713 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7714 code_actions_indicator: Option<AnyElement>,
7715 test_indicators: Vec<AnyElement>,
7716 breakpoints: Vec<AnyElement>,
7717 crease_toggles: Vec<Option<AnyElement>>,
7718 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
7719 diff_hunk_controls: Vec<AnyElement>,
7720 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7721 inline_completion_popover: Option<AnyElement>,
7722 mouse_context_menu: Option<AnyElement>,
7723 tab_invisible: ShapedLine,
7724 space_invisible: ShapedLine,
7725 sticky_buffer_header: Option<AnyElement>,
7726}
7727
7728impl EditorLayout {
7729 fn line_end_overshoot(&self) -> Pixels {
7730 0.15 * self.position_map.line_height
7731 }
7732}
7733
7734struct LineNumberLayout {
7735 shaped_line: ShapedLine,
7736 hitbox: Option<Hitbox>,
7737}
7738
7739struct ColoredRange<T> {
7740 start: T,
7741 end: T,
7742 color: Hsla,
7743}
7744
7745impl Along for ScrollbarAxes {
7746 type Unit = bool;
7747
7748 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
7749 match axis {
7750 ScrollbarAxis::Horizontal => self.horizontal,
7751 ScrollbarAxis::Vertical => self.vertical,
7752 }
7753 }
7754
7755 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
7756 match axis {
7757 ScrollbarAxis::Horizontal => ScrollbarAxes {
7758 horizontal: f(self.horizontal),
7759 vertical: self.vertical,
7760 },
7761 ScrollbarAxis::Vertical => ScrollbarAxes {
7762 horizontal: self.horizontal,
7763 vertical: f(self.vertical),
7764 },
7765 }
7766 }
7767}
7768
7769#[derive(Clone)]
7770struct EditorScrollbars {
7771 pub vertical: Option<ScrollbarLayout>,
7772 pub horizontal: Option<ScrollbarLayout>,
7773 pub visible: bool,
7774}
7775
7776impl EditorScrollbars {
7777 pub fn from_scrollbar_axes(
7778 settings_visibility: ScrollbarAxes,
7779 layout_information: &ScrollbarLayoutInformation,
7780 content_offset: gpui::Point<Pixels>,
7781 scroll_position: gpui::Point<f32>,
7782 scrollbar_width: Pixels,
7783 show_scrollbars: bool,
7784 window: &mut Window,
7785 ) -> Self {
7786 let ScrollbarLayoutInformation {
7787 editor_bounds,
7788 scroll_range,
7789 glyph_grid_cell,
7790 } = layout_information;
7791
7792 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
7793 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
7794 Corner::BottomLeft,
7795 editor_bounds.bottom_left(),
7796 size(
7797 if settings_visibility.vertical {
7798 editor_bounds.size.width - scrollbar_width
7799 } else {
7800 editor_bounds.size.width
7801 },
7802 scrollbar_width,
7803 ),
7804 ),
7805 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
7806 Corner::TopRight,
7807 editor_bounds.top_right(),
7808 size(scrollbar_width, editor_bounds.size.height),
7809 ),
7810 };
7811
7812 let mut create_scrollbar_layout = |axis| {
7813 settings_visibility
7814 .along(axis)
7815 .then(|| {
7816 (
7817 editor_bounds.size.along(axis) - content_offset.along(axis),
7818 scroll_range.along(axis),
7819 )
7820 })
7821 .filter(|(editor_content_size, scroll_range)| {
7822 // The scrollbar should only be rendered if the content does
7823 // not entirely fit into the editor
7824 // However, this only applies to the horizontal scrollbar, as information about the
7825 // vertical scrollbar layout is always needed for scrollbar diagnostics.
7826 axis != ScrollbarAxis::Horizontal || editor_content_size < scroll_range
7827 })
7828 .map(|(editor_content_size, scroll_range)| {
7829 ScrollbarLayout::new(
7830 window.insert_hitbox(scrollbar_bounds_for(axis), false),
7831 editor_content_size,
7832 scroll_range,
7833 glyph_grid_cell.along(axis),
7834 content_offset.along(axis),
7835 scroll_position.along(axis),
7836 axis,
7837 )
7838 })
7839 };
7840
7841 Self {
7842 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
7843 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
7844 visible: show_scrollbars,
7845 }
7846 }
7847
7848 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
7849 [
7850 (&self.vertical, ScrollbarAxis::Vertical),
7851 (&self.horizontal, ScrollbarAxis::Horizontal),
7852 ]
7853 .into_iter()
7854 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
7855 }
7856
7857 /// Returns the currently hovered scrollbar axis, if any.
7858 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
7859 self.iter_scrollbars()
7860 .find(|s| s.0.hitbox.is_hovered(window))
7861 }
7862}
7863
7864#[derive(Clone)]
7865struct ScrollbarLayout {
7866 hitbox: Hitbox,
7867 visible_range: Range<f32>,
7868 text_unit_size: Pixels,
7869 content_offset: Pixels,
7870 thumb_size: Pixels,
7871 axis: ScrollbarAxis,
7872}
7873
7874impl ScrollbarLayout {
7875 const BORDER_WIDTH: Pixels = px(1.0);
7876 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7877 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7878 const MIN_THUMB_SIZE: Pixels = px(25.0);
7879
7880 fn new(
7881 scrollbar_track_hitbox: Hitbox,
7882 editor_content_size: Pixels,
7883 scroll_range: Pixels,
7884 glyph_space: Pixels,
7885 content_offset: Pixels,
7886 scroll_position: f32,
7887 axis: ScrollbarAxis,
7888 ) -> Self {
7889 let track_bounds = scrollbar_track_hitbox.bounds;
7890 // The length of the track available to the scrollbar thumb. We deliberately
7891 // exclude the content size here so that the thumb aligns with the content.
7892 let track_length = track_bounds.size.along(axis) - content_offset;
7893
7894 let text_units_per_page = editor_content_size / glyph_space;
7895 let visible_range = scroll_position..scroll_position + text_units_per_page;
7896 let total_text_units = scroll_range / glyph_space;
7897
7898 let thumb_percentage = text_units_per_page / total_text_units;
7899 let thumb_size = (track_length * thumb_percentage)
7900 .max(ScrollbarLayout::MIN_THUMB_SIZE)
7901 .min(track_length);
7902 let text_unit_size =
7903 (track_length - thumb_size) / (total_text_units - text_units_per_page).max(0.);
7904
7905 ScrollbarLayout {
7906 hitbox: scrollbar_track_hitbox,
7907 visible_range,
7908 text_unit_size,
7909 content_offset,
7910 thumb_size,
7911 axis,
7912 }
7913 }
7914
7915 fn thumb_bounds(&self) -> Bounds<Pixels> {
7916 let scrollbar_track = &self.hitbox.bounds;
7917 Bounds::new(
7918 scrollbar_track
7919 .origin
7920 .apply_along(self.axis, |origin| self.thumb_origin(origin)),
7921 scrollbar_track
7922 .size
7923 .apply_along(self.axis, |_| self.thumb_size),
7924 )
7925 }
7926
7927 fn thumb_origin(&self, origin: Pixels) -> Pixels {
7928 origin + self.content_offset + self.visible_range.start * self.text_unit_size
7929 }
7930
7931 fn marker_quads_for_ranges(
7932 &self,
7933 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7934 column: Option<usize>,
7935 ) -> Vec<PaintQuad> {
7936 struct MinMax {
7937 min: Pixels,
7938 max: Pixels,
7939 }
7940 let (x_range, height_limit) = if let Some(column) = column {
7941 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7942 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7943 let end = start + column_width;
7944 (
7945 Range { start, end },
7946 MinMax {
7947 min: Self::MIN_MARKER_HEIGHT,
7948 max: px(f32::MAX),
7949 },
7950 )
7951 } else {
7952 (
7953 Range {
7954 start: Self::BORDER_WIDTH,
7955 end: self.hitbox.size.width,
7956 },
7957 MinMax {
7958 min: Self::LINE_MARKER_HEIGHT,
7959 max: Self::LINE_MARKER_HEIGHT,
7960 },
7961 )
7962 };
7963
7964 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7965 let mut pixel_ranges = row_ranges
7966 .into_iter()
7967 .map(|range| {
7968 let start_y = row_to_y(range.start);
7969 let end_y = row_to_y(range.end)
7970 + self
7971 .text_unit_size
7972 .max(height_limit.min)
7973 .min(height_limit.max);
7974 ColoredRange {
7975 start: start_y,
7976 end: end_y,
7977 color: range.color,
7978 }
7979 })
7980 .peekable();
7981
7982 let mut quads = Vec::new();
7983 while let Some(mut pixel_range) = pixel_ranges.next() {
7984 while let Some(next_pixel_range) = pixel_ranges.peek() {
7985 if pixel_range.end >= next_pixel_range.start - px(1.0)
7986 && pixel_range.color == next_pixel_range.color
7987 {
7988 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7989 pixel_ranges.next();
7990 } else {
7991 break;
7992 }
7993 }
7994
7995 let bounds = Bounds::from_corners(
7996 point(x_range.start, pixel_range.start),
7997 point(x_range.end, pixel_range.end),
7998 );
7999 quads.push(quad(
8000 bounds,
8001 Corners::default(),
8002 pixel_range.color,
8003 Edges::default(),
8004 Hsla::transparent_black(),
8005 BorderStyle::default(),
8006 ));
8007 }
8008
8009 quads
8010 }
8011}
8012
8013struct CreaseTrailerLayout {
8014 element: AnyElement,
8015 bounds: Bounds<Pixels>,
8016}
8017
8018pub(crate) struct PositionMap {
8019 pub size: Size<Pixels>,
8020 pub line_height: Pixels,
8021 pub scroll_pixel_position: gpui::Point<Pixels>,
8022 pub scroll_max: gpui::Point<f32>,
8023 pub em_width: Pixels,
8024 pub em_advance: Pixels,
8025 pub visible_row_range: Range<DisplayRow>,
8026 pub line_layouts: Vec<LineWithInvisibles>,
8027 pub snapshot: EditorSnapshot,
8028 pub text_hitbox: Hitbox,
8029 pub gutter_hitbox: Hitbox,
8030}
8031
8032#[derive(Debug, Copy, Clone)]
8033pub struct PointForPosition {
8034 pub previous_valid: DisplayPoint,
8035 pub next_valid: DisplayPoint,
8036 pub exact_unclipped: DisplayPoint,
8037 pub column_overshoot_after_line_end: u32,
8038}
8039
8040impl PointForPosition {
8041 pub fn as_valid(&self) -> Option<DisplayPoint> {
8042 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8043 Some(self.previous_valid)
8044 } else {
8045 None
8046 }
8047 }
8048}
8049
8050impl PositionMap {
8051 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8052 let text_bounds = self.text_hitbox.bounds;
8053 let scroll_position = self.snapshot.scroll_position();
8054 let position = position - text_bounds.origin;
8055 let y = position.y.max(px(0.)).min(self.size.height);
8056 let x = position.x + (scroll_position.x * self.em_width);
8057 let row = ((y / self.line_height) + scroll_position.y) as u32;
8058
8059 let (column, x_overshoot_after_line_end) = if let Some(line) = self
8060 .line_layouts
8061 .get(row as usize - scroll_position.y as usize)
8062 {
8063 if let Some(ix) = line.index_for_x(x) {
8064 (ix as u32, px(0.))
8065 } else {
8066 (line.len as u32, px(0.).max(x - line.width))
8067 }
8068 } else {
8069 (0, x)
8070 };
8071
8072 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8073 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8074 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8075
8076 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8077 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8078 PointForPosition {
8079 previous_valid,
8080 next_valid,
8081 exact_unclipped,
8082 column_overshoot_after_line_end,
8083 }
8084 }
8085}
8086
8087struct BlockLayout {
8088 id: BlockId,
8089 x_offset: Pixels,
8090 row: Option<DisplayRow>,
8091 element: AnyElement,
8092 available_space: Size<AvailableSpace>,
8093 style: BlockStyle,
8094 overlaps_gutter: bool,
8095 is_buffer_header: bool,
8096}
8097
8098pub fn layout_line(
8099 row: DisplayRow,
8100 snapshot: &EditorSnapshot,
8101 style: &EditorStyle,
8102 text_width: Pixels,
8103 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8104 window: &mut Window,
8105 cx: &mut App,
8106) -> LineWithInvisibles {
8107 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8108 LineWithInvisibles::from_chunks(
8109 chunks,
8110 &style,
8111 MAX_LINE_LEN,
8112 1,
8113 snapshot.mode,
8114 text_width,
8115 is_row_soft_wrapped,
8116 window,
8117 cx,
8118 )
8119 .pop()
8120 .unwrap()
8121}
8122
8123#[derive(Debug)]
8124pub struct IndentGuideLayout {
8125 origin: gpui::Point<Pixels>,
8126 length: Pixels,
8127 single_indent_width: Pixels,
8128 depth: u32,
8129 active: bool,
8130 settings: IndentGuideSettings,
8131}
8132
8133pub struct CursorLayout {
8134 origin: gpui::Point<Pixels>,
8135 block_width: Pixels,
8136 line_height: Pixels,
8137 color: Hsla,
8138 shape: CursorShape,
8139 block_text: Option<ShapedLine>,
8140 cursor_name: Option<AnyElement>,
8141}
8142
8143#[derive(Debug)]
8144pub struct CursorName {
8145 string: SharedString,
8146 color: Hsla,
8147 is_top_row: bool,
8148}
8149
8150impl CursorLayout {
8151 pub fn new(
8152 origin: gpui::Point<Pixels>,
8153 block_width: Pixels,
8154 line_height: Pixels,
8155 color: Hsla,
8156 shape: CursorShape,
8157 block_text: Option<ShapedLine>,
8158 ) -> CursorLayout {
8159 CursorLayout {
8160 origin,
8161 block_width,
8162 line_height,
8163 color,
8164 shape,
8165 block_text,
8166 cursor_name: None,
8167 }
8168 }
8169
8170 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8171 Bounds {
8172 origin: self.origin + origin,
8173 size: size(self.block_width, self.line_height),
8174 }
8175 }
8176
8177 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8178 match self.shape {
8179 CursorShape::Bar => Bounds {
8180 origin: self.origin + origin,
8181 size: size(px(2.0), self.line_height),
8182 },
8183 CursorShape::Block | CursorShape::Hollow => Bounds {
8184 origin: self.origin + origin,
8185 size: size(self.block_width, self.line_height),
8186 },
8187 CursorShape::Underline => Bounds {
8188 origin: self.origin
8189 + origin
8190 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8191 size: size(self.block_width, px(2.0)),
8192 },
8193 }
8194 }
8195
8196 pub fn layout(
8197 &mut self,
8198 origin: gpui::Point<Pixels>,
8199 cursor_name: Option<CursorName>,
8200 window: &mut Window,
8201 cx: &mut App,
8202 ) {
8203 if let Some(cursor_name) = cursor_name {
8204 let bounds = self.bounds(origin);
8205 let text_size = self.line_height / 1.5;
8206
8207 let name_origin = if cursor_name.is_top_row {
8208 point(bounds.right() - px(1.), bounds.top())
8209 } else {
8210 match self.shape {
8211 CursorShape::Bar => point(
8212 bounds.right() - px(2.),
8213 bounds.top() - text_size / 2. - px(1.),
8214 ),
8215 _ => point(
8216 bounds.right() - px(1.),
8217 bounds.top() - text_size / 2. - px(1.),
8218 ),
8219 }
8220 };
8221 let mut name_element = div()
8222 .bg(self.color)
8223 .text_size(text_size)
8224 .px_0p5()
8225 .line_height(text_size + px(2.))
8226 .text_color(cursor_name.color)
8227 .child(cursor_name.string.clone())
8228 .into_any_element();
8229
8230 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8231
8232 self.cursor_name = Some(name_element);
8233 }
8234 }
8235
8236 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8237 let bounds = self.bounds(origin);
8238
8239 //Draw background or border quad
8240 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8241 outline(bounds, self.color, BorderStyle::Solid)
8242 } else {
8243 fill(bounds, self.color)
8244 };
8245
8246 if let Some(name) = &mut self.cursor_name {
8247 name.paint(window, cx);
8248 }
8249
8250 window.paint_quad(cursor);
8251
8252 if let Some(block_text) = &self.block_text {
8253 block_text
8254 .paint(self.origin + origin, self.line_height, window, cx)
8255 .log_err();
8256 }
8257 }
8258
8259 pub fn shape(&self) -> CursorShape {
8260 self.shape
8261 }
8262}
8263
8264#[derive(Debug)]
8265pub struct HighlightedRange {
8266 pub start_y: Pixels,
8267 pub line_height: Pixels,
8268 pub lines: Vec<HighlightedRangeLine>,
8269 pub color: Hsla,
8270 pub corner_radius: Pixels,
8271}
8272
8273#[derive(Debug)]
8274pub struct HighlightedRangeLine {
8275 pub start_x: Pixels,
8276 pub end_x: Pixels,
8277}
8278
8279impl HighlightedRange {
8280 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8281 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8282 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8283 self.paint_lines(
8284 self.start_y + self.line_height,
8285 &self.lines[1..],
8286 bounds,
8287 window,
8288 );
8289 } else {
8290 self.paint_lines(self.start_y, &self.lines, bounds, window);
8291 }
8292 }
8293
8294 fn paint_lines(
8295 &self,
8296 start_y: Pixels,
8297 lines: &[HighlightedRangeLine],
8298 _bounds: Bounds<Pixels>,
8299 window: &mut Window,
8300 ) {
8301 if lines.is_empty() {
8302 return;
8303 }
8304
8305 let first_line = lines.first().unwrap();
8306 let last_line = lines.last().unwrap();
8307
8308 let first_top_left = point(first_line.start_x, start_y);
8309 let first_top_right = point(first_line.end_x, start_y);
8310
8311 let curve_height = point(Pixels::ZERO, self.corner_radius);
8312 let curve_width = |start_x: Pixels, end_x: Pixels| {
8313 let max = (end_x - start_x) / 2.;
8314 let width = if max < self.corner_radius {
8315 max
8316 } else {
8317 self.corner_radius
8318 };
8319
8320 point(width, Pixels::ZERO)
8321 };
8322
8323 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8324 let mut builder = gpui::PathBuilder::fill();
8325 builder.move_to(first_top_right - top_curve_width);
8326 builder.curve_to(first_top_right + curve_height, first_top_right);
8327
8328 let mut iter = lines.iter().enumerate().peekable();
8329 while let Some((ix, line)) = iter.next() {
8330 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8331
8332 if let Some((_, next_line)) = iter.peek() {
8333 let next_top_right = point(next_line.end_x, bottom_right.y);
8334
8335 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8336 Ordering::Equal => {
8337 builder.line_to(bottom_right);
8338 }
8339 Ordering::Less => {
8340 let curve_width = curve_width(next_top_right.x, bottom_right.x);
8341 builder.line_to(bottom_right - curve_height);
8342 if self.corner_radius > Pixels::ZERO {
8343 builder.curve_to(bottom_right - curve_width, bottom_right);
8344 }
8345 builder.line_to(next_top_right + curve_width);
8346 if self.corner_radius > Pixels::ZERO {
8347 builder.curve_to(next_top_right + curve_height, next_top_right);
8348 }
8349 }
8350 Ordering::Greater => {
8351 let curve_width = curve_width(bottom_right.x, next_top_right.x);
8352 builder.line_to(bottom_right - curve_height);
8353 if self.corner_radius > Pixels::ZERO {
8354 builder.curve_to(bottom_right + curve_width, bottom_right);
8355 }
8356 builder.line_to(next_top_right - curve_width);
8357 if self.corner_radius > Pixels::ZERO {
8358 builder.curve_to(next_top_right + curve_height, next_top_right);
8359 }
8360 }
8361 }
8362 } else {
8363 let curve_width = curve_width(line.start_x, line.end_x);
8364 builder.line_to(bottom_right - curve_height);
8365 if self.corner_radius > Pixels::ZERO {
8366 builder.curve_to(bottom_right - curve_width, bottom_right);
8367 }
8368
8369 let bottom_left = point(line.start_x, bottom_right.y);
8370 builder.line_to(bottom_left + curve_width);
8371 if self.corner_radius > Pixels::ZERO {
8372 builder.curve_to(bottom_left - curve_height, bottom_left);
8373 }
8374 }
8375 }
8376
8377 if first_line.start_x > last_line.start_x {
8378 let curve_width = curve_width(last_line.start_x, first_line.start_x);
8379 let second_top_left = point(last_line.start_x, start_y + self.line_height);
8380 builder.line_to(second_top_left + curve_height);
8381 if self.corner_radius > Pixels::ZERO {
8382 builder.curve_to(second_top_left + curve_width, second_top_left);
8383 }
8384 let first_bottom_left = point(first_line.start_x, second_top_left.y);
8385 builder.line_to(first_bottom_left - curve_width);
8386 if self.corner_radius > Pixels::ZERO {
8387 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8388 }
8389 }
8390
8391 builder.line_to(first_top_left + curve_height);
8392 if self.corner_radius > Pixels::ZERO {
8393 builder.curve_to(first_top_left + top_curve_width, first_top_left);
8394 }
8395 builder.line_to(first_top_right - top_curve_width);
8396
8397 if let Ok(path) = builder.build() {
8398 window.paint_path(path, self.color);
8399 }
8400 }
8401}
8402
8403enum CursorPopoverType {
8404 CodeContextMenu,
8405 EditPrediction,
8406}
8407
8408pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8409 (delta.pow(1.5) / 100.0).into()
8410}
8411
8412fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8413 (delta.pow(1.2) / 300.0).into()
8414}
8415
8416pub fn register_action<T: Action>(
8417 editor: &Entity<Editor>,
8418 window: &mut Window,
8419 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8420) {
8421 let editor = editor.clone();
8422 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8423 let action = action.downcast_ref().unwrap();
8424 if phase == DispatchPhase::Bubble {
8425 editor.update(cx, |editor, cx| {
8426 listener(editor, action, window, cx);
8427 })
8428 }
8429 })
8430}
8431
8432fn compute_auto_height_layout(
8433 editor: &mut Editor,
8434 max_lines: usize,
8435 max_line_number_width: Pixels,
8436 known_dimensions: Size<Option<Pixels>>,
8437 available_width: AvailableSpace,
8438 window: &mut Window,
8439 cx: &mut Context<Editor>,
8440) -> Option<Size<Pixels>> {
8441 let width = known_dimensions.width.or({
8442 if let AvailableSpace::Definite(available_width) = available_width {
8443 Some(available_width)
8444 } else {
8445 None
8446 }
8447 })?;
8448 if let Some(height) = known_dimensions.height {
8449 return Some(size(width, height));
8450 }
8451
8452 let style = editor.style.as_ref().unwrap();
8453 let font_id = window.text_system().resolve_font(&style.text.font());
8454 let font_size = style.text.font_size.to_pixels(window.rem_size());
8455 let line_height = style.text.line_height_in_pixels(window.rem_size());
8456 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8457
8458 let mut snapshot = editor.snapshot(window, cx);
8459 let gutter_dimensions = snapshot
8460 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8461 .unwrap_or_default();
8462
8463 editor.gutter_dimensions = gutter_dimensions;
8464 let text_width = width - gutter_dimensions.width;
8465 let overscroll = size(em_width, px(0.));
8466
8467 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8468 if editor.set_wrap_width(Some(editor_width), cx) {
8469 snapshot = editor.snapshot(window, cx);
8470 }
8471
8472 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
8473 let height = scroll_height
8474 .max(line_height)
8475 .min(line_height * max_lines as f32);
8476
8477 Some(size(width, height))
8478}
8479
8480#[cfg(test)]
8481mod tests {
8482 use super::*;
8483 use crate::{
8484 Editor, MultiBuffer,
8485 display_map::{BlockPlacement, BlockProperties},
8486 editor_tests::{init_test, update_test_language_settings},
8487 };
8488 use gpui::{TestAppContext, VisualTestContext};
8489 use language::language_settings;
8490 use log::info;
8491 use std::num::NonZeroU32;
8492 use util::test::sample_text;
8493
8494 #[gpui::test]
8495 fn test_shape_line_numbers(cx: &mut TestAppContext) {
8496 init_test(cx, |_| {});
8497 let window = cx.add_window(|window, cx| {
8498 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8499 Editor::new(EditorMode::Full, buffer, None, window, cx)
8500 });
8501
8502 let editor = window.root(cx).unwrap();
8503 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8504 let line_height = window
8505 .update(cx, |_, window, _| {
8506 style.text.line_height_in_pixels(window.rem_size())
8507 })
8508 .unwrap();
8509 let element = EditorElement::new(&editor, style);
8510 let snapshot = window
8511 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8512 .unwrap();
8513
8514 let layouts = cx
8515 .update_window(*window, |_, window, cx| {
8516 element.layout_line_numbers(
8517 None,
8518 GutterDimensions {
8519 left_padding: Pixels::ZERO,
8520 right_padding: Pixels::ZERO,
8521 width: px(30.0),
8522 margin: Pixels::ZERO,
8523 git_blame_entries_width: None,
8524 },
8525 line_height,
8526 gpui::Point::default(),
8527 DisplayRow(0)..DisplayRow(6),
8528 &(0..6)
8529 .map(|row| RowInfo {
8530 buffer_row: Some(row),
8531 ..Default::default()
8532 })
8533 .collect::<Vec<_>>(),
8534 &BTreeMap::default(),
8535 Some(DisplayPoint::new(DisplayRow(0), 0)),
8536 &snapshot,
8537 window,
8538 cx,
8539 )
8540 })
8541 .unwrap();
8542 assert_eq!(layouts.len(), 6);
8543
8544 let relative_rows = window
8545 .update(cx, |editor, window, cx| {
8546 let snapshot = editor.snapshot(window, cx);
8547 element.calculate_relative_line_numbers(
8548 &snapshot,
8549 &(DisplayRow(0)..DisplayRow(6)),
8550 Some(DisplayRow(3)),
8551 )
8552 })
8553 .unwrap();
8554 assert_eq!(relative_rows[&DisplayRow(0)], 3);
8555 assert_eq!(relative_rows[&DisplayRow(1)], 2);
8556 assert_eq!(relative_rows[&DisplayRow(2)], 1);
8557 // current line has no relative number
8558 assert_eq!(relative_rows[&DisplayRow(4)], 1);
8559 assert_eq!(relative_rows[&DisplayRow(5)], 2);
8560
8561 // works if cursor is before screen
8562 let relative_rows = window
8563 .update(cx, |editor, window, cx| {
8564 let snapshot = editor.snapshot(window, cx);
8565 element.calculate_relative_line_numbers(
8566 &snapshot,
8567 &(DisplayRow(3)..DisplayRow(6)),
8568 Some(DisplayRow(1)),
8569 )
8570 })
8571 .unwrap();
8572 assert_eq!(relative_rows.len(), 3);
8573 assert_eq!(relative_rows[&DisplayRow(3)], 2);
8574 assert_eq!(relative_rows[&DisplayRow(4)], 3);
8575 assert_eq!(relative_rows[&DisplayRow(5)], 4);
8576
8577 // works if cursor is after screen
8578 let relative_rows = window
8579 .update(cx, |editor, window, cx| {
8580 let snapshot = editor.snapshot(window, cx);
8581 element.calculate_relative_line_numbers(
8582 &snapshot,
8583 &(DisplayRow(0)..DisplayRow(3)),
8584 Some(DisplayRow(6)),
8585 )
8586 })
8587 .unwrap();
8588 assert_eq!(relative_rows.len(), 3);
8589 assert_eq!(relative_rows[&DisplayRow(0)], 5);
8590 assert_eq!(relative_rows[&DisplayRow(1)], 4);
8591 assert_eq!(relative_rows[&DisplayRow(2)], 3);
8592 }
8593
8594 #[gpui::test]
8595 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8596 init_test(cx, |_| {});
8597
8598 let window = cx.add_window(|window, cx| {
8599 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8600 Editor::new(EditorMode::Full, buffer, None, window, cx)
8601 });
8602 let cx = &mut VisualTestContext::from_window(*window, cx);
8603 let editor = window.root(cx).unwrap();
8604 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8605
8606 window
8607 .update(cx, |editor, window, cx| {
8608 editor.cursor_shape = CursorShape::Block;
8609 editor.change_selections(None, window, cx, |s| {
8610 s.select_ranges([
8611 Point::new(0, 0)..Point::new(1, 0),
8612 Point::new(3, 2)..Point::new(3, 3),
8613 Point::new(5, 6)..Point::new(6, 0),
8614 ]);
8615 });
8616 })
8617 .unwrap();
8618
8619 let (_, state) = cx.draw(
8620 point(px(500.), px(500.)),
8621 size(px(500.), px(500.)),
8622 |_, _| EditorElement::new(&editor, style),
8623 );
8624
8625 assert_eq!(state.selections.len(), 1);
8626 let local_selections = &state.selections[0].1;
8627 assert_eq!(local_selections.len(), 3);
8628 // moves cursor back one line
8629 assert_eq!(
8630 local_selections[0].head,
8631 DisplayPoint::new(DisplayRow(0), 6)
8632 );
8633 assert_eq!(
8634 local_selections[0].range,
8635 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8636 );
8637
8638 // moves cursor back one column
8639 assert_eq!(
8640 local_selections[1].range,
8641 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8642 );
8643 assert_eq!(
8644 local_selections[1].head,
8645 DisplayPoint::new(DisplayRow(3), 2)
8646 );
8647
8648 // leaves cursor on the max point
8649 assert_eq!(
8650 local_selections[2].range,
8651 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8652 );
8653 assert_eq!(
8654 local_selections[2].head,
8655 DisplayPoint::new(DisplayRow(6), 0)
8656 );
8657
8658 // active lines does not include 1 (even though the range of the selection does)
8659 assert_eq!(
8660 state.active_rows.keys().cloned().collect::<Vec<_>>(),
8661 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8662 );
8663 }
8664
8665 #[gpui::test]
8666 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8667 init_test(cx, |_| {});
8668
8669 let window = cx.add_window(|window, cx| {
8670 let buffer = MultiBuffer::build_simple("", cx);
8671 Editor::new(EditorMode::Full, buffer, None, window, cx)
8672 });
8673 let cx = &mut VisualTestContext::from_window(*window, cx);
8674 let editor = window.root(cx).unwrap();
8675 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8676 window
8677 .update(cx, |editor, window, cx| {
8678 editor.set_placeholder_text("hello", cx);
8679 editor.insert_blocks(
8680 [BlockProperties {
8681 style: BlockStyle::Fixed,
8682 placement: BlockPlacement::Above(Anchor::min()),
8683 height: Some(3),
8684 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8685 priority: 0,
8686 }],
8687 None,
8688 cx,
8689 );
8690
8691 // Blur the editor so that it displays placeholder text.
8692 window.blur();
8693 })
8694 .unwrap();
8695
8696 let (_, state) = cx.draw(
8697 point(px(500.), px(500.)),
8698 size(px(500.), px(500.)),
8699 |_, _| EditorElement::new(&editor, style),
8700 );
8701 assert_eq!(state.position_map.line_layouts.len(), 4);
8702 assert_eq!(state.line_numbers.len(), 1);
8703 assert_eq!(
8704 state
8705 .line_numbers
8706 .get(&MultiBufferRow(0))
8707 .map(|line_number| line_number.shaped_line.text.as_ref()),
8708 Some("1")
8709 );
8710 }
8711
8712 #[gpui::test]
8713 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8714 const TAB_SIZE: u32 = 4;
8715
8716 let input_text = "\t \t|\t| a b";
8717 let expected_invisibles = vec![
8718 Invisible::Tab {
8719 line_start_offset: 0,
8720 line_end_offset: TAB_SIZE as usize,
8721 },
8722 Invisible::Whitespace {
8723 line_offset: TAB_SIZE as usize,
8724 },
8725 Invisible::Tab {
8726 line_start_offset: TAB_SIZE as usize + 1,
8727 line_end_offset: TAB_SIZE as usize * 2,
8728 },
8729 Invisible::Tab {
8730 line_start_offset: TAB_SIZE as usize * 2 + 1,
8731 line_end_offset: TAB_SIZE as usize * 3,
8732 },
8733 Invisible::Whitespace {
8734 line_offset: TAB_SIZE as usize * 3 + 1,
8735 },
8736 Invisible::Whitespace {
8737 line_offset: TAB_SIZE as usize * 3 + 3,
8738 },
8739 ];
8740 assert_eq!(
8741 expected_invisibles.len(),
8742 input_text
8743 .chars()
8744 .filter(|initial_char| initial_char.is_whitespace())
8745 .count(),
8746 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8747 );
8748
8749 for show_line_numbers in [true, false] {
8750 init_test(cx, |s| {
8751 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8752 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8753 });
8754
8755 let actual_invisibles = collect_invisibles_from_new_editor(
8756 cx,
8757 EditorMode::Full,
8758 input_text,
8759 px(500.0),
8760 show_line_numbers,
8761 );
8762
8763 assert_eq!(expected_invisibles, actual_invisibles);
8764 }
8765 }
8766
8767 #[gpui::test]
8768 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8769 init_test(cx, |s| {
8770 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8771 s.defaults.tab_size = NonZeroU32::new(4);
8772 });
8773
8774 for editor_mode_without_invisibles in [
8775 EditorMode::SingleLine { auto_width: false },
8776 EditorMode::AutoHeight { max_lines: 100 },
8777 ] {
8778 for show_line_numbers in [true, false] {
8779 let invisibles = collect_invisibles_from_new_editor(
8780 cx,
8781 editor_mode_without_invisibles,
8782 "\t\t\t| | a b",
8783 px(500.0),
8784 show_line_numbers,
8785 );
8786 assert!(
8787 invisibles.is_empty(),
8788 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
8789 );
8790 }
8791 }
8792 }
8793
8794 #[gpui::test]
8795 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8796 let tab_size = 4;
8797 let input_text = "a\tbcd ".repeat(9);
8798 let repeated_invisibles = [
8799 Invisible::Tab {
8800 line_start_offset: 1,
8801 line_end_offset: tab_size as usize,
8802 },
8803 Invisible::Whitespace {
8804 line_offset: tab_size as usize + 3,
8805 },
8806 Invisible::Whitespace {
8807 line_offset: tab_size as usize + 4,
8808 },
8809 Invisible::Whitespace {
8810 line_offset: tab_size as usize + 5,
8811 },
8812 Invisible::Whitespace {
8813 line_offset: tab_size as usize + 6,
8814 },
8815 Invisible::Whitespace {
8816 line_offset: tab_size as usize + 7,
8817 },
8818 ];
8819 let expected_invisibles = std::iter::once(repeated_invisibles)
8820 .cycle()
8821 .take(9)
8822 .flatten()
8823 .collect::<Vec<_>>();
8824 assert_eq!(
8825 expected_invisibles.len(),
8826 input_text
8827 .chars()
8828 .filter(|initial_char| initial_char.is_whitespace())
8829 .count(),
8830 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8831 );
8832 info!("Expected invisibles: {expected_invisibles:?}");
8833
8834 init_test(cx, |_| {});
8835
8836 // Put the same string with repeating whitespace pattern into editors of various size,
8837 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8838 let resize_step = 10.0;
8839 let mut editor_width = 200.0;
8840 while editor_width <= 1000.0 {
8841 for show_line_numbers in [true, false] {
8842 update_test_language_settings(cx, |s| {
8843 s.defaults.tab_size = NonZeroU32::new(tab_size);
8844 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8845 s.defaults.preferred_line_length = Some(editor_width as u32);
8846 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8847 });
8848
8849 let actual_invisibles = collect_invisibles_from_new_editor(
8850 cx,
8851 EditorMode::Full,
8852 &input_text,
8853 px(editor_width),
8854 show_line_numbers,
8855 );
8856
8857 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8858 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8859 let mut i = 0;
8860 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8861 i = actual_index;
8862 match expected_invisibles.get(i) {
8863 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8864 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8865 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8866 _ => {
8867 panic!(
8868 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
8869 )
8870 }
8871 },
8872 None => {
8873 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8874 }
8875 }
8876 }
8877 let missing_expected_invisibles = &expected_invisibles[i + 1..];
8878 assert!(
8879 missing_expected_invisibles.is_empty(),
8880 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8881 );
8882
8883 editor_width += resize_step;
8884 }
8885 }
8886 }
8887
8888 fn collect_invisibles_from_new_editor(
8889 cx: &mut TestAppContext,
8890 editor_mode: EditorMode,
8891 input_text: &str,
8892 editor_width: Pixels,
8893 show_line_numbers: bool,
8894 ) -> Vec<Invisible> {
8895 info!(
8896 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8897 editor_width.0
8898 );
8899 let window = cx.add_window(|window, cx| {
8900 let buffer = MultiBuffer::build_simple(input_text, cx);
8901 Editor::new(editor_mode, buffer, None, window, cx)
8902 });
8903 let cx = &mut VisualTestContext::from_window(*window, cx);
8904 let editor = window.root(cx).unwrap();
8905
8906 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8907 window
8908 .update(cx, |editor, _, cx| {
8909 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8910 editor.set_wrap_width(Some(editor_width), cx);
8911 editor.set_show_line_numbers(show_line_numbers, cx);
8912 })
8913 .unwrap();
8914 let (_, state) = cx.draw(
8915 point(px(500.), px(500.)),
8916 size(px(500.), px(500.)),
8917 |_, _| EditorElement::new(&editor, style),
8918 );
8919 state
8920 .position_map
8921 .line_layouts
8922 .iter()
8923 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8924 .cloned()
8925 .collect()
8926 }
8927}