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