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