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