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