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