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