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