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 | ScrollbarThumbState::Hovered => {
5284 cx.theme().colors().scrollbar_thumb_hover_background
5285 }
5286 ScrollbarThumbState::Idle => cx.theme().colors().scrollbar_thumb_background,
5287 };
5288 window.paint_quad(quad(
5289 thumb_bounds,
5290 Corners::default(),
5291 scrollbar_thumb_color,
5292 scrollbar_edges,
5293 cx.theme().colors().scrollbar_thumb_border,
5294 BorderStyle::Solid,
5295 ));
5296 })
5297 }
5298 window.set_cursor_style(CursorStyle::Arrow, Some(&hitbox));
5299 }
5300
5301 window.on_mouse_event({
5302 let editor = self.editor.clone();
5303 let scrollbars_layout = scrollbars_layout.clone();
5304
5305 let mut mouse_position = window.mouse_position();
5306 move |event: &MouseMoveEvent, phase, window, cx| {
5307 if phase == DispatchPhase::Capture {
5308 return;
5309 }
5310
5311 editor.update(cx, |editor, cx| {
5312 if let Some((scrollbar_layout, axis)) = event
5313 .pressed_button
5314 .filter(|button| *button == MouseButton::Left)
5315 .and(editor.scroll_manager.dragging_scrollbar_axis())
5316 .and_then(|axis| {
5317 scrollbars_layout
5318 .iter_scrollbars()
5319 .find(|(_, a)| *a == axis)
5320 })
5321 {
5322 let ScrollbarLayout {
5323 hitbox,
5324 text_unit_size,
5325 ..
5326 } = scrollbar_layout;
5327
5328 let old_position = mouse_position.along(axis);
5329 let new_position = event.position.along(axis);
5330 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
5331 .contains(&old_position)
5332 {
5333 let position = editor.scroll_position(cx).apply_along(axis, |p| {
5334 (p + (new_position - old_position) / *text_unit_size).max(0.)
5335 });
5336 editor.set_scroll_position(position, window, cx);
5337 }
5338
5339 editor.scroll_manager.show_scrollbars(window, cx);
5340 cx.stop_propagation();
5341 } else if let Some((layout, axis)) = scrollbars_layout.get_hovered_axis(window)
5342 {
5343 if layout.thumb_bounds().contains(&event.position) {
5344 editor
5345 .scroll_manager
5346 .set_hovered_scroll_thumb_axis(axis, cx);
5347 } else {
5348 editor.scroll_manager.reset_scrollbar_state(cx);
5349 }
5350
5351 editor.scroll_manager.show_scrollbars(window, cx);
5352 } else {
5353 editor.scroll_manager.reset_scrollbar_state(cx);
5354 }
5355
5356 mouse_position = event.position;
5357 })
5358 }
5359 });
5360
5361 if self.editor.read(cx).scroll_manager.any_scrollbar_dragged() {
5362 window.on_mouse_event({
5363 let editor = self.editor.clone();
5364 move |_: &MouseUpEvent, phase, window, cx| {
5365 if phase == DispatchPhase::Capture {
5366 return;
5367 }
5368
5369 editor.update(cx, |editor, cx| {
5370 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
5371 editor
5372 .scroll_manager
5373 .set_hovered_scroll_thumb_axis(axis, cx);
5374 } else {
5375 editor.scroll_manager.reset_scrollbar_state(cx);
5376 }
5377 cx.stop_propagation();
5378 });
5379 }
5380 });
5381 } else {
5382 window.on_mouse_event({
5383 let editor = self.editor.clone();
5384
5385 move |event: &MouseDownEvent, phase, window, cx| {
5386 if phase == DispatchPhase::Capture {
5387 return;
5388 }
5389 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
5390 else {
5391 return;
5392 };
5393
5394 let ScrollbarLayout {
5395 hitbox,
5396 visible_range,
5397 text_unit_size,
5398 ..
5399 } = scrollbar_layout;
5400
5401 let thumb_bounds = scrollbar_layout.thumb_bounds();
5402
5403 editor.update(cx, |editor, cx| {
5404 editor
5405 .scroll_manager
5406 .set_dragged_scroll_thumb_axis(axis, cx);
5407
5408 let event_position = event.position.along(axis);
5409
5410 if event_position < thumb_bounds.origin.along(axis)
5411 || thumb_bounds.bottom_right().along(axis) < event_position
5412 {
5413 let center_position = ((event_position - hitbox.origin.along(axis))
5414 / *text_unit_size)
5415 .round() as u32;
5416 let start_position = center_position.saturating_sub(
5417 (visible_range.end - visible_range.start) as u32 / 2,
5418 );
5419
5420 let position = editor
5421 .scroll_position(cx)
5422 .apply_along(axis, |_| start_position as f32);
5423
5424 editor.set_scroll_position(position, window, cx);
5425 } else {
5426 editor.scroll_manager.show_scrollbars(window, cx);
5427 }
5428
5429 cx.stop_propagation();
5430 });
5431 }
5432 });
5433 }
5434 }
5435
5436 fn collect_fast_scrollbar_markers(
5437 &self,
5438 layout: &EditorLayout,
5439 scrollbar_layout: &ScrollbarLayout,
5440 cx: &mut App,
5441 ) -> Vec<PaintQuad> {
5442 const LIMIT: usize = 100;
5443 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5444 return vec![];
5445 }
5446 let cursor_ranges = layout
5447 .cursors
5448 .iter()
5449 .map(|(point, color)| ColoredRange {
5450 start: point.row(),
5451 end: point.row(),
5452 color: *color,
5453 })
5454 .collect_vec();
5455 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5456 }
5457
5458 fn refresh_slow_scrollbar_markers(
5459 &self,
5460 layout: &EditorLayout,
5461 scrollbar_layout: &ScrollbarLayout,
5462 window: &mut Window,
5463 cx: &mut App,
5464 ) {
5465 self.editor.update(cx, |editor, cx| {
5466 if !editor.is_singleton(cx)
5467 || !editor
5468 .scrollbar_marker_state
5469 .should_refresh(scrollbar_layout.hitbox.size)
5470 {
5471 return;
5472 }
5473
5474 let scrollbar_layout = scrollbar_layout.clone();
5475 let background_highlights = editor.background_highlights.clone();
5476 let snapshot = layout.position_map.snapshot.clone();
5477 let theme = cx.theme().clone();
5478 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5479
5480 editor.scrollbar_marker_state.dirty = false;
5481 editor.scrollbar_marker_state.pending_refresh =
5482 Some(cx.spawn_in(window, async move |editor, cx| {
5483 let scrollbar_size = scrollbar_layout.hitbox.size;
5484 let scrollbar_markers = cx
5485 .background_spawn(async move {
5486 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5487 let mut marker_quads = Vec::new();
5488 if scrollbar_settings.git_diff {
5489 let marker_row_ranges =
5490 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5491 let start_display_row =
5492 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5493 .to_display_point(&snapshot.display_snapshot)
5494 .row();
5495 let mut end_display_row =
5496 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5497 .to_display_point(&snapshot.display_snapshot)
5498 .row();
5499 if end_display_row != start_display_row {
5500 end_display_row.0 -= 1;
5501 }
5502 let color = match &hunk.status().kind {
5503 DiffHunkStatusKind::Added => {
5504 theme.colors().version_control_added
5505 }
5506 DiffHunkStatusKind::Modified => {
5507 theme.colors().version_control_modified
5508 }
5509 DiffHunkStatusKind::Deleted => {
5510 theme.colors().version_control_deleted
5511 }
5512 };
5513 ColoredRange {
5514 start: start_display_row,
5515 end: end_display_row,
5516 color,
5517 }
5518 });
5519
5520 marker_quads.extend(
5521 scrollbar_layout
5522 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5523 );
5524 }
5525
5526 for (background_highlight_id, (_, background_ranges)) in
5527 background_highlights.iter()
5528 {
5529 let is_search_highlights = *background_highlight_id
5530 == TypeId::of::<BufferSearchHighlights>();
5531 let is_text_highlights = *background_highlight_id
5532 == TypeId::of::<SelectedTextHighlight>();
5533 let is_symbol_occurrences = *background_highlight_id
5534 == TypeId::of::<DocumentHighlightRead>()
5535 || *background_highlight_id
5536 == TypeId::of::<DocumentHighlightWrite>();
5537 if (is_search_highlights && scrollbar_settings.search_results)
5538 || (is_text_highlights && scrollbar_settings.selected_text)
5539 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5540 {
5541 let mut color = theme.status().info;
5542 if is_symbol_occurrences {
5543 color.fade_out(0.5);
5544 }
5545 let marker_row_ranges = background_ranges.iter().map(|range| {
5546 let display_start = range
5547 .start
5548 .to_display_point(&snapshot.display_snapshot);
5549 let display_end =
5550 range.end.to_display_point(&snapshot.display_snapshot);
5551 ColoredRange {
5552 start: display_start.row(),
5553 end: display_end.row(),
5554 color,
5555 }
5556 });
5557 marker_quads.extend(
5558 scrollbar_layout
5559 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5560 );
5561 }
5562 }
5563
5564 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5565 let diagnostics = snapshot
5566 .buffer_snapshot
5567 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5568 // Don't show diagnostics the user doesn't care about
5569 .filter(|diagnostic| {
5570 match (
5571 scrollbar_settings.diagnostics,
5572 diagnostic.diagnostic.severity,
5573 ) {
5574 (ScrollbarDiagnostics::All, _) => true,
5575 (
5576 ScrollbarDiagnostics::Error,
5577 DiagnosticSeverity::ERROR,
5578 ) => true,
5579 (
5580 ScrollbarDiagnostics::Warning,
5581 DiagnosticSeverity::ERROR
5582 | DiagnosticSeverity::WARNING,
5583 ) => true,
5584 (
5585 ScrollbarDiagnostics::Information,
5586 DiagnosticSeverity::ERROR
5587 | DiagnosticSeverity::WARNING
5588 | DiagnosticSeverity::INFORMATION,
5589 ) => true,
5590 (_, _) => false,
5591 }
5592 })
5593 // We want to sort by severity, in order to paint the most severe diagnostics last.
5594 .sorted_by_key(|diagnostic| {
5595 std::cmp::Reverse(diagnostic.diagnostic.severity)
5596 });
5597
5598 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5599 let start_display = diagnostic
5600 .range
5601 .start
5602 .to_display_point(&snapshot.display_snapshot);
5603 let end_display = diagnostic
5604 .range
5605 .end
5606 .to_display_point(&snapshot.display_snapshot);
5607 let color = match diagnostic.diagnostic.severity {
5608 DiagnosticSeverity::ERROR => theme.status().error,
5609 DiagnosticSeverity::WARNING => theme.status().warning,
5610 DiagnosticSeverity::INFORMATION => theme.status().info,
5611 _ => theme.status().hint,
5612 };
5613 ColoredRange {
5614 start: start_display.row(),
5615 end: end_display.row(),
5616 color,
5617 }
5618 });
5619 marker_quads.extend(
5620 scrollbar_layout
5621 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5622 );
5623 }
5624
5625 Arc::from(marker_quads)
5626 })
5627 .await;
5628
5629 editor.update(cx, |editor, cx| {
5630 editor.scrollbar_marker_state.markers = scrollbar_markers;
5631 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5632 editor.scrollbar_marker_state.pending_refresh = None;
5633 cx.notify();
5634 })?;
5635
5636 Ok(())
5637 }));
5638 });
5639 }
5640
5641 fn paint_highlighted_range(
5642 &self,
5643 range: Range<DisplayPoint>,
5644 color: Hsla,
5645 corner_radius: Pixels,
5646 line_end_overshoot: Pixels,
5647 layout: &EditorLayout,
5648 window: &mut Window,
5649 ) {
5650 let start_row = layout.visible_display_row_range.start;
5651 let end_row = layout.visible_display_row_range.end;
5652 if range.start != range.end {
5653 let row_range = if range.end.column() == 0 {
5654 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5655 } else {
5656 cmp::max(range.start.row(), start_row)
5657 ..cmp::min(range.end.row().next_row(), end_row)
5658 };
5659
5660 let highlighted_range = HighlightedRange {
5661 color,
5662 line_height: layout.position_map.line_height,
5663 corner_radius,
5664 start_y: layout.content_origin.y
5665 + row_range.start.as_f32() * layout.position_map.line_height
5666 - layout.position_map.scroll_pixel_position.y,
5667 lines: row_range
5668 .iter_rows()
5669 .map(|row| {
5670 let line_layout =
5671 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5672 HighlightedRangeLine {
5673 start_x: if row == range.start.row() {
5674 layout.content_origin.x
5675 + line_layout.x_for_index(range.start.column() as usize)
5676 - layout.position_map.scroll_pixel_position.x
5677 } else {
5678 layout.content_origin.x
5679 - layout.position_map.scroll_pixel_position.x
5680 },
5681 end_x: if row == range.end.row() {
5682 layout.content_origin.x
5683 + line_layout.x_for_index(range.end.column() as usize)
5684 - layout.position_map.scroll_pixel_position.x
5685 } else {
5686 layout.content_origin.x + line_layout.width + line_end_overshoot
5687 - layout.position_map.scroll_pixel_position.x
5688 },
5689 }
5690 })
5691 .collect(),
5692 };
5693
5694 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5695 }
5696 }
5697
5698 fn paint_inline_diagnostics(
5699 &mut self,
5700 layout: &mut EditorLayout,
5701 window: &mut Window,
5702 cx: &mut App,
5703 ) {
5704 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
5705 inline_diagnostic.1.paint(window, cx);
5706 }
5707 }
5708
5709 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5710 if let Some(mut inline_blame) = layout.inline_blame.take() {
5711 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5712 inline_blame.paint(window, cx);
5713 })
5714 }
5715 }
5716
5717 fn paint_diff_hunk_controls(
5718 &mut self,
5719 layout: &mut EditorLayout,
5720 window: &mut Window,
5721 cx: &mut App,
5722 ) {
5723 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5724 diff_hunk_control.paint(window, cx);
5725 }
5726 }
5727
5728 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5729 if let Some(mut layout) = layout.minimap.take() {
5730 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
5731 let thumb_bounds = layout.thumb_layout.thumb_bounds();
5732
5733 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
5734 window.with_element_namespace("minimap", |window| {
5735 layout.minimap.paint(window, cx);
5736 if layout.show_thumb {
5737 let minimap_thumb_border = match layout.thumb_border_style {
5738 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
5739 MinimapThumbBorder::LeftOnly => Edges {
5740 left: ScrollbarLayout::BORDER_WIDTH,
5741 ..Default::default()
5742 },
5743 MinimapThumbBorder::LeftOpen => Edges {
5744 right: ScrollbarLayout::BORDER_WIDTH,
5745 top: ScrollbarLayout::BORDER_WIDTH,
5746 bottom: ScrollbarLayout::BORDER_WIDTH,
5747 ..Default::default()
5748 },
5749 MinimapThumbBorder::RightOpen => Edges {
5750 left: ScrollbarLayout::BORDER_WIDTH,
5751 top: ScrollbarLayout::BORDER_WIDTH,
5752 bottom: ScrollbarLayout::BORDER_WIDTH,
5753 ..Default::default()
5754 },
5755 MinimapThumbBorder::None => Default::default(),
5756 };
5757
5758 window.paint_layer(minimap_hitbox.bounds, |window| {
5759 window.paint_quad(quad(
5760 thumb_bounds,
5761 Corners::default(),
5762 cx.theme().colors().scrollbar_thumb_background,
5763 minimap_thumb_border,
5764 cx.theme().colors().scrollbar_thumb_border,
5765 BorderStyle::Solid,
5766 ));
5767 });
5768 }
5769 });
5770 });
5771
5772 window.set_cursor_style(CursorStyle::Arrow, Some(&minimap_hitbox));
5773
5774 let minimap_axis = ScrollbarAxis::Vertical;
5775 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
5776 .min(layout.minimap_line_height);
5777
5778 let mut mouse_position = window.mouse_position();
5779
5780 window.on_mouse_event({
5781 let editor = self.editor.clone();
5782
5783 let minimap_hitbox = minimap_hitbox.clone();
5784
5785 move |event: &MouseMoveEvent, phase, window, cx| {
5786 if phase == DispatchPhase::Capture {
5787 return;
5788 }
5789
5790 editor.update(cx, |editor, cx| {
5791 if event.pressed_button == Some(MouseButton::Left)
5792 && editor.scroll_manager.is_dragging_minimap()
5793 {
5794 let old_position = mouse_position.along(minimap_axis);
5795 let new_position = event.position.along(minimap_axis);
5796 if (minimap_hitbox.origin.along(minimap_axis)
5797 ..minimap_hitbox.bottom_right().along(minimap_axis))
5798 .contains(&old_position)
5799 {
5800 let position =
5801 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
5802 (p + (new_position - old_position) / pixels_per_line)
5803 .max(0.)
5804 });
5805 editor.set_scroll_position(position, window, cx);
5806 }
5807 cx.stop_propagation();
5808 } else {
5809 editor.scroll_manager.set_is_dragging_minimap(false, cx);
5810
5811 if minimap_hitbox.is_hovered(window) {
5812 editor.scroll_manager.show_minimap_thumb(cx);
5813
5814 // Stop hover events from propagating to the
5815 // underlying editor if the minimap hitbox is hovered
5816 if !event.dragging() {
5817 cx.stop_propagation();
5818 }
5819 } else {
5820 editor.scroll_manager.hide_minimap_thumb(cx);
5821 }
5822 }
5823 mouse_position = event.position;
5824 });
5825 }
5826 });
5827
5828 if self.editor.read(cx).scroll_manager.is_dragging_minimap() {
5829 window.on_mouse_event({
5830 let editor = self.editor.clone();
5831 move |_: &MouseUpEvent, phase, _, cx| {
5832 if phase == DispatchPhase::Capture {
5833 return;
5834 }
5835
5836 editor.update(cx, |editor, cx| {
5837 editor.scroll_manager.set_is_dragging_minimap(false, cx);
5838 cx.stop_propagation();
5839 });
5840 }
5841 });
5842 } else {
5843 window.on_mouse_event({
5844 let editor = self.editor.clone();
5845
5846 move |event: &MouseDownEvent, phase, window, cx| {
5847 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
5848 return;
5849 }
5850
5851 let event_position = event.position;
5852
5853 editor.update(cx, |editor, cx| {
5854 if !thumb_bounds.contains(&event_position) {
5855 let click_position =
5856 event_position.relative_to(&minimap_hitbox.origin).y;
5857
5858 let top_position = (click_position
5859 - thumb_bounds.size.along(minimap_axis) / 2.0)
5860 .max(Pixels::ZERO);
5861
5862 let scroll_offset = (layout.minimap_scroll_top
5863 + top_position / layout.minimap_line_height)
5864 .min(layout.max_scroll_top);
5865
5866 let scroll_position = editor
5867 .scroll_position(cx)
5868 .apply_along(minimap_axis, |_| scroll_offset);
5869 editor.set_scroll_position(scroll_position, window, cx);
5870 }
5871
5872 editor.scroll_manager.set_is_dragging_minimap(true, cx);
5873 cx.stop_propagation();
5874 });
5875 }
5876 });
5877 }
5878 }
5879 }
5880
5881 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5882 for mut block in layout.blocks.drain(..) {
5883 if block.overlaps_gutter {
5884 block.element.paint(window, cx);
5885 } else {
5886 let mut bounds = layout.hitbox.bounds;
5887 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
5888 window.with_content_mask(Some(ContentMask { bounds }), |window| {
5889 block.element.paint(window, cx);
5890 })
5891 }
5892 }
5893 }
5894
5895 fn paint_inline_completion_popover(
5896 &mut self,
5897 layout: &mut EditorLayout,
5898 window: &mut Window,
5899 cx: &mut App,
5900 ) {
5901 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5902 inline_completion_popover.paint(window, cx);
5903 }
5904 }
5905
5906 fn paint_mouse_context_menu(
5907 &mut self,
5908 layout: &mut EditorLayout,
5909 window: &mut Window,
5910 cx: &mut App,
5911 ) {
5912 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5913 mouse_context_menu.paint(window, cx);
5914 }
5915 }
5916
5917 fn paint_scroll_wheel_listener(
5918 &mut self,
5919 layout: &EditorLayout,
5920 window: &mut Window,
5921 cx: &mut App,
5922 ) {
5923 window.on_mouse_event({
5924 let position_map = layout.position_map.clone();
5925 let editor = self.editor.clone();
5926 let hitbox = layout.hitbox.clone();
5927 let mut delta = ScrollDelta::default();
5928
5929 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5930 // accidentally turn off their scrolling.
5931 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5932
5933 move |event: &ScrollWheelEvent, phase, window, cx| {
5934 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5935 delta = delta.coalesce(event.delta);
5936 editor.update(cx, |editor, cx| {
5937 let position_map: &PositionMap = &position_map;
5938
5939 let line_height = position_map.line_height;
5940 let max_glyph_width = position_map.em_width;
5941 let (delta, axis) = match delta {
5942 gpui::ScrollDelta::Pixels(mut pixels) => {
5943 //Trackpad
5944 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5945 (pixels, axis)
5946 }
5947
5948 gpui::ScrollDelta::Lines(lines) => {
5949 //Not trackpad
5950 let pixels =
5951 point(lines.x * max_glyph_width, lines.y * line_height);
5952 (pixels, None)
5953 }
5954 };
5955
5956 let current_scroll_position = position_map.snapshot.scroll_position();
5957 let x = (current_scroll_position.x * max_glyph_width
5958 - (delta.x * scroll_sensitivity))
5959 / max_glyph_width;
5960 let y = (current_scroll_position.y * line_height
5961 - (delta.y * scroll_sensitivity))
5962 / line_height;
5963 let mut scroll_position =
5964 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5965 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5966 if forbid_vertical_scroll {
5967 scroll_position.y = current_scroll_position.y;
5968 }
5969
5970 if scroll_position != current_scroll_position {
5971 editor.scroll(scroll_position, axis, window, cx);
5972 cx.stop_propagation();
5973 } else if y < 0. {
5974 // Due to clamping, we may fail to detect cases of overscroll to the top;
5975 // We want the scroll manager to get an update in such cases and detect the change of direction
5976 // on the next frame.
5977 cx.notify();
5978 }
5979 });
5980 }
5981 }
5982 });
5983 }
5984
5985 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5986 if self.editor.read(cx).mode.is_minimap() {
5987 return;
5988 }
5989
5990 self.paint_scroll_wheel_listener(layout, window, cx);
5991
5992 window.on_mouse_event({
5993 let position_map = layout.position_map.clone();
5994 let editor = self.editor.clone();
5995 let diff_hunk_range =
5996 layout
5997 .display_hunks
5998 .iter()
5999 .find_map(|(hunk, hunk_hitbox)| match hunk {
6000 DisplayDiffHunk::Folded { .. } => None,
6001 DisplayDiffHunk::Unfolded {
6002 multi_buffer_range, ..
6003 } => {
6004 if hunk_hitbox
6005 .as_ref()
6006 .map(|hitbox| hitbox.is_hovered(window))
6007 .unwrap_or(false)
6008 {
6009 Some(multi_buffer_range.clone())
6010 } else {
6011 None
6012 }
6013 }
6014 });
6015 let line_numbers = layout.line_numbers.clone();
6016
6017 move |event: &MouseDownEvent, phase, window, cx| {
6018 if phase == DispatchPhase::Bubble {
6019 match event.button {
6020 MouseButton::Left => editor.update(cx, |editor, cx| {
6021 let pending_mouse_down = editor
6022 .pending_mouse_down
6023 .get_or_insert_with(Default::default)
6024 .clone();
6025
6026 *pending_mouse_down.borrow_mut() = Some(event.clone());
6027
6028 Self::mouse_left_down(
6029 editor,
6030 event,
6031 diff_hunk_range.clone(),
6032 &position_map,
6033 line_numbers.as_ref(),
6034 window,
6035 cx,
6036 );
6037 }),
6038 MouseButton::Right => editor.update(cx, |editor, cx| {
6039 Self::mouse_right_down(editor, event, &position_map, window, cx);
6040 }),
6041 MouseButton::Middle => editor.update(cx, |editor, cx| {
6042 Self::mouse_middle_down(editor, event, &position_map, window, cx);
6043 }),
6044 _ => {}
6045 };
6046 }
6047 }
6048 });
6049
6050 window.on_mouse_event({
6051 let editor = self.editor.clone();
6052 let position_map = layout.position_map.clone();
6053
6054 move |event: &MouseUpEvent, phase, window, cx| {
6055 if phase == DispatchPhase::Bubble {
6056 editor.update(cx, |editor, cx| {
6057 Self::mouse_up(editor, event, &position_map, window, cx)
6058 });
6059 }
6060 }
6061 });
6062
6063 window.on_mouse_event({
6064 let editor = self.editor.clone();
6065 let position_map = layout.position_map.clone();
6066 let mut captured_mouse_down = None;
6067
6068 move |event: &MouseUpEvent, phase, window, cx| match phase {
6069 // Clear the pending mouse down during the capture phase,
6070 // so that it happens even if another event handler stops
6071 // propagation.
6072 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
6073 let pending_mouse_down = editor
6074 .pending_mouse_down
6075 .get_or_insert_with(Default::default)
6076 .clone();
6077
6078 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
6079 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
6080 captured_mouse_down = pending_mouse_down.take();
6081 window.refresh();
6082 }
6083 }),
6084 // Fire click handlers during the bubble phase.
6085 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
6086 if let Some(mouse_down) = captured_mouse_down.take() {
6087 let event = ClickEvent {
6088 down: mouse_down,
6089 up: event.clone(),
6090 };
6091 Self::click(editor, &event, &position_map, window, cx);
6092 }
6093 }),
6094 }
6095 });
6096
6097 window.on_mouse_event({
6098 let position_map = layout.position_map.clone();
6099 let editor = self.editor.clone();
6100
6101 move |event: &MouseMoveEvent, phase, window, cx| {
6102 if phase == DispatchPhase::Bubble {
6103 editor.update(cx, |editor, cx| {
6104 if editor.hover_state.focused(window, cx) {
6105 return;
6106 }
6107 if event.pressed_button == Some(MouseButton::Left)
6108 || event.pressed_button == Some(MouseButton::Middle)
6109 {
6110 Self::mouse_dragged(editor, event, &position_map, window, cx)
6111 }
6112
6113 Self::mouse_moved(editor, event, &position_map, window, cx)
6114 });
6115 }
6116 }
6117 });
6118 }
6119
6120 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
6121 bounds.top_right().x - self.style.scrollbar_width
6122 }
6123
6124 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
6125 let style = &self.style;
6126 let font_size = style.text.font_size.to_pixels(window.rem_size());
6127 let layout = window
6128 .text_system()
6129 .shape_line(
6130 SharedString::from(" ".repeat(column)),
6131 font_size,
6132 &[TextRun {
6133 len: column,
6134 font: style.text.font(),
6135 color: Hsla::default(),
6136 background_color: None,
6137 underline: None,
6138 strikethrough: None,
6139 }],
6140 )
6141 .unwrap();
6142
6143 layout.width
6144 }
6145
6146 fn max_line_number_width(
6147 &self,
6148 snapshot: &EditorSnapshot,
6149 window: &mut Window,
6150 cx: &mut App,
6151 ) -> Pixels {
6152 let digit_count = snapshot.widest_line_number().ilog10() + 1;
6153 self.column_pixels(digit_count as usize, window, cx)
6154 }
6155
6156 fn shape_line_number(
6157 &self,
6158 text: SharedString,
6159 color: Hsla,
6160 window: &mut Window,
6161 ) -> anyhow::Result<ShapedLine> {
6162 let run = TextRun {
6163 len: text.len(),
6164 font: self.style.text.font(),
6165 color,
6166 background_color: None,
6167 underline: None,
6168 strikethrough: None,
6169 };
6170 window.text_system().shape_line(
6171 text,
6172 self.style.text.font_size.to_pixels(window.rem_size()),
6173 &[run],
6174 )
6175 }
6176
6177 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
6178 let unstaged = status.has_secondary_hunk();
6179 let unstaged_hollow = ProjectSettings::get_global(cx)
6180 .git
6181 .hunk_style
6182 .map_or(false, |style| {
6183 matches!(style, GitHunkStyleSetting::UnstagedHollow)
6184 });
6185
6186 unstaged == unstaged_hollow
6187 }
6188}
6189
6190fn header_jump_data(
6191 snapshot: &EditorSnapshot,
6192 block_row_start: DisplayRow,
6193 height: u32,
6194 for_excerpt: &ExcerptInfo,
6195) -> JumpData {
6196 let range = &for_excerpt.range;
6197 let buffer = &for_excerpt.buffer;
6198 let jump_anchor = range.primary.start;
6199
6200 let excerpt_start = range.context.start;
6201 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
6202 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
6203 0
6204 } else {
6205 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
6206 jump_position.row.saturating_sub(excerpt_start_point.row)
6207 };
6208
6209 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
6210 .saturating_sub(
6211 snapshot
6212 .scroll_anchor
6213 .scroll_position(&snapshot.display_snapshot)
6214 .y as u32,
6215 );
6216
6217 JumpData::MultiBufferPoint {
6218 excerpt_id: for_excerpt.id,
6219 anchor: jump_anchor,
6220 position: jump_position,
6221 line_offset_from_top,
6222 }
6223}
6224
6225pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
6226
6227impl AcceptEditPredictionBinding {
6228 pub fn keystroke(&self) -> Option<&Keystroke> {
6229 if let Some(binding) = self.0.as_ref() {
6230 match &binding.keystrokes() {
6231 [keystroke] => Some(keystroke),
6232 _ => None,
6233 }
6234 } else {
6235 None
6236 }
6237 }
6238}
6239
6240fn prepaint_gutter_button(
6241 button: IconButton,
6242 row: DisplayRow,
6243 line_height: Pixels,
6244 gutter_dimensions: &GutterDimensions,
6245 scroll_pixel_position: gpui::Point<Pixels>,
6246 gutter_hitbox: &Hitbox,
6247 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
6248 window: &mut Window,
6249 cx: &mut App,
6250) -> AnyElement {
6251 let mut button = button.into_any_element();
6252
6253 let available_space = size(
6254 AvailableSpace::MinContent,
6255 AvailableSpace::Definite(line_height),
6256 );
6257 let indicator_size = button.layout_as_root(available_space, window, cx);
6258
6259 let blame_width = gutter_dimensions.git_blame_entries_width;
6260 let gutter_width = display_hunks
6261 .binary_search_by(|(hunk, _)| match hunk {
6262 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
6263 DisplayDiffHunk::Unfolded {
6264 display_row_range, ..
6265 } => {
6266 if display_row_range.end <= row {
6267 Ordering::Less
6268 } else if display_row_range.start > row {
6269 Ordering::Greater
6270 } else {
6271 Ordering::Equal
6272 }
6273 }
6274 })
6275 .ok()
6276 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
6277 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
6278
6279 let mut x = left_offset;
6280 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
6281 - indicator_size.width
6282 - left_offset;
6283 x += available_width / 2.;
6284
6285 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
6286 y += (line_height - indicator_size.height) / 2.;
6287
6288 button.prepaint_as_root(
6289 gutter_hitbox.origin + point(x, y),
6290 available_space,
6291 window,
6292 cx,
6293 );
6294 button
6295}
6296
6297fn render_inline_blame_entry(
6298 blame_entry: BlameEntry,
6299 style: &EditorStyle,
6300 cx: &mut App,
6301) -> Option<AnyElement> {
6302 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6303 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
6304}
6305
6306fn render_blame_entry_popover(
6307 blame_entry: BlameEntry,
6308 scroll_handle: ScrollHandle,
6309 commit_message: Option<ParsedCommitMessage>,
6310 markdown: Entity<Markdown>,
6311 workspace: WeakEntity<Workspace>,
6312 blame: &Entity<GitBlame>,
6313 window: &mut Window,
6314 cx: &mut App,
6315) -> Option<AnyElement> {
6316 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
6317 let blame = blame.read(cx);
6318 let repository = blame.repository(cx)?.clone();
6319 renderer.render_blame_entry_popover(
6320 blame_entry,
6321 scroll_handle,
6322 commit_message,
6323 markdown,
6324 repository,
6325 workspace,
6326 window,
6327 cx,
6328 )
6329}
6330
6331fn render_blame_entry(
6332 ix: usize,
6333 blame: &Entity<GitBlame>,
6334 blame_entry: BlameEntry,
6335 style: &EditorStyle,
6336 last_used_color: &mut Option<(PlayerColor, Oid)>,
6337 editor: Entity<Editor>,
6338 workspace: Entity<Workspace>,
6339 renderer: Arc<dyn BlameRenderer>,
6340 cx: &mut App,
6341) -> Option<AnyElement> {
6342 let mut sha_color = cx
6343 .theme()
6344 .players()
6345 .color_for_participant(blame_entry.sha.into());
6346
6347 // If the last color we used is the same as the one we get for this line, but
6348 // the commit SHAs are different, then we try again to get a different color.
6349 match *last_used_color {
6350 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
6351 let index: u32 = blame_entry.sha.into();
6352 sha_color = cx.theme().players().color_for_participant(index + 1);
6353 }
6354 _ => {}
6355 };
6356 last_used_color.replace((sha_color, blame_entry.sha));
6357
6358 let blame = blame.read(cx);
6359 let details = blame.details_for_entry(&blame_entry);
6360 let repository = blame.repository(cx)?;
6361 renderer.render_blame_entry(
6362 &style.text,
6363 blame_entry,
6364 details,
6365 repository,
6366 workspace.downgrade(),
6367 editor,
6368 ix,
6369 sha_color.cursor,
6370 cx,
6371 )
6372}
6373
6374#[derive(Debug)]
6375pub(crate) struct LineWithInvisibles {
6376 fragments: SmallVec<[LineFragment; 1]>,
6377 invisibles: Vec<Invisible>,
6378 len: usize,
6379 pub(crate) width: Pixels,
6380 font_size: Pixels,
6381}
6382
6383#[allow(clippy::large_enum_variant)]
6384enum LineFragment {
6385 Text(ShapedLine),
6386 Element {
6387 id: FoldId,
6388 element: Option<AnyElement>,
6389 size: Size<Pixels>,
6390 len: usize,
6391 },
6392}
6393
6394impl fmt::Debug for LineFragment {
6395 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6396 match self {
6397 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6398 LineFragment::Element { size, len, .. } => f
6399 .debug_struct("Element")
6400 .field("size", size)
6401 .field("len", len)
6402 .finish(),
6403 }
6404 }
6405}
6406
6407impl LineWithInvisibles {
6408 fn from_chunks<'a>(
6409 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6410 editor_style: &EditorStyle,
6411 max_line_len: usize,
6412 max_line_count: usize,
6413 editor_mode: &EditorMode,
6414 text_width: Pixels,
6415 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6416 window: &mut Window,
6417 cx: &mut App,
6418 ) -> Vec<Self> {
6419 let text_style = &editor_style.text;
6420 let mut layouts = Vec::with_capacity(max_line_count);
6421 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6422 let mut line = String::new();
6423 let mut invisibles = Vec::new();
6424 let mut width = Pixels::ZERO;
6425 let mut len = 0;
6426 let mut styles = Vec::new();
6427 let mut non_whitespace_added = false;
6428 let mut row = 0;
6429 let mut line_exceeded_max_len = false;
6430 let font_size = text_style.font_size.to_pixels(window.rem_size());
6431
6432 let ellipsis = SharedString::from("⋯");
6433
6434 for highlighted_chunk in chunks.chain([HighlightedChunk {
6435 text: "\n",
6436 style: None,
6437 is_tab: false,
6438 replacement: None,
6439 }]) {
6440 if let Some(replacement) = highlighted_chunk.replacement {
6441 if !line.is_empty() {
6442 let shaped_line = window
6443 .text_system()
6444 .shape_line(line.clone().into(), font_size, &styles)
6445 .unwrap();
6446 width += shaped_line.width;
6447 len += shaped_line.len;
6448 fragments.push(LineFragment::Text(shaped_line));
6449 line.clear();
6450 styles.clear();
6451 }
6452
6453 match replacement {
6454 ChunkReplacement::Renderer(renderer) => {
6455 let available_width = if renderer.constrain_width {
6456 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6457 ellipsis.clone()
6458 } else {
6459 SharedString::from(Arc::from(highlighted_chunk.text))
6460 };
6461 let shaped_line = window
6462 .text_system()
6463 .shape_line(
6464 chunk,
6465 font_size,
6466 &[text_style.to_run(highlighted_chunk.text.len())],
6467 )
6468 .unwrap();
6469 AvailableSpace::Definite(shaped_line.width)
6470 } else {
6471 AvailableSpace::MinContent
6472 };
6473
6474 let mut element = (renderer.render)(&mut ChunkRendererContext {
6475 context: cx,
6476 window,
6477 max_width: text_width,
6478 });
6479 let line_height = text_style.line_height_in_pixels(window.rem_size());
6480 let size = element.layout_as_root(
6481 size(available_width, AvailableSpace::Definite(line_height)),
6482 window,
6483 cx,
6484 );
6485
6486 width += size.width;
6487 len += highlighted_chunk.text.len();
6488 fragments.push(LineFragment::Element {
6489 id: renderer.id,
6490 element: Some(element),
6491 size,
6492 len: highlighted_chunk.text.len(),
6493 });
6494 }
6495 ChunkReplacement::Str(x) => {
6496 let text_style = if let Some(style) = highlighted_chunk.style {
6497 Cow::Owned(text_style.clone().highlight(style))
6498 } else {
6499 Cow::Borrowed(text_style)
6500 };
6501
6502 let run = TextRun {
6503 len: x.len(),
6504 font: text_style.font(),
6505 color: text_style.color,
6506 background_color: text_style.background_color,
6507 underline: text_style.underline,
6508 strikethrough: text_style.strikethrough,
6509 };
6510 let line_layout = window
6511 .text_system()
6512 .shape_line(x, font_size, &[run])
6513 .unwrap()
6514 .with_len(highlighted_chunk.text.len());
6515
6516 width += line_layout.width;
6517 len += highlighted_chunk.text.len();
6518 fragments.push(LineFragment::Text(line_layout))
6519 }
6520 }
6521 } else {
6522 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6523 if ix > 0 {
6524 let shaped_line = window
6525 .text_system()
6526 .shape_line(line.clone().into(), font_size, &styles)
6527 .unwrap();
6528 width += shaped_line.width;
6529 len += shaped_line.len;
6530 fragments.push(LineFragment::Text(shaped_line));
6531 layouts.push(Self {
6532 width: mem::take(&mut width),
6533 len: mem::take(&mut len),
6534 fragments: mem::take(&mut fragments),
6535 invisibles: std::mem::take(&mut invisibles),
6536 font_size,
6537 });
6538
6539 line.clear();
6540 styles.clear();
6541 row += 1;
6542 line_exceeded_max_len = false;
6543 non_whitespace_added = false;
6544 if row == max_line_count {
6545 return layouts;
6546 }
6547 }
6548
6549 if !line_chunk.is_empty() && !line_exceeded_max_len {
6550 let text_style = if let Some(style) = highlighted_chunk.style {
6551 Cow::Owned(text_style.clone().highlight(style))
6552 } else {
6553 Cow::Borrowed(text_style)
6554 };
6555
6556 if line.len() + line_chunk.len() > max_line_len {
6557 let mut chunk_len = max_line_len - line.len();
6558 while !line_chunk.is_char_boundary(chunk_len) {
6559 chunk_len -= 1;
6560 }
6561 line_chunk = &line_chunk[..chunk_len];
6562 line_exceeded_max_len = true;
6563 }
6564
6565 styles.push(TextRun {
6566 len: line_chunk.len(),
6567 font: text_style.font(),
6568 color: text_style.color,
6569 background_color: text_style.background_color,
6570 underline: text_style.underline,
6571 strikethrough: text_style.strikethrough,
6572 });
6573
6574 if editor_mode.is_full() {
6575 // Line wrap pads its contents with fake whitespaces,
6576 // avoid printing them
6577 let is_soft_wrapped = is_row_soft_wrapped(row);
6578 if highlighted_chunk.is_tab {
6579 if non_whitespace_added || !is_soft_wrapped {
6580 invisibles.push(Invisible::Tab {
6581 line_start_offset: line.len(),
6582 line_end_offset: line.len() + line_chunk.len(),
6583 });
6584 }
6585 } else {
6586 invisibles.extend(line_chunk.char_indices().filter_map(
6587 |(index, c)| {
6588 let is_whitespace = c.is_whitespace();
6589 non_whitespace_added |= !is_whitespace;
6590 if is_whitespace
6591 && (non_whitespace_added || !is_soft_wrapped)
6592 {
6593 Some(Invisible::Whitespace {
6594 line_offset: line.len() + index,
6595 })
6596 } else {
6597 None
6598 }
6599 },
6600 ))
6601 }
6602 }
6603
6604 line.push_str(line_chunk);
6605 }
6606 }
6607 }
6608 }
6609
6610 layouts
6611 }
6612
6613 fn prepaint(
6614 &mut self,
6615 line_height: Pixels,
6616 scroll_pixel_position: gpui::Point<Pixels>,
6617 row: DisplayRow,
6618 content_origin: gpui::Point<Pixels>,
6619 line_elements: &mut SmallVec<[AnyElement; 1]>,
6620 window: &mut Window,
6621 cx: &mut App,
6622 ) {
6623 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6624 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6625 for fragment in &mut self.fragments {
6626 match fragment {
6627 LineFragment::Text(line) => {
6628 fragment_origin.x += line.width;
6629 }
6630 LineFragment::Element { element, size, .. } => {
6631 let mut element = element
6632 .take()
6633 .expect("you can't prepaint LineWithInvisibles twice");
6634
6635 // Center the element vertically within the line.
6636 let mut element_origin = fragment_origin;
6637 element_origin.y += (line_height - size.height) / 2.;
6638 element.prepaint_at(element_origin, window, cx);
6639 line_elements.push(element);
6640
6641 fragment_origin.x += size.width;
6642 }
6643 }
6644 }
6645 }
6646
6647 fn draw(
6648 &self,
6649 layout: &EditorLayout,
6650 row: DisplayRow,
6651 content_origin: gpui::Point<Pixels>,
6652 whitespace_setting: ShowWhitespaceSetting,
6653 selection_ranges: &[Range<DisplayPoint>],
6654 window: &mut Window,
6655 cx: &mut App,
6656 ) {
6657 let line_height = layout.position_map.line_height;
6658 let line_y = line_height
6659 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6660
6661 let mut fragment_origin =
6662 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6663
6664 for fragment in &self.fragments {
6665 match fragment {
6666 LineFragment::Text(line) => {
6667 line.paint(fragment_origin, line_height, window, cx)
6668 .log_err();
6669 fragment_origin.x += line.width;
6670 }
6671 LineFragment::Element { size, .. } => {
6672 fragment_origin.x += size.width;
6673 }
6674 }
6675 }
6676
6677 self.draw_invisibles(
6678 selection_ranges,
6679 layout,
6680 content_origin,
6681 line_y,
6682 row,
6683 line_height,
6684 whitespace_setting,
6685 window,
6686 cx,
6687 );
6688 }
6689
6690 fn draw_background(
6691 &self,
6692 layout: &EditorLayout,
6693 row: DisplayRow,
6694 content_origin: gpui::Point<Pixels>,
6695 window: &mut Window,
6696 cx: &mut App,
6697 ) {
6698 let line_height = layout.position_map.line_height;
6699 let line_y = line_height
6700 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6701
6702 let mut fragment_origin =
6703 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6704
6705 for fragment in &self.fragments {
6706 match fragment {
6707 LineFragment::Text(line) => {
6708 line.paint_background(fragment_origin, line_height, window, cx)
6709 .log_err();
6710 fragment_origin.x += line.width;
6711 }
6712 LineFragment::Element { size, .. } => {
6713 fragment_origin.x += size.width;
6714 }
6715 }
6716 }
6717 }
6718
6719 fn draw_invisibles(
6720 &self,
6721 selection_ranges: &[Range<DisplayPoint>],
6722 layout: &EditorLayout,
6723 content_origin: gpui::Point<Pixels>,
6724 line_y: Pixels,
6725 row: DisplayRow,
6726 line_height: Pixels,
6727 whitespace_setting: ShowWhitespaceSetting,
6728 window: &mut Window,
6729 cx: &mut App,
6730 ) {
6731 let extract_whitespace_info = |invisible: &Invisible| {
6732 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6733 Invisible::Tab {
6734 line_start_offset,
6735 line_end_offset,
6736 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6737 Invisible::Whitespace { line_offset } => {
6738 (*line_offset, line_offset + 1, &layout.space_invisible)
6739 }
6740 };
6741
6742 let x_offset = self.x_for_index(token_offset);
6743 let invisible_offset =
6744 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6745 let origin = content_origin
6746 + gpui::point(
6747 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6748 line_y,
6749 );
6750
6751 (
6752 [token_offset, token_end_offset],
6753 Box::new(move |window: &mut Window, cx: &mut App| {
6754 invisible_symbol
6755 .paint(origin, line_height, window, cx)
6756 .log_err();
6757 }),
6758 )
6759 };
6760
6761 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6762 match whitespace_setting {
6763 ShowWhitespaceSetting::None => (),
6764 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6765 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6766 let invisible_point = DisplayPoint::new(row, start as u32);
6767 if !selection_ranges
6768 .iter()
6769 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6770 {
6771 return;
6772 }
6773
6774 paint(window, cx);
6775 }),
6776
6777 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6778 // - It is a tab
6779 // - It is adjacent to an edge (start or end)
6780 // - It is adjacent to a whitespace (left or right)
6781 ShowWhitespaceSetting::Boundary => {
6782 // 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
6783 // the above cases.
6784 // Note: We zip in the original `invisibles` to check for tab equality
6785 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6786 for (([start, end], paint), invisible) in
6787 invisible_iter.zip_eq(self.invisibles.iter())
6788 {
6789 let should_render = match (&last_seen, invisible) {
6790 (_, Invisible::Tab { .. }) => true,
6791 (Some((_, last_end, _)), _) => *last_end == start,
6792 _ => false,
6793 };
6794
6795 if should_render || start == 0 || end == self.len {
6796 paint(window, cx);
6797
6798 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6799 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6800 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6801 // Note that we need to make sure that the last one is actually adjacent
6802 if !should_render_last && last_end == start {
6803 paint_last(window, cx);
6804 }
6805 }
6806 }
6807
6808 // Manually render anything within a selection
6809 let invisible_point = DisplayPoint::new(row, start as u32);
6810 if selection_ranges.iter().any(|region| {
6811 region.start <= invisible_point && invisible_point < region.end
6812 }) {
6813 paint(window, cx);
6814 }
6815
6816 last_seen = Some((should_render, end, paint));
6817 }
6818 }
6819 }
6820 }
6821
6822 pub fn x_for_index(&self, index: usize) -> Pixels {
6823 let mut fragment_start_x = Pixels::ZERO;
6824 let mut fragment_start_index = 0;
6825
6826 for fragment in &self.fragments {
6827 match fragment {
6828 LineFragment::Text(shaped_line) => {
6829 let fragment_end_index = fragment_start_index + shaped_line.len;
6830 if index < fragment_end_index {
6831 return fragment_start_x
6832 + shaped_line.x_for_index(index - fragment_start_index);
6833 }
6834 fragment_start_x += shaped_line.width;
6835 fragment_start_index = fragment_end_index;
6836 }
6837 LineFragment::Element { len, size, .. } => {
6838 let fragment_end_index = fragment_start_index + len;
6839 if index < fragment_end_index {
6840 return fragment_start_x;
6841 }
6842 fragment_start_x += size.width;
6843 fragment_start_index = fragment_end_index;
6844 }
6845 }
6846 }
6847
6848 fragment_start_x
6849 }
6850
6851 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6852 let mut fragment_start_x = Pixels::ZERO;
6853 let mut fragment_start_index = 0;
6854
6855 for fragment in &self.fragments {
6856 match fragment {
6857 LineFragment::Text(shaped_line) => {
6858 let fragment_end_x = fragment_start_x + shaped_line.width;
6859 if x < fragment_end_x {
6860 return Some(
6861 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6862 );
6863 }
6864 fragment_start_x = fragment_end_x;
6865 fragment_start_index += shaped_line.len;
6866 }
6867 LineFragment::Element { len, size, .. } => {
6868 let fragment_end_x = fragment_start_x + size.width;
6869 if x < fragment_end_x {
6870 return Some(fragment_start_index);
6871 }
6872 fragment_start_index += len;
6873 fragment_start_x = fragment_end_x;
6874 }
6875 }
6876 }
6877
6878 None
6879 }
6880
6881 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6882 let mut fragment_start_index = 0;
6883
6884 for fragment in &self.fragments {
6885 match fragment {
6886 LineFragment::Text(shaped_line) => {
6887 let fragment_end_index = fragment_start_index + shaped_line.len;
6888 if index < fragment_end_index {
6889 return shaped_line.font_id_for_index(index - fragment_start_index);
6890 }
6891 fragment_start_index = fragment_end_index;
6892 }
6893 LineFragment::Element { len, .. } => {
6894 let fragment_end_index = fragment_start_index + len;
6895 if index < fragment_end_index {
6896 return None;
6897 }
6898 fragment_start_index = fragment_end_index;
6899 }
6900 }
6901 }
6902
6903 None
6904 }
6905}
6906
6907#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6908enum Invisible {
6909 /// A tab character
6910 ///
6911 /// A tab character is internally represented by spaces (configured by the user's tab width)
6912 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6913 /// adjacency checks.
6914 Tab {
6915 line_start_offset: usize,
6916 line_end_offset: usize,
6917 },
6918 Whitespace {
6919 line_offset: usize,
6920 },
6921}
6922
6923impl EditorElement {
6924 /// Returns the rem size to use when rendering the [`EditorElement`].
6925 ///
6926 /// This allows UI elements to scale based on the `buffer_font_size`.
6927 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6928 match self.editor.read(cx).mode {
6929 EditorMode::Full {
6930 scale_ui_elements_with_buffer_font_size: true,
6931 ..
6932 }
6933 | EditorMode::Minimap { .. } => {
6934 let buffer_font_size = self.style.text.font_size;
6935 match buffer_font_size {
6936 AbsoluteLength::Pixels(pixels) => {
6937 let rem_size_scale = {
6938 // Our default UI font size is 14px on a 16px base scale.
6939 // This means the default UI font size is 0.875rems.
6940 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6941
6942 // We then determine the delta between a single rem and the default font
6943 // size scale.
6944 let default_font_size_delta = 1. - default_font_size_scale;
6945
6946 // Finally, we add this delta to 1rem to get the scale factor that
6947 // should be used to scale up the UI.
6948 1. + default_font_size_delta
6949 };
6950
6951 Some(pixels * rem_size_scale)
6952 }
6953 AbsoluteLength::Rems(rems) => {
6954 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6955 }
6956 }
6957 }
6958 // We currently use single-line and auto-height editors in UI contexts,
6959 // so we don't want to scale everything with the buffer font size, as it
6960 // ends up looking off.
6961 _ => None,
6962 }
6963 }
6964
6965 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
6966 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
6967 parent.upgrade()
6968 } else {
6969 Some(self.editor.clone())
6970 }
6971 }
6972}
6973
6974impl Element for EditorElement {
6975 type RequestLayoutState = ();
6976 type PrepaintState = EditorLayout;
6977
6978 fn id(&self) -> Option<ElementId> {
6979 None
6980 }
6981
6982 fn request_layout(
6983 &mut self,
6984 _: Option<&GlobalElementId>,
6985 window: &mut Window,
6986 cx: &mut App,
6987 ) -> (gpui::LayoutId, ()) {
6988 let rem_size = self.rem_size(cx);
6989 window.with_rem_size(rem_size, |window| {
6990 self.editor.update(cx, |editor, cx| {
6991 editor.set_style(self.style.clone(), window, cx);
6992
6993 let layout_id = match editor.mode {
6994 EditorMode::SingleLine { auto_width } => {
6995 let rem_size = window.rem_size();
6996
6997 let height = self.style.text.line_height_in_pixels(rem_size);
6998 if auto_width {
6999 let editor_handle = cx.entity().clone();
7000 let style = self.style.clone();
7001 window.request_measured_layout(
7002 Style::default(),
7003 move |_, _, window, cx| {
7004 let editor_snapshot = editor_handle
7005 .update(cx, |editor, cx| editor.snapshot(window, cx));
7006 let line = Self::layout_lines(
7007 DisplayRow(0)..DisplayRow(1),
7008 &editor_snapshot,
7009 &style,
7010 px(f32::MAX),
7011 |_| false, // Single lines never soft wrap
7012 window,
7013 cx,
7014 )
7015 .pop()
7016 .unwrap();
7017
7018 let font_id =
7019 window.text_system().resolve_font(&style.text.font());
7020 let font_size =
7021 style.text.font_size.to_pixels(window.rem_size());
7022 let em_width =
7023 window.text_system().em_width(font_id, font_size).unwrap();
7024
7025 size(line.width + em_width, height)
7026 },
7027 )
7028 } else {
7029 let mut style = Style::default();
7030 style.size.height = height.into();
7031 style.size.width = relative(1.).into();
7032 window.request_layout(style, None, cx)
7033 }
7034 }
7035 EditorMode::AutoHeight { max_lines } => {
7036 let editor_handle = cx.entity().clone();
7037 let max_line_number_width =
7038 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
7039 window.request_measured_layout(
7040 Style::default(),
7041 move |known_dimensions, available_space, window, cx| {
7042 editor_handle
7043 .update(cx, |editor, cx| {
7044 compute_auto_height_layout(
7045 editor,
7046 max_lines,
7047 max_line_number_width,
7048 known_dimensions,
7049 available_space.width,
7050 window,
7051 cx,
7052 )
7053 })
7054 .unwrap_or_default()
7055 },
7056 )
7057 }
7058 EditorMode::Minimap { .. } => {
7059 let mut style = Style::default();
7060 style.size.width = relative(1.).into();
7061 style.size.height = relative(1.).into();
7062 window.request_layout(style, None, cx)
7063 }
7064 EditorMode::Full {
7065 sized_by_content, ..
7066 } => {
7067 let mut style = Style::default();
7068 style.size.width = relative(1.).into();
7069 if sized_by_content {
7070 let snapshot = editor.snapshot(window, cx);
7071 let line_height =
7072 self.style.text.line_height_in_pixels(window.rem_size());
7073 let scroll_height =
7074 (snapshot.max_point().row().next_row().0 as f32) * line_height;
7075 style.size.height = scroll_height.into();
7076 } else {
7077 style.size.height = relative(1.).into();
7078 }
7079 window.request_layout(style, None, cx)
7080 }
7081 };
7082
7083 (layout_id, ())
7084 })
7085 })
7086 }
7087
7088 fn prepaint(
7089 &mut self,
7090 _: Option<&GlobalElementId>,
7091 bounds: Bounds<Pixels>,
7092 _: &mut Self::RequestLayoutState,
7093 window: &mut Window,
7094 cx: &mut App,
7095 ) -> Self::PrepaintState {
7096 let text_style = TextStyleRefinement {
7097 font_size: Some(self.style.text.font_size),
7098 line_height: Some(self.style.text.line_height),
7099 ..Default::default()
7100 };
7101 let focus_handle = self.editor.focus_handle(cx);
7102 window.set_view_id(self.editor.entity_id());
7103 window.set_focus_handle(&focus_handle, cx);
7104
7105 let rem_size = self.rem_size(cx);
7106 window.with_rem_size(rem_size, |window| {
7107 window.with_text_style(Some(text_style), |window| {
7108 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7109 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
7110 (editor.snapshot(window, cx), editor.read_only(cx))
7111 });
7112 let style = self.style.clone();
7113
7114 let font_id = window.text_system().resolve_font(&style.text.font());
7115 let font_size = style.text.font_size.to_pixels(window.rem_size());
7116 let line_height = style.text.line_height_in_pixels(window.rem_size());
7117 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
7118 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
7119
7120 let glyph_grid_cell = size(em_width, line_height);
7121
7122 let gutter_dimensions = snapshot
7123 .gutter_dimensions(
7124 font_id,
7125 font_size,
7126 self.max_line_number_width(&snapshot, window, cx),
7127 cx,
7128 )
7129 .unwrap_or_else(|| {
7130 GutterDimensions::default_with_margin(font_id, font_size, cx)
7131 });
7132 let text_width = bounds.size.width - gutter_dimensions.width;
7133
7134 let settings = EditorSettings::get_global(cx);
7135 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
7136 let vertical_scrollbar_width = (scrollbars_shown
7137 && settings.scrollbar.axes.vertical
7138 && self
7139 .editor
7140 .read_with(cx, |editor, _| editor.show_scrollbars))
7141 .then_some(style.scrollbar_width)
7142 .unwrap_or_default();
7143 let minimap_width = self
7144 .editor
7145 .read_with(cx, |editor, _| editor.minimap().is_some())
7146 .then(|| match settings.minimap.show {
7147 ShowMinimap::Never => None,
7148 ShowMinimap::Always => Some(MinimapLayout::MINIMAP_WIDTH),
7149 ShowMinimap::Auto => {
7150 scrollbars_shown.then_some(MinimapLayout::MINIMAP_WIDTH)
7151 }
7152 })
7153 .flatten()
7154 .filter(|minimap_width| {
7155 text_width - vertical_scrollbar_width - *minimap_width > *minimap_width
7156 })
7157 .unwrap_or_default();
7158
7159 let right_margin = minimap_width + vertical_scrollbar_width;
7160
7161 let editor_width =
7162 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
7163
7164 // Offset the content_bounds from the text_bounds by the gutter margin (which
7165 // is roughly half a character wide) to make hit testing work more like how we want.
7166 let content_offset = point(gutter_dimensions.margin, Pixels::ZERO);
7167
7168 let editor_content_width = editor_width - content_offset.x;
7169
7170 snapshot = self.editor.update(cx, |editor, cx| {
7171 editor.last_bounds = Some(bounds);
7172 editor.gutter_dimensions = gutter_dimensions;
7173 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
7174
7175 if matches!(
7176 editor.mode,
7177 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
7178 ) {
7179 snapshot
7180 } else {
7181 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
7182 let wrap_width = match editor.soft_wrap_mode(cx) {
7183 SoftWrap::GitDiff => None,
7184 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
7185 SoftWrap::EditorWidth => Some(editor_content_width),
7186 SoftWrap::Column(column) => Some(wrap_width_for(column)),
7187 SoftWrap::Bounded(column) => {
7188 Some(editor_content_width.min(wrap_width_for(column)))
7189 }
7190 };
7191
7192 if editor.set_wrap_width(wrap_width, cx) {
7193 editor.snapshot(window, cx)
7194 } else {
7195 snapshot
7196 }
7197 }
7198 });
7199
7200 let wrap_guides = self
7201 .editor
7202 .read(cx)
7203 .wrap_guides(cx)
7204 .iter()
7205 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
7206 .collect::<SmallVec<[_; 2]>>();
7207
7208 let hitbox = window.insert_hitbox(bounds, false);
7209 let gutter_hitbox =
7210 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
7211 let text_hitbox = window.insert_hitbox(
7212 Bounds {
7213 origin: gutter_hitbox.top_right(),
7214 size: size(text_width, bounds.size.height),
7215 },
7216 false,
7217 );
7218
7219 let content_origin = text_hitbox.origin + content_offset;
7220
7221 let editor_text_bounds =
7222 Bounds::from_corners(content_origin, bounds.bottom_right());
7223
7224 let height_in_lines = editor_text_bounds.size.height / line_height;
7225
7226 let max_row = snapshot.max_point().row().as_f32();
7227
7228 // The max scroll position for the top of the window
7229 let max_scroll_top = if matches!(
7230 snapshot.mode,
7231 EditorMode::SingleLine { .. }
7232 | EditorMode::AutoHeight { .. }
7233 | EditorMode::Full {
7234 sized_by_content: true,
7235 ..
7236 }
7237 ) {
7238 (max_row - height_in_lines + 1.).max(0.)
7239 } else {
7240 let settings = EditorSettings::get_global(cx);
7241 match settings.scroll_beyond_last_line {
7242 ScrollBeyondLastLine::OnePage => max_row,
7243 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
7244 ScrollBeyondLastLine::VerticalScrollMargin => {
7245 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
7246 .max(0.)
7247 }
7248 }
7249 };
7250
7251 // TODO: Autoscrolling for both axes
7252 let mut autoscroll_request = None;
7253 let mut autoscroll_containing_element = false;
7254 let mut autoscroll_horizontally = false;
7255 self.editor.update(cx, |editor, cx| {
7256 autoscroll_request = editor.autoscroll_request();
7257 autoscroll_containing_element =
7258 autoscroll_request.is_some() || editor.has_pending_selection();
7259 // TODO: Is this horizontal or vertical?!
7260 autoscroll_horizontally = editor.autoscroll_vertically(
7261 bounds,
7262 line_height,
7263 max_scroll_top,
7264 window,
7265 cx,
7266 );
7267 snapshot = editor.snapshot(window, cx);
7268 });
7269
7270 let mut scroll_position = snapshot.scroll_position();
7271 // The scroll position is a fractional point, the whole number of which represents
7272 // the top of the window in terms of display rows.
7273 let start_row = DisplayRow(scroll_position.y as u32);
7274 let max_row = snapshot.max_point().row();
7275 let end_row = cmp::min(
7276 (scroll_position.y + height_in_lines).ceil() as u32,
7277 max_row.next_row().0,
7278 );
7279 let end_row = DisplayRow(end_row);
7280
7281 let row_infos = snapshot
7282 .row_infos(start_row)
7283 .take((start_row..end_row).len())
7284 .collect::<Vec<RowInfo>>();
7285 let is_row_soft_wrapped = |row: usize| {
7286 row_infos
7287 .get(row)
7288 .map_or(true, |info| info.buffer_row.is_none())
7289 };
7290
7291 let start_anchor = if start_row == Default::default() {
7292 Anchor::min()
7293 } else {
7294 snapshot.buffer_snapshot.anchor_before(
7295 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
7296 )
7297 };
7298 let end_anchor = if end_row > max_row {
7299 Anchor::max()
7300 } else {
7301 snapshot.buffer_snapshot.anchor_before(
7302 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
7303 )
7304 };
7305
7306 let mut highlighted_rows = self
7307 .editor
7308 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
7309
7310 let is_light = cx.theme().appearance().is_light();
7311
7312 for (ix, row_info) in row_infos.iter().enumerate() {
7313 let Some(diff_status) = row_info.diff_status else {
7314 continue;
7315 };
7316
7317 let background_color = match diff_status.kind {
7318 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
7319 DiffHunkStatusKind::Deleted => {
7320 cx.theme().colors().version_control_deleted
7321 }
7322 DiffHunkStatusKind::Modified => {
7323 debug_panic!("modified diff status for row info");
7324 continue;
7325 }
7326 };
7327
7328 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
7329
7330 let hollow_highlight = LineHighlight {
7331 background: (background_color.opacity(if is_light {
7332 0.08
7333 } else {
7334 0.06
7335 }))
7336 .into(),
7337 border: Some(if is_light {
7338 background_color.opacity(0.48)
7339 } else {
7340 background_color.opacity(0.36)
7341 }),
7342 include_gutter: true,
7343 type_id: None,
7344 };
7345
7346 let filled_highlight = LineHighlight {
7347 background: solid_background(background_color.opacity(hunk_opacity)),
7348 border: None,
7349 include_gutter: true,
7350 type_id: None,
7351 };
7352
7353 let background = if Self::diff_hunk_hollow(diff_status, cx) {
7354 hollow_highlight
7355 } else {
7356 filled_highlight
7357 };
7358
7359 highlighted_rows
7360 .entry(start_row + DisplayRow(ix as u32))
7361 .or_insert(background);
7362 }
7363
7364 let highlighted_ranges = self
7365 .editor_with_selections(cx)
7366 .map(|editor| {
7367 editor.read(cx).background_highlights_in_range(
7368 start_anchor..end_anchor,
7369 &snapshot.display_snapshot,
7370 cx.theme().colors(),
7371 )
7372 })
7373 .unwrap_or_default();
7374 let highlighted_gutter_ranges =
7375 self.editor.read(cx).gutter_highlights_in_range(
7376 start_anchor..end_anchor,
7377 &snapshot.display_snapshot,
7378 cx,
7379 );
7380
7381 let redacted_ranges = self.editor.read(cx).redacted_ranges(
7382 start_anchor..end_anchor,
7383 &snapshot.display_snapshot,
7384 cx,
7385 );
7386
7387 let (local_selections, selected_buffer_ids): (
7388 Vec<Selection<Point>>,
7389 Vec<BufferId>,
7390 ) = self
7391 .editor_with_selections(cx)
7392 .map(|editor| {
7393 editor.update(cx, |editor, cx| {
7394 let all_selections = editor.selections.all::<Point>(cx);
7395 let selected_buffer_ids = if editor.is_singleton(cx) {
7396 Vec::new()
7397 } else {
7398 let mut selected_buffer_ids =
7399 Vec::with_capacity(all_selections.len());
7400
7401 for selection in all_selections {
7402 for buffer_id in snapshot
7403 .buffer_snapshot
7404 .buffer_ids_for_range(selection.range())
7405 {
7406 if selected_buffer_ids.last() != Some(&buffer_id) {
7407 selected_buffer_ids.push(buffer_id);
7408 }
7409 }
7410 }
7411
7412 selected_buffer_ids
7413 };
7414
7415 let mut selections = editor
7416 .selections
7417 .disjoint_in_range(start_anchor..end_anchor, cx);
7418 selections.extend(editor.selections.pending(cx));
7419
7420 (selections, selected_buffer_ids)
7421 })
7422 })
7423 .unwrap_or_default();
7424
7425 let (selections, mut active_rows, newest_selection_head) = self
7426 .layout_selections(
7427 start_anchor,
7428 end_anchor,
7429 &local_selections,
7430 &snapshot,
7431 start_row,
7432 end_row,
7433 window,
7434 cx,
7435 );
7436 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
7437 editor.active_breakpoints(start_row..end_row, window, cx)
7438 });
7439 if cx.has_flag::<DebuggerFeatureFlag>() {
7440 for display_row in breakpoint_rows.keys() {
7441 active_rows.entry(*display_row).or_default().breakpoint = true;
7442 }
7443 }
7444
7445 let line_numbers = self.layout_line_numbers(
7446 Some(&gutter_hitbox),
7447 gutter_dimensions,
7448 line_height,
7449 scroll_position,
7450 start_row..end_row,
7451 &row_infos,
7452 &active_rows,
7453 newest_selection_head,
7454 &snapshot,
7455 window,
7456 cx,
7457 );
7458
7459 // We add the gutter breakpoint indicator to breakpoint_rows after painting
7460 // line numbers so we don't paint a line number debug accent color if a user
7461 // has their mouse over that line when a breakpoint isn't there
7462 if cx.has_flag::<DebuggerFeatureFlag>() {
7463 self.editor.update(cx, |editor, _| {
7464 if let Some(phantom_breakpoint) = &mut editor
7465 .gutter_breakpoint_indicator
7466 .0
7467 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
7468 {
7469 // Is there a non-phantom breakpoint on this line?
7470 phantom_breakpoint.collides_with_existing_breakpoint = true;
7471 breakpoint_rows
7472 .entry(phantom_breakpoint.display_row)
7473 .or_insert_with(|| {
7474 let position = snapshot.display_point_to_anchor(
7475 DisplayPoint::new(phantom_breakpoint.display_row, 0),
7476 Bias::Right,
7477 );
7478 let breakpoint = Breakpoint::new_standard();
7479 phantom_breakpoint.collides_with_existing_breakpoint =
7480 false;
7481 (position, breakpoint)
7482 });
7483 }
7484 })
7485 }
7486
7487 let mut expand_toggles =
7488 window.with_element_namespace("expand_toggles", |window| {
7489 self.layout_expand_toggles(
7490 &gutter_hitbox,
7491 gutter_dimensions,
7492 em_width,
7493 line_height,
7494 scroll_position,
7495 &row_infos,
7496 window,
7497 cx,
7498 )
7499 });
7500
7501 let mut crease_toggles =
7502 window.with_element_namespace("crease_toggles", |window| {
7503 self.layout_crease_toggles(
7504 start_row..end_row,
7505 &row_infos,
7506 &active_rows,
7507 &snapshot,
7508 window,
7509 cx,
7510 )
7511 });
7512 let crease_trailers =
7513 window.with_element_namespace("crease_trailers", |window| {
7514 self.layout_crease_trailers(
7515 row_infos.iter().copied(),
7516 &snapshot,
7517 window,
7518 cx,
7519 )
7520 });
7521
7522 let display_hunks = self.layout_gutter_diff_hunks(
7523 line_height,
7524 &gutter_hitbox,
7525 start_row..end_row,
7526 &snapshot,
7527 window,
7528 cx,
7529 );
7530
7531 let mut line_layouts = Self::layout_lines(
7532 start_row..end_row,
7533 &snapshot,
7534 &self.style,
7535 editor_width,
7536 is_row_soft_wrapped,
7537 window,
7538 cx,
7539 );
7540 let new_fold_widths = line_layouts
7541 .iter()
7542 .flat_map(|layout| &layout.fragments)
7543 .filter_map(|fragment| {
7544 if let LineFragment::Element { id, size, .. } = fragment {
7545 Some((*id, size.width))
7546 } else {
7547 None
7548 }
7549 });
7550 if self.editor.update(cx, |editor, cx| {
7551 editor.update_fold_widths(new_fold_widths, cx)
7552 }) {
7553 // If the fold widths have changed, we need to prepaint
7554 // the element again to account for any changes in
7555 // wrapping.
7556 return self.prepaint(None, bounds, &mut (), window, cx);
7557 }
7558
7559 let longest_line_blame_width = self
7560 .editor
7561 .update(cx, |editor, cx| {
7562 if !editor.show_git_blame_inline {
7563 return None;
7564 }
7565 let blame = editor.blame.as_ref()?;
7566 let blame_entry = blame
7567 .update(cx, |blame, cx| {
7568 let row_infos =
7569 snapshot.row_infos(snapshot.longest_row()).next()?;
7570 blame.blame_for_rows(&[row_infos], cx).next()
7571 })
7572 .flatten()?;
7573 let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
7574 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7575 Some(
7576 element
7577 .layout_as_root(AvailableSpace::min_size(), window, cx)
7578 .width
7579 + inline_blame_padding,
7580 )
7581 })
7582 .unwrap_or(Pixels::ZERO);
7583
7584 let longest_line_width = layout_line(
7585 snapshot.longest_row(),
7586 &snapshot,
7587 &style,
7588 editor_width,
7589 is_row_soft_wrapped,
7590 window,
7591 cx,
7592 )
7593 .width;
7594
7595 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
7596 text_hitbox.bounds,
7597 glyph_grid_cell,
7598 size(longest_line_width, max_row.as_f32() * line_height),
7599 longest_line_blame_width,
7600 editor_width,
7601 EditorSettings::get_global(cx),
7602 );
7603
7604 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
7605
7606 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7607 snapshot.sticky_header_excerpt(scroll_position.y)
7608 } else {
7609 None
7610 };
7611 let sticky_header_excerpt_id =
7612 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7613
7614 let blocks = window.with_element_namespace("blocks", |window| {
7615 self.render_blocks(
7616 start_row..end_row,
7617 &snapshot,
7618 &hitbox,
7619 &text_hitbox,
7620 editor_width,
7621 &mut scroll_width,
7622 &gutter_dimensions,
7623 right_margin,
7624 em_width,
7625 gutter_dimensions.full_width(),
7626 line_height,
7627 &mut line_layouts,
7628 &local_selections,
7629 &selected_buffer_ids,
7630 is_row_soft_wrapped,
7631 sticky_header_excerpt_id,
7632 window,
7633 cx,
7634 )
7635 });
7636 let (mut blocks, row_block_types) = match blocks {
7637 Ok(blocks) => blocks,
7638 Err(resized_blocks) => {
7639 self.editor.update(cx, |editor, cx| {
7640 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7641 });
7642 return self.prepaint(None, bounds, &mut (), window, cx);
7643 }
7644 };
7645
7646 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7647 window.with_element_namespace("blocks", |window| {
7648 self.layout_sticky_buffer_header(
7649 sticky_header_excerpt,
7650 scroll_position.y,
7651 line_height,
7652 &snapshot,
7653 &hitbox,
7654 &selected_buffer_ids,
7655 &blocks,
7656 window,
7657 cx,
7658 )
7659 })
7660 });
7661
7662 let start_buffer_row =
7663 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7664 let end_buffer_row =
7665 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7666
7667 let scroll_max = point(
7668 ((scroll_width - editor_content_width) / em_width).max(0.0),
7669 max_scroll_top,
7670 );
7671
7672 self.editor.update(cx, |editor, cx| {
7673 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7674
7675 let autoscrolled = if autoscroll_horizontally {
7676 editor.autoscroll_horizontally(
7677 start_row,
7678 editor_content_width,
7679 scroll_width,
7680 em_width,
7681 &line_layouts,
7682 cx,
7683 )
7684 } else {
7685 false
7686 };
7687
7688 if clamped || autoscrolled {
7689 snapshot = editor.snapshot(window, cx);
7690 scroll_position = snapshot.scroll_position();
7691 }
7692 });
7693
7694 let scroll_pixel_position = point(
7695 scroll_position.x * em_width,
7696 scroll_position.y * line_height,
7697 );
7698
7699 let indent_guides = self.layout_indent_guides(
7700 content_origin,
7701 text_hitbox.origin,
7702 start_buffer_row..end_buffer_row,
7703 scroll_pixel_position,
7704 line_height,
7705 &snapshot,
7706 window,
7707 cx,
7708 );
7709
7710 let crease_trailers =
7711 window.with_element_namespace("crease_trailers", |window| {
7712 self.prepaint_crease_trailers(
7713 crease_trailers,
7714 &line_layouts,
7715 line_height,
7716 content_origin,
7717 scroll_pixel_position,
7718 em_width,
7719 window,
7720 cx,
7721 )
7722 });
7723
7724 let (inline_completion_popover, inline_completion_popover_origin) = self
7725 .editor
7726 .update(cx, |editor, cx| {
7727 editor.render_edit_prediction_popover(
7728 &text_hitbox.bounds,
7729 content_origin,
7730 right_margin,
7731 &snapshot,
7732 start_row..end_row,
7733 scroll_position.y,
7734 scroll_position.y + height_in_lines,
7735 &line_layouts,
7736 line_height,
7737 scroll_pixel_position,
7738 newest_selection_head,
7739 editor_width,
7740 &style,
7741 window,
7742 cx,
7743 )
7744 })
7745 .unzip();
7746
7747 let mut inline_diagnostics = self.layout_inline_diagnostics(
7748 &line_layouts,
7749 &crease_trailers,
7750 &row_block_types,
7751 content_origin,
7752 scroll_pixel_position,
7753 inline_completion_popover_origin,
7754 start_row,
7755 end_row,
7756 line_height,
7757 em_width,
7758 &style,
7759 window,
7760 cx,
7761 );
7762
7763 let mut inline_blame = None;
7764 if let Some(newest_selection_head) = newest_selection_head {
7765 let display_row = newest_selection_head.row();
7766 if (start_row..end_row).contains(&display_row)
7767 && !row_block_types.contains_key(&display_row)
7768 {
7769 let line_ix = display_row.minus(start_row) as usize;
7770 let row_info = &row_infos[line_ix];
7771 let line_layout = &line_layouts[line_ix];
7772 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7773 inline_blame = self.layout_inline_blame(
7774 display_row,
7775 row_info,
7776 line_layout,
7777 crease_trailer_layout,
7778 em_width,
7779 content_origin,
7780 scroll_pixel_position,
7781 line_height,
7782 &text_hitbox,
7783 window,
7784 cx,
7785 );
7786 if inline_blame.is_some() {
7787 // Blame overrides inline diagnostics
7788 inline_diagnostics.remove(&display_row);
7789 }
7790 }
7791 }
7792
7793 let blamed_display_rows = self.layout_blame_entries(
7794 &row_infos,
7795 em_width,
7796 scroll_position,
7797 line_height,
7798 &gutter_hitbox,
7799 gutter_dimensions.git_blame_entries_width,
7800 window,
7801 cx,
7802 );
7803
7804 self.editor.update(cx, |editor, cx| {
7805 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7806
7807 let autoscrolled = if autoscroll_horizontally {
7808 editor.autoscroll_horizontally(
7809 start_row,
7810 editor_content_width,
7811 scroll_width,
7812 em_width,
7813 &line_layouts,
7814 cx,
7815 )
7816 } else {
7817 false
7818 };
7819
7820 if clamped || autoscrolled {
7821 snapshot = editor.snapshot(window, cx);
7822 scroll_position = snapshot.scroll_position();
7823 }
7824 });
7825
7826 let line_elements = self.prepaint_lines(
7827 start_row,
7828 &mut line_layouts,
7829 line_height,
7830 scroll_pixel_position,
7831 content_origin,
7832 window,
7833 cx,
7834 );
7835
7836 window.with_element_namespace("blocks", |window| {
7837 self.layout_blocks(
7838 &mut blocks,
7839 &hitbox,
7840 line_height,
7841 scroll_pixel_position,
7842 window,
7843 cx,
7844 );
7845 });
7846
7847 let cursors = self.collect_cursors(&snapshot, cx);
7848 let visible_row_range = start_row..end_row;
7849 let non_visible_cursors = cursors
7850 .iter()
7851 .any(|c| !visible_row_range.contains(&c.0.row()));
7852
7853 let visible_cursors = self.layout_visible_cursors(
7854 &snapshot,
7855 &selections,
7856 &row_block_types,
7857 start_row..end_row,
7858 &line_layouts,
7859 &text_hitbox,
7860 content_origin,
7861 scroll_position,
7862 scroll_pixel_position,
7863 line_height,
7864 em_width,
7865 em_advance,
7866 autoscroll_containing_element,
7867 window,
7868 cx,
7869 );
7870
7871 let scrollbars_layout = self.layout_scrollbars(
7872 &snapshot,
7873 &scrollbar_layout_information,
7874 content_offset,
7875 scroll_position,
7876 non_visible_cursors,
7877 right_margin,
7878 editor_width,
7879 window,
7880 cx,
7881 );
7882
7883 let gutter_settings = EditorSettings::get_global(cx).gutter;
7884
7885 if let Some(newest_selection_head) = newest_selection_head {
7886 let newest_selection_point =
7887 newest_selection_head.to_point(&snapshot.display_snapshot);
7888
7889 if (start_row..end_row).contains(&newest_selection_head.row()) {
7890 self.layout_cursor_popovers(
7891 line_height,
7892 &text_hitbox,
7893 content_origin,
7894 right_margin,
7895 start_row,
7896 scroll_pixel_position,
7897 &line_layouts,
7898 newest_selection_head,
7899 newest_selection_point,
7900 &style,
7901 window,
7902 cx,
7903 );
7904 }
7905 }
7906
7907 self.layout_gutter_menu(
7908 line_height,
7909 &text_hitbox,
7910 content_origin,
7911 right_margin,
7912 scroll_pixel_position,
7913 gutter_dimensions.width - gutter_dimensions.left_padding,
7914 window,
7915 cx,
7916 );
7917
7918 let test_indicators = if gutter_settings.runnables {
7919 self.layout_run_indicators(
7920 line_height,
7921 start_row..end_row,
7922 &row_infos,
7923 scroll_pixel_position,
7924 &gutter_dimensions,
7925 &gutter_hitbox,
7926 &display_hunks,
7927 &snapshot,
7928 &mut breakpoint_rows,
7929 window,
7930 cx,
7931 )
7932 } else {
7933 Vec::new()
7934 };
7935
7936 let show_breakpoints = snapshot
7937 .show_breakpoints
7938 .unwrap_or(gutter_settings.breakpoints);
7939 let breakpoints = if cx.has_flag::<DebuggerFeatureFlag>() && show_breakpoints {
7940 self.layout_breakpoints(
7941 line_height,
7942 start_row..end_row,
7943 scroll_pixel_position,
7944 &gutter_dimensions,
7945 &gutter_hitbox,
7946 &display_hunks,
7947 &snapshot,
7948 breakpoint_rows,
7949 &row_infos,
7950 window,
7951 cx,
7952 )
7953 } else {
7954 vec![]
7955 };
7956
7957 self.layout_signature_help(
7958 &hitbox,
7959 &text_hitbox,
7960 content_origin,
7961 scroll_pixel_position,
7962 newest_selection_head,
7963 start_row,
7964 &line_layouts,
7965 line_height,
7966 em_width,
7967 window,
7968 cx,
7969 );
7970
7971 if !cx.has_active_drag() {
7972 self.layout_hover_popovers(
7973 &snapshot,
7974 &hitbox,
7975 &text_hitbox,
7976 start_row..end_row,
7977 content_origin,
7978 scroll_pixel_position,
7979 &line_layouts,
7980 line_height,
7981 em_width,
7982 window,
7983 cx,
7984 );
7985 }
7986
7987 let mouse_context_menu = self.layout_mouse_context_menu(
7988 &snapshot,
7989 start_row..end_row,
7990 content_origin,
7991 window,
7992 cx,
7993 );
7994
7995 window.with_element_namespace("crease_toggles", |window| {
7996 self.prepaint_crease_toggles(
7997 &mut crease_toggles,
7998 line_height,
7999 &gutter_dimensions,
8000 gutter_settings,
8001 scroll_pixel_position,
8002 &gutter_hitbox,
8003 window,
8004 cx,
8005 )
8006 });
8007
8008 window.with_element_namespace("expand_toggles", |window| {
8009 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
8010 });
8011
8012 let minimap = window.with_element_namespace("minimap", |window| {
8013 self.layout_minimap(
8014 &snapshot,
8015 minimap_width,
8016 scroll_position,
8017 &scrollbar_layout_information,
8018 scrollbars_layout.as_ref(),
8019 window,
8020 cx,
8021 )
8022 });
8023
8024 let invisible_symbol_font_size = font_size / 2.;
8025 let tab_invisible = window
8026 .text_system()
8027 .shape_line(
8028 "→".into(),
8029 invisible_symbol_font_size,
8030 &[TextRun {
8031 len: "→".len(),
8032 font: self.style.text.font(),
8033 color: cx.theme().colors().editor_invisible,
8034 background_color: None,
8035 underline: None,
8036 strikethrough: None,
8037 }],
8038 )
8039 .unwrap();
8040 let space_invisible = window
8041 .text_system()
8042 .shape_line(
8043 "•".into(),
8044 invisible_symbol_font_size,
8045 &[TextRun {
8046 len: "•".len(),
8047 font: self.style.text.font(),
8048 color: cx.theme().colors().editor_invisible,
8049 background_color: None,
8050 underline: None,
8051 strikethrough: None,
8052 }],
8053 )
8054 .unwrap();
8055
8056 let mode = snapshot.mode.clone();
8057
8058 let position_map = Rc::new(PositionMap {
8059 size: bounds.size,
8060 visible_row_range,
8061 scroll_pixel_position,
8062 scroll_max,
8063 line_layouts,
8064 line_height,
8065 em_width,
8066 em_advance,
8067 snapshot,
8068 gutter_hitbox: gutter_hitbox.clone(),
8069 text_hitbox: text_hitbox.clone(),
8070 });
8071
8072 self.editor.update(cx, |editor, _| {
8073 editor.last_position_map = Some(position_map.clone())
8074 });
8075
8076 let diff_hunk_controls = if is_read_only {
8077 vec![]
8078 } else {
8079 self.layout_diff_hunk_controls(
8080 start_row..end_row,
8081 &row_infos,
8082 &text_hitbox,
8083 &position_map,
8084 newest_selection_head,
8085 line_height,
8086 right_margin,
8087 scroll_pixel_position,
8088 &display_hunks,
8089 &highlighted_rows,
8090 self.editor.clone(),
8091 window,
8092 cx,
8093 )
8094 };
8095
8096 EditorLayout {
8097 mode,
8098 position_map,
8099 visible_display_row_range: start_row..end_row,
8100 wrap_guides,
8101 indent_guides,
8102 hitbox,
8103 gutter_hitbox,
8104 display_hunks,
8105 content_origin,
8106 scrollbars_layout,
8107 minimap,
8108 active_rows,
8109 highlighted_rows,
8110 highlighted_ranges,
8111 highlighted_gutter_ranges,
8112 redacted_ranges,
8113 line_elements,
8114 line_numbers,
8115 blamed_display_rows,
8116 inline_diagnostics,
8117 inline_blame,
8118 blocks,
8119 cursors,
8120 visible_cursors,
8121 selections,
8122 inline_completion_popover,
8123 diff_hunk_controls,
8124 mouse_context_menu,
8125 test_indicators,
8126 breakpoints,
8127 crease_toggles,
8128 crease_trailers,
8129 tab_invisible,
8130 space_invisible,
8131 sticky_buffer_header,
8132 expand_toggles,
8133 }
8134 })
8135 })
8136 })
8137 }
8138
8139 fn paint(
8140 &mut self,
8141 _: Option<&GlobalElementId>,
8142 bounds: Bounds<gpui::Pixels>,
8143 _: &mut Self::RequestLayoutState,
8144 layout: &mut Self::PrepaintState,
8145 window: &mut Window,
8146 cx: &mut App,
8147 ) {
8148 let focus_handle = self.editor.focus_handle(cx);
8149 let key_context = self
8150 .editor
8151 .update(cx, |editor, cx| editor.key_context(window, cx));
8152
8153 window.set_key_context(key_context);
8154 window.handle_input(
8155 &focus_handle,
8156 ElementInputHandler::new(bounds, self.editor.clone()),
8157 cx,
8158 );
8159 self.register_actions(window, cx);
8160 self.register_key_listeners(window, cx, layout);
8161
8162 let text_style = TextStyleRefinement {
8163 font_size: Some(self.style.text.font_size),
8164 line_height: Some(self.style.text.line_height),
8165 ..Default::default()
8166 };
8167 let rem_size = self.rem_size(cx);
8168 window.with_rem_size(rem_size, |window| {
8169 window.with_text_style(Some(text_style), |window| {
8170 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8171 self.paint_mouse_listeners(layout, window, cx);
8172 self.paint_background(layout, window, cx);
8173 self.paint_indent_guides(layout, window, cx);
8174
8175 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8176 self.paint_blamed_display_rows(layout, window, cx);
8177 self.paint_line_numbers(layout, window, cx);
8178 }
8179
8180 self.paint_text(layout, window, cx);
8181
8182 if layout.gutter_hitbox.size.width > Pixels::ZERO {
8183 self.paint_gutter_highlights(layout, window, cx);
8184 self.paint_gutter_indicators(layout, window, cx);
8185 }
8186
8187 if !layout.blocks.is_empty() {
8188 window.with_element_namespace("blocks", |window| {
8189 self.paint_blocks(layout, window, cx);
8190 });
8191 }
8192
8193 window.with_element_namespace("blocks", |window| {
8194 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
8195 sticky_header.paint(window, cx)
8196 }
8197 });
8198
8199 self.paint_minimap(layout, window, cx);
8200 self.paint_scrollbars(layout, window, cx);
8201 self.paint_inline_completion_popover(layout, window, cx);
8202 self.paint_mouse_context_menu(layout, window, cx);
8203 });
8204 })
8205 })
8206 }
8207}
8208
8209pub(super) fn gutter_bounds(
8210 editor_bounds: Bounds<Pixels>,
8211 gutter_dimensions: GutterDimensions,
8212) -> Bounds<Pixels> {
8213 Bounds {
8214 origin: editor_bounds.origin,
8215 size: size(gutter_dimensions.width, editor_bounds.size.height),
8216 }
8217}
8218
8219/// Holds information required for layouting the editor scrollbars.
8220struct ScrollbarLayoutInformation {
8221 /// The bounds of the editor area (excluding the content offset).
8222 editor_bounds: Bounds<Pixels>,
8223 /// The available range to scroll within the document.
8224 scroll_range: Size<Pixels>,
8225 /// The space available for one glyph in the editor.
8226 glyph_grid_cell: Size<Pixels>,
8227}
8228
8229impl ScrollbarLayoutInformation {
8230 pub fn new(
8231 editor_bounds: Bounds<Pixels>,
8232 glyph_grid_cell: Size<Pixels>,
8233 document_size: Size<Pixels>,
8234 longest_line_blame_width: Pixels,
8235 editor_width: Pixels,
8236 settings: &EditorSettings,
8237 ) -> Self {
8238 let vertical_overscroll = match settings.scroll_beyond_last_line {
8239 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
8240 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
8241 ScrollBeyondLastLine::VerticalScrollMargin => {
8242 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
8243 }
8244 };
8245
8246 let right_margin = if document_size.width + longest_line_blame_width >= editor_width {
8247 glyph_grid_cell.width
8248 } else {
8249 px(0.0)
8250 };
8251
8252 let overscroll = size(right_margin + longest_line_blame_width, vertical_overscroll);
8253
8254 let scroll_range = document_size + overscroll;
8255
8256 ScrollbarLayoutInformation {
8257 editor_bounds,
8258 scroll_range,
8259 glyph_grid_cell,
8260 }
8261 }
8262}
8263
8264impl IntoElement for EditorElement {
8265 type Element = Self;
8266
8267 fn into_element(self) -> Self::Element {
8268 self
8269 }
8270}
8271
8272pub struct EditorLayout {
8273 position_map: Rc<PositionMap>,
8274 hitbox: Hitbox,
8275 gutter_hitbox: Hitbox,
8276 content_origin: gpui::Point<Pixels>,
8277 scrollbars_layout: Option<EditorScrollbars>,
8278 minimap: Option<MinimapLayout>,
8279 mode: EditorMode,
8280 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
8281 indent_guides: Option<Vec<IndentGuideLayout>>,
8282 visible_display_row_range: Range<DisplayRow>,
8283 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
8284 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
8285 line_elements: SmallVec<[AnyElement; 1]>,
8286 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
8287 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
8288 blamed_display_rows: Option<Vec<AnyElement>>,
8289 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
8290 inline_blame: Option<AnyElement>,
8291 blocks: Vec<BlockLayout>,
8292 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
8293 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
8294 redacted_ranges: Vec<Range<DisplayPoint>>,
8295 cursors: Vec<(DisplayPoint, Hsla)>,
8296 visible_cursors: Vec<CursorLayout>,
8297 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
8298 test_indicators: Vec<AnyElement>,
8299 breakpoints: Vec<AnyElement>,
8300 crease_toggles: Vec<Option<AnyElement>>,
8301 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
8302 diff_hunk_controls: Vec<AnyElement>,
8303 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
8304 inline_completion_popover: Option<AnyElement>,
8305 mouse_context_menu: Option<AnyElement>,
8306 tab_invisible: ShapedLine,
8307 space_invisible: ShapedLine,
8308 sticky_buffer_header: Option<AnyElement>,
8309}
8310
8311impl EditorLayout {
8312 fn line_end_overshoot(&self) -> Pixels {
8313 0.15 * self.position_map.line_height
8314 }
8315}
8316
8317struct LineNumberLayout {
8318 shaped_line: ShapedLine,
8319 hitbox: Option<Hitbox>,
8320}
8321
8322struct ColoredRange<T> {
8323 start: T,
8324 end: T,
8325 color: Hsla,
8326}
8327
8328impl Along for ScrollbarAxes {
8329 type Unit = bool;
8330
8331 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
8332 match axis {
8333 ScrollbarAxis::Horizontal => self.horizontal,
8334 ScrollbarAxis::Vertical => self.vertical,
8335 }
8336 }
8337
8338 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
8339 match axis {
8340 ScrollbarAxis::Horizontal => ScrollbarAxes {
8341 horizontal: f(self.horizontal),
8342 vertical: self.vertical,
8343 },
8344 ScrollbarAxis::Vertical => ScrollbarAxes {
8345 horizontal: self.horizontal,
8346 vertical: f(self.vertical),
8347 },
8348 }
8349 }
8350}
8351
8352#[derive(Clone)]
8353struct EditorScrollbars {
8354 pub vertical: Option<ScrollbarLayout>,
8355 pub horizontal: Option<ScrollbarLayout>,
8356 pub visible: bool,
8357}
8358
8359impl EditorScrollbars {
8360 pub fn from_scrollbar_axes(
8361 settings_visibility: ScrollbarAxes,
8362 layout_information: &ScrollbarLayoutInformation,
8363 content_offset: gpui::Point<Pixels>,
8364 scroll_position: gpui::Point<f32>,
8365 scrollbar_width: Pixels,
8366 right_margin: Pixels,
8367 editor_width: Pixels,
8368 show_scrollbars: bool,
8369 scrollbar_state: Option<&ActiveScrollbarState>,
8370 window: &mut Window,
8371 ) -> Self {
8372 let ScrollbarLayoutInformation {
8373 editor_bounds,
8374 scroll_range,
8375 glyph_grid_cell,
8376 } = layout_information;
8377
8378 let viewport_size = size(editor_width, editor_bounds.size.height);
8379
8380 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
8381 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
8382 Corner::BottomLeft,
8383 editor_bounds.bottom_left(),
8384 size(
8385 // The horizontal viewport size differs from the space available for the
8386 // horizontal scrollbar, so we have to manually stich it together here.
8387 editor_bounds.size.width - right_margin,
8388 scrollbar_width,
8389 ),
8390 ),
8391 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
8392 Corner::TopRight,
8393 editor_bounds.top_right(),
8394 size(scrollbar_width, viewport_size.height),
8395 ),
8396 };
8397
8398 let mut create_scrollbar_layout = |axis| {
8399 settings_visibility
8400 .along(axis)
8401 .then(|| {
8402 (
8403 viewport_size.along(axis) - content_offset.along(axis),
8404 scroll_range.along(axis),
8405 )
8406 })
8407 .filter(|(viewport_size, scroll_range)| {
8408 // The scrollbar should only be rendered if the content does
8409 // not entirely fit into the editor
8410 // However, this only applies to the horizontal scrollbar, as information about the
8411 // vertical scrollbar layout is always needed for scrollbar diagnostics.
8412 axis != ScrollbarAxis::Horizontal || viewport_size < scroll_range
8413 })
8414 .map(|(viewport_size, scroll_range)| {
8415 let thumb_state = scrollbar_state
8416 .and_then(|state| state.thumb_state_for_axis(axis))
8417 .unwrap_or(ScrollbarThumbState::Idle);
8418
8419 ScrollbarLayout::new(
8420 window.insert_hitbox(scrollbar_bounds_for(axis), false),
8421 viewport_size,
8422 scroll_range,
8423 glyph_grid_cell.along(axis),
8424 content_offset.along(axis),
8425 scroll_position.along(axis),
8426 thumb_state,
8427 axis,
8428 )
8429 })
8430 };
8431
8432 Self {
8433 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
8434 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
8435 visible: show_scrollbars,
8436 }
8437 }
8438
8439 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
8440 [
8441 (&self.vertical, ScrollbarAxis::Vertical),
8442 (&self.horizontal, ScrollbarAxis::Horizontal),
8443 ]
8444 .into_iter()
8445 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
8446 }
8447
8448 /// Returns the currently hovered scrollbar axis, if any.
8449 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
8450 self.iter_scrollbars()
8451 .find(|s| s.0.hitbox.is_hovered(window))
8452 }
8453}
8454
8455#[derive(Clone)]
8456struct ScrollbarLayout {
8457 hitbox: Hitbox,
8458 visible_range: Range<f32>,
8459 text_unit_size: Pixels,
8460 content_offset: Pixels,
8461 thumb_size: Pixels,
8462 thumb_state: ScrollbarThumbState,
8463 axis: ScrollbarAxis,
8464}
8465
8466impl ScrollbarLayout {
8467 const BORDER_WIDTH: Pixels = px(1.0);
8468 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
8469 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
8470 const MIN_THUMB_SIZE: Pixels = px(25.0);
8471
8472 fn new(
8473 scrollbar_track_hitbox: Hitbox,
8474 viewport_size: Pixels,
8475 scroll_range: Pixels,
8476 glyph_space: Pixels,
8477 content_offset: Pixels,
8478 scroll_position: f32,
8479 thumb_state: ScrollbarThumbState,
8480 axis: ScrollbarAxis,
8481 ) -> Self {
8482 let track_bounds = scrollbar_track_hitbox.bounds;
8483 // The length of the track available to the scrollbar thumb. We deliberately
8484 // exclude the content size here so that the thumb aligns with the content.
8485 let track_length = track_bounds.size.along(axis) - content_offset;
8486
8487 Self::new_with_hitbox_and_track_length(
8488 scrollbar_track_hitbox,
8489 track_length,
8490 viewport_size,
8491 scroll_range,
8492 glyph_space,
8493 content_offset,
8494 scroll_position,
8495 thumb_state,
8496 axis,
8497 )
8498 }
8499
8500 fn for_minimap(
8501 minimap_track_hitbox: Hitbox,
8502 visible_lines: f32,
8503 total_editor_lines: f32,
8504 minimap_line_height: Pixels,
8505 scroll_position: f32,
8506 minimap_scroll_top: f32,
8507 ) -> Self {
8508 // The scrollbar thumb size is calculated as
8509 // (visible_content/total_content) × scrollbar_track_length.
8510 //
8511 // For the minimap's thumb layout, we leverage this by setting the
8512 // scrollbar track length to the entire document size (using minimap line
8513 // height). This creates a thumb that exactly represents the editor
8514 // viewport scaled to minimap proportions.
8515 //
8516 // We adjust the thumb position relative to `minimap_scroll_top` to
8517 // accommodate for the deliberately oversized track.
8518 //
8519 // This approach ensures that the minimap thumb accurately reflects the
8520 // editor's current scroll position whilst nicely synchronizing the minimap
8521 // thumb and scrollbar thumb.
8522 let scroll_range = total_editor_lines * minimap_line_height;
8523 let viewport_size = visible_lines * minimap_line_height;
8524
8525 let track_top_offset = -minimap_scroll_top * minimap_line_height;
8526
8527 Self::new_with_hitbox_and_track_length(
8528 minimap_track_hitbox,
8529 scroll_range,
8530 viewport_size,
8531 scroll_range,
8532 minimap_line_height,
8533 track_top_offset,
8534 scroll_position,
8535 ScrollbarThumbState::Idle,
8536 ScrollbarAxis::Vertical,
8537 )
8538 }
8539
8540 fn new_with_hitbox_and_track_length(
8541 scrollbar_track_hitbox: Hitbox,
8542 track_length: Pixels,
8543 viewport_size: Pixels,
8544 scroll_range: Pixels,
8545 glyph_space: Pixels,
8546 content_offset: Pixels,
8547 scroll_position: f32,
8548 thumb_state: ScrollbarThumbState,
8549 axis: ScrollbarAxis,
8550 ) -> Self {
8551 let text_units_per_page = viewport_size / glyph_space;
8552 let visible_range = scroll_position..scroll_position + text_units_per_page;
8553 let total_text_units = scroll_range / glyph_space;
8554
8555 let thumb_percentage = text_units_per_page / total_text_units;
8556 let thumb_size = (track_length * thumb_percentage)
8557 .max(ScrollbarLayout::MIN_THUMB_SIZE)
8558 .min(track_length);
8559 let text_unit_size =
8560 (track_length - thumb_size) / (total_text_units - text_units_per_page).max(0.);
8561
8562 ScrollbarLayout {
8563 hitbox: scrollbar_track_hitbox,
8564 visible_range,
8565 text_unit_size,
8566 content_offset,
8567 thumb_size,
8568 thumb_state,
8569 axis,
8570 }
8571 }
8572
8573 fn thumb_bounds(&self) -> Bounds<Pixels> {
8574 let scrollbar_track = &self.hitbox.bounds;
8575 Bounds::new(
8576 scrollbar_track
8577 .origin
8578 .apply_along(self.axis, |origin| self.thumb_origin(origin)),
8579 scrollbar_track
8580 .size
8581 .apply_along(self.axis, |_| self.thumb_size),
8582 )
8583 }
8584
8585 fn thumb_origin(&self, origin: Pixels) -> Pixels {
8586 origin + self.content_offset + self.visible_range.start * self.text_unit_size
8587 }
8588
8589 fn marker_quads_for_ranges(
8590 &self,
8591 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
8592 column: Option<usize>,
8593 ) -> Vec<PaintQuad> {
8594 struct MinMax {
8595 min: Pixels,
8596 max: Pixels,
8597 }
8598 let (x_range, height_limit) = if let Some(column) = column {
8599 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
8600 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
8601 let end = start + column_width;
8602 (
8603 Range { start, end },
8604 MinMax {
8605 min: Self::MIN_MARKER_HEIGHT,
8606 max: px(f32::MAX),
8607 },
8608 )
8609 } else {
8610 (
8611 Range {
8612 start: Self::BORDER_WIDTH,
8613 end: self.hitbox.size.width,
8614 },
8615 MinMax {
8616 min: Self::LINE_MARKER_HEIGHT,
8617 max: Self::LINE_MARKER_HEIGHT,
8618 },
8619 )
8620 };
8621
8622 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
8623 let mut pixel_ranges = row_ranges
8624 .into_iter()
8625 .map(|range| {
8626 let start_y = row_to_y(range.start);
8627 let end_y = row_to_y(range.end)
8628 + self
8629 .text_unit_size
8630 .max(height_limit.min)
8631 .min(height_limit.max);
8632 ColoredRange {
8633 start: start_y,
8634 end: end_y,
8635 color: range.color,
8636 }
8637 })
8638 .peekable();
8639
8640 let mut quads = Vec::new();
8641 while let Some(mut pixel_range) = pixel_ranges.next() {
8642 while let Some(next_pixel_range) = pixel_ranges.peek() {
8643 if pixel_range.end >= next_pixel_range.start - px(1.0)
8644 && pixel_range.color == next_pixel_range.color
8645 {
8646 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
8647 pixel_ranges.next();
8648 } else {
8649 break;
8650 }
8651 }
8652
8653 let bounds = Bounds::from_corners(
8654 point(x_range.start, pixel_range.start),
8655 point(x_range.end, pixel_range.end),
8656 );
8657 quads.push(quad(
8658 bounds,
8659 Corners::default(),
8660 pixel_range.color,
8661 Edges::default(),
8662 Hsla::transparent_black(),
8663 BorderStyle::default(),
8664 ));
8665 }
8666
8667 quads
8668 }
8669}
8670
8671struct MinimapLayout {
8672 pub minimap: AnyElement,
8673 pub thumb_layout: ScrollbarLayout,
8674 pub minimap_scroll_top: f32,
8675 pub minimap_line_height: Pixels,
8676 pub thumb_border_style: MinimapThumbBorder,
8677 pub show_thumb: bool,
8678 pub max_scroll_top: f32,
8679}
8680
8681impl MinimapLayout {
8682 const MINIMAP_WIDTH: Pixels = px(100.);
8683 /// Calculates the scroll top offset the minimap editor has to have based on the
8684 /// current scroll progress.
8685 fn calculate_minimap_top_offset(
8686 document_lines: f32,
8687 visible_editor_lines: f32,
8688 visible_minimap_lines: f32,
8689 scroll_position: f32,
8690 ) -> f32 {
8691 let scroll_percentage =
8692 (scroll_position / (document_lines - visible_editor_lines)).clamp(0., 1.);
8693 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
8694 }
8695}
8696
8697struct CreaseTrailerLayout {
8698 element: AnyElement,
8699 bounds: Bounds<Pixels>,
8700}
8701
8702pub(crate) struct PositionMap {
8703 pub size: Size<Pixels>,
8704 pub line_height: Pixels,
8705 pub scroll_pixel_position: gpui::Point<Pixels>,
8706 pub scroll_max: gpui::Point<f32>,
8707 pub em_width: Pixels,
8708 pub em_advance: Pixels,
8709 pub visible_row_range: Range<DisplayRow>,
8710 pub line_layouts: Vec<LineWithInvisibles>,
8711 pub snapshot: EditorSnapshot,
8712 pub text_hitbox: Hitbox,
8713 pub gutter_hitbox: Hitbox,
8714}
8715
8716#[derive(Debug, Copy, Clone)]
8717pub struct PointForPosition {
8718 pub previous_valid: DisplayPoint,
8719 pub next_valid: DisplayPoint,
8720 pub exact_unclipped: DisplayPoint,
8721 pub column_overshoot_after_line_end: u32,
8722}
8723
8724impl PointForPosition {
8725 pub fn as_valid(&self) -> Option<DisplayPoint> {
8726 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
8727 Some(self.previous_valid)
8728 } else {
8729 None
8730 }
8731 }
8732}
8733
8734impl PositionMap {
8735 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
8736 let text_bounds = self.text_hitbox.bounds;
8737 let scroll_position = self.snapshot.scroll_position();
8738 let position = position - text_bounds.origin;
8739 let y = position.y.max(px(0.)).min(self.size.height);
8740 let x = position.x + (scroll_position.x * self.em_width);
8741 let row = ((y / self.line_height) + scroll_position.y) as u32;
8742
8743 let (column, x_overshoot_after_line_end) = if let Some(line) = self
8744 .line_layouts
8745 .get(row as usize - scroll_position.y as usize)
8746 {
8747 if let Some(ix) = line.index_for_x(x) {
8748 (ix as u32, px(0.))
8749 } else {
8750 (line.len as u32, px(0.).max(x - line.width))
8751 }
8752 } else {
8753 (0, x)
8754 };
8755
8756 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
8757 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
8758 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
8759
8760 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
8761 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
8762 PointForPosition {
8763 previous_valid,
8764 next_valid,
8765 exact_unclipped,
8766 column_overshoot_after_line_end,
8767 }
8768 }
8769}
8770
8771struct BlockLayout {
8772 id: BlockId,
8773 x_offset: Pixels,
8774 row: Option<DisplayRow>,
8775 element: AnyElement,
8776 available_space: Size<AvailableSpace>,
8777 style: BlockStyle,
8778 overlaps_gutter: bool,
8779 is_buffer_header: bool,
8780}
8781
8782pub fn layout_line(
8783 row: DisplayRow,
8784 snapshot: &EditorSnapshot,
8785 style: &EditorStyle,
8786 text_width: Pixels,
8787 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
8788 window: &mut Window,
8789 cx: &mut App,
8790) -> LineWithInvisibles {
8791 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8792 LineWithInvisibles::from_chunks(
8793 chunks,
8794 &style,
8795 MAX_LINE_LEN,
8796 1,
8797 &snapshot.mode,
8798 text_width,
8799 is_row_soft_wrapped,
8800 window,
8801 cx,
8802 )
8803 .pop()
8804 .unwrap()
8805}
8806
8807#[derive(Debug)]
8808pub struct IndentGuideLayout {
8809 origin: gpui::Point<Pixels>,
8810 length: Pixels,
8811 single_indent_width: Pixels,
8812 depth: u32,
8813 active: bool,
8814 settings: IndentGuideSettings,
8815}
8816
8817pub struct CursorLayout {
8818 origin: gpui::Point<Pixels>,
8819 block_width: Pixels,
8820 line_height: Pixels,
8821 color: Hsla,
8822 shape: CursorShape,
8823 block_text: Option<ShapedLine>,
8824 cursor_name: Option<AnyElement>,
8825}
8826
8827#[derive(Debug)]
8828pub struct CursorName {
8829 string: SharedString,
8830 color: Hsla,
8831 is_top_row: bool,
8832}
8833
8834impl CursorLayout {
8835 pub fn new(
8836 origin: gpui::Point<Pixels>,
8837 block_width: Pixels,
8838 line_height: Pixels,
8839 color: Hsla,
8840 shape: CursorShape,
8841 block_text: Option<ShapedLine>,
8842 ) -> CursorLayout {
8843 CursorLayout {
8844 origin,
8845 block_width,
8846 line_height,
8847 color,
8848 shape,
8849 block_text,
8850 cursor_name: None,
8851 }
8852 }
8853
8854 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8855 Bounds {
8856 origin: self.origin + origin,
8857 size: size(self.block_width, self.line_height),
8858 }
8859 }
8860
8861 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8862 match self.shape {
8863 CursorShape::Bar => Bounds {
8864 origin: self.origin + origin,
8865 size: size(px(2.0), self.line_height),
8866 },
8867 CursorShape::Block | CursorShape::Hollow => Bounds {
8868 origin: self.origin + origin,
8869 size: size(self.block_width, self.line_height),
8870 },
8871 CursorShape::Underline => Bounds {
8872 origin: self.origin
8873 + origin
8874 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8875 size: size(self.block_width, px(2.0)),
8876 },
8877 }
8878 }
8879
8880 pub fn layout(
8881 &mut self,
8882 origin: gpui::Point<Pixels>,
8883 cursor_name: Option<CursorName>,
8884 window: &mut Window,
8885 cx: &mut App,
8886 ) {
8887 if let Some(cursor_name) = cursor_name {
8888 let bounds = self.bounds(origin);
8889 let text_size = self.line_height / 1.5;
8890
8891 let name_origin = if cursor_name.is_top_row {
8892 point(bounds.right() - px(1.), bounds.top())
8893 } else {
8894 match self.shape {
8895 CursorShape::Bar => point(
8896 bounds.right() - px(2.),
8897 bounds.top() - text_size / 2. - px(1.),
8898 ),
8899 _ => point(
8900 bounds.right() - px(1.),
8901 bounds.top() - text_size / 2. - px(1.),
8902 ),
8903 }
8904 };
8905 let mut name_element = div()
8906 .bg(self.color)
8907 .text_size(text_size)
8908 .px_0p5()
8909 .line_height(text_size + px(2.))
8910 .text_color(cursor_name.color)
8911 .child(cursor_name.string.clone())
8912 .into_any_element();
8913
8914 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8915
8916 self.cursor_name = Some(name_element);
8917 }
8918 }
8919
8920 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8921 let bounds = self.bounds(origin);
8922
8923 //Draw background or border quad
8924 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8925 outline(bounds, self.color, BorderStyle::Solid)
8926 } else {
8927 fill(bounds, self.color)
8928 };
8929
8930 if let Some(name) = &mut self.cursor_name {
8931 name.paint(window, cx);
8932 }
8933
8934 window.paint_quad(cursor);
8935
8936 if let Some(block_text) = &self.block_text {
8937 block_text
8938 .paint(self.origin + origin, self.line_height, window, cx)
8939 .log_err();
8940 }
8941 }
8942
8943 pub fn shape(&self) -> CursorShape {
8944 self.shape
8945 }
8946}
8947
8948#[derive(Debug)]
8949pub struct HighlightedRange {
8950 pub start_y: Pixels,
8951 pub line_height: Pixels,
8952 pub lines: Vec<HighlightedRangeLine>,
8953 pub color: Hsla,
8954 pub corner_radius: Pixels,
8955}
8956
8957#[derive(Debug)]
8958pub struct HighlightedRangeLine {
8959 pub start_x: Pixels,
8960 pub end_x: Pixels,
8961}
8962
8963impl HighlightedRange {
8964 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8965 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8966 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8967 self.paint_lines(
8968 self.start_y + self.line_height,
8969 &self.lines[1..],
8970 bounds,
8971 window,
8972 );
8973 } else {
8974 self.paint_lines(self.start_y, &self.lines, bounds, window);
8975 }
8976 }
8977
8978 fn paint_lines(
8979 &self,
8980 start_y: Pixels,
8981 lines: &[HighlightedRangeLine],
8982 _bounds: Bounds<Pixels>,
8983 window: &mut Window,
8984 ) {
8985 if lines.is_empty() {
8986 return;
8987 }
8988
8989 let first_line = lines.first().unwrap();
8990 let last_line = lines.last().unwrap();
8991
8992 let first_top_left = point(first_line.start_x, start_y);
8993 let first_top_right = point(first_line.end_x, start_y);
8994
8995 let curve_height = point(Pixels::ZERO, self.corner_radius);
8996 let curve_width = |start_x: Pixels, end_x: Pixels| {
8997 let max = (end_x - start_x) / 2.;
8998 let width = if max < self.corner_radius {
8999 max
9000 } else {
9001 self.corner_radius
9002 };
9003
9004 point(width, Pixels::ZERO)
9005 };
9006
9007 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
9008 let mut builder = gpui::PathBuilder::fill();
9009 builder.move_to(first_top_right - top_curve_width);
9010 builder.curve_to(first_top_right + curve_height, first_top_right);
9011
9012 let mut iter = lines.iter().enumerate().peekable();
9013 while let Some((ix, line)) = iter.next() {
9014 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
9015
9016 if let Some((_, next_line)) = iter.peek() {
9017 let next_top_right = point(next_line.end_x, bottom_right.y);
9018
9019 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
9020 Ordering::Equal => {
9021 builder.line_to(bottom_right);
9022 }
9023 Ordering::Less => {
9024 let curve_width = curve_width(next_top_right.x, bottom_right.x);
9025 builder.line_to(bottom_right - curve_height);
9026 if self.corner_radius > Pixels::ZERO {
9027 builder.curve_to(bottom_right - curve_width, bottom_right);
9028 }
9029 builder.line_to(next_top_right + curve_width);
9030 if self.corner_radius > Pixels::ZERO {
9031 builder.curve_to(next_top_right + curve_height, next_top_right);
9032 }
9033 }
9034 Ordering::Greater => {
9035 let curve_width = curve_width(bottom_right.x, next_top_right.x);
9036 builder.line_to(bottom_right - curve_height);
9037 if self.corner_radius > Pixels::ZERO {
9038 builder.curve_to(bottom_right + curve_width, bottom_right);
9039 }
9040 builder.line_to(next_top_right - curve_width);
9041 if self.corner_radius > Pixels::ZERO {
9042 builder.curve_to(next_top_right + curve_height, next_top_right);
9043 }
9044 }
9045 }
9046 } else {
9047 let curve_width = curve_width(line.start_x, line.end_x);
9048 builder.line_to(bottom_right - curve_height);
9049 if self.corner_radius > Pixels::ZERO {
9050 builder.curve_to(bottom_right - curve_width, bottom_right);
9051 }
9052
9053 let bottom_left = point(line.start_x, bottom_right.y);
9054 builder.line_to(bottom_left + curve_width);
9055 if self.corner_radius > Pixels::ZERO {
9056 builder.curve_to(bottom_left - curve_height, bottom_left);
9057 }
9058 }
9059 }
9060
9061 if first_line.start_x > last_line.start_x {
9062 let curve_width = curve_width(last_line.start_x, first_line.start_x);
9063 let second_top_left = point(last_line.start_x, start_y + self.line_height);
9064 builder.line_to(second_top_left + curve_height);
9065 if self.corner_radius > Pixels::ZERO {
9066 builder.curve_to(second_top_left + curve_width, second_top_left);
9067 }
9068 let first_bottom_left = point(first_line.start_x, second_top_left.y);
9069 builder.line_to(first_bottom_left - curve_width);
9070 if self.corner_radius > Pixels::ZERO {
9071 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
9072 }
9073 }
9074
9075 builder.line_to(first_top_left + curve_height);
9076 if self.corner_radius > Pixels::ZERO {
9077 builder.curve_to(first_top_left + top_curve_width, first_top_left);
9078 }
9079 builder.line_to(first_top_right - top_curve_width);
9080
9081 if let Ok(path) = builder.build() {
9082 window.paint_path(path, self.color);
9083 }
9084 }
9085}
9086
9087enum CursorPopoverType {
9088 CodeContextMenu,
9089 EditPrediction,
9090}
9091
9092pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9093 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
9094}
9095
9096fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
9097 (delta.pow(1.2) / 300.0).into()
9098}
9099
9100pub fn register_action<T: Action>(
9101 editor: &Entity<Editor>,
9102 window: &mut Window,
9103 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
9104) {
9105 let editor = editor.clone();
9106 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
9107 let action = action.downcast_ref().unwrap();
9108 if phase == DispatchPhase::Bubble {
9109 editor.update(cx, |editor, cx| {
9110 listener(editor, action, window, cx);
9111 })
9112 }
9113 })
9114}
9115
9116fn compute_auto_height_layout(
9117 editor: &mut Editor,
9118 max_lines: usize,
9119 max_line_number_width: Pixels,
9120 known_dimensions: Size<Option<Pixels>>,
9121 available_width: AvailableSpace,
9122 window: &mut Window,
9123 cx: &mut Context<Editor>,
9124) -> Option<Size<Pixels>> {
9125 let width = known_dimensions.width.or({
9126 if let AvailableSpace::Definite(available_width) = available_width {
9127 Some(available_width)
9128 } else {
9129 None
9130 }
9131 })?;
9132 if let Some(height) = known_dimensions.height {
9133 return Some(size(width, height));
9134 }
9135
9136 let style = editor.style.as_ref().unwrap();
9137 let font_id = window.text_system().resolve_font(&style.text.font());
9138 let font_size = style.text.font_size.to_pixels(window.rem_size());
9139 let line_height = style.text.line_height_in_pixels(window.rem_size());
9140 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
9141
9142 let mut snapshot = editor.snapshot(window, cx);
9143 let gutter_dimensions = snapshot
9144 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
9145 .unwrap_or_else(|| GutterDimensions::default_with_margin(font_id, font_size, cx));
9146
9147 editor.gutter_dimensions = gutter_dimensions;
9148 let text_width = width - gutter_dimensions.width;
9149 let overscroll = size(em_width, px(0.));
9150
9151 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
9152 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None) {
9153 if editor.set_wrap_width(Some(editor_width), cx) {
9154 snapshot = editor.snapshot(window, cx);
9155 }
9156 }
9157
9158 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
9159 let height = scroll_height
9160 .max(line_height)
9161 .min(line_height * max_lines as f32);
9162
9163 Some(size(width, height))
9164}
9165
9166#[cfg(test)]
9167mod tests {
9168 use super::*;
9169 use crate::{
9170 Editor, MultiBuffer,
9171 display_map::{BlockPlacement, BlockProperties},
9172 editor_tests::{init_test, update_test_language_settings},
9173 };
9174 use gpui::{TestAppContext, VisualTestContext};
9175 use language::language_settings;
9176 use log::info;
9177 use std::num::NonZeroU32;
9178 use util::test::sample_text;
9179
9180 #[gpui::test]
9181 fn test_shape_line_numbers(cx: &mut TestAppContext) {
9182 init_test(cx, |_| {});
9183 let window = cx.add_window(|window, cx| {
9184 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
9185 Editor::new(EditorMode::full(), buffer, None, window, cx)
9186 });
9187
9188 let editor = window.root(cx).unwrap();
9189 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
9190 let line_height = window
9191 .update(cx, |_, window, _| {
9192 style.text.line_height_in_pixels(window.rem_size())
9193 })
9194 .unwrap();
9195 let element = EditorElement::new(&editor, style);
9196 let snapshot = window
9197 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
9198 .unwrap();
9199
9200 let layouts = cx
9201 .update_window(*window, |_, window, cx| {
9202 element.layout_line_numbers(
9203 None,
9204 GutterDimensions {
9205 left_padding: Pixels::ZERO,
9206 right_padding: Pixels::ZERO,
9207 width: px(30.0),
9208 margin: Pixels::ZERO,
9209 git_blame_entries_width: None,
9210 },
9211 line_height,
9212 gpui::Point::default(),
9213 DisplayRow(0)..DisplayRow(6),
9214 &(0..6)
9215 .map(|row| RowInfo {
9216 buffer_row: Some(row),
9217 ..Default::default()
9218 })
9219 .collect::<Vec<_>>(),
9220 &BTreeMap::default(),
9221 Some(DisplayPoint::new(DisplayRow(0), 0)),
9222 &snapshot,
9223 window,
9224 cx,
9225 )
9226 })
9227 .unwrap();
9228 assert_eq!(layouts.len(), 6);
9229
9230 let relative_rows = window
9231 .update(cx, |editor, window, cx| {
9232 let snapshot = editor.snapshot(window, cx);
9233 element.calculate_relative_line_numbers(
9234 &snapshot,
9235 &(DisplayRow(0)..DisplayRow(6)),
9236 Some(DisplayRow(3)),
9237 )
9238 })
9239 .unwrap();
9240 assert_eq!(relative_rows[&DisplayRow(0)], 3);
9241 assert_eq!(relative_rows[&DisplayRow(1)], 2);
9242 assert_eq!(relative_rows[&DisplayRow(2)], 1);
9243 // current line has no relative number
9244 assert_eq!(relative_rows[&DisplayRow(4)], 1);
9245 assert_eq!(relative_rows[&DisplayRow(5)], 2);
9246
9247 // works if cursor is before screen
9248 let relative_rows = window
9249 .update(cx, |editor, window, cx| {
9250 let snapshot = editor.snapshot(window, cx);
9251 element.calculate_relative_line_numbers(
9252 &snapshot,
9253 &(DisplayRow(3)..DisplayRow(6)),
9254 Some(DisplayRow(1)),
9255 )
9256 })
9257 .unwrap();
9258 assert_eq!(relative_rows.len(), 3);
9259 assert_eq!(relative_rows[&DisplayRow(3)], 2);
9260 assert_eq!(relative_rows[&DisplayRow(4)], 3);
9261 assert_eq!(relative_rows[&DisplayRow(5)], 4);
9262
9263 // works if cursor is after screen
9264 let relative_rows = window
9265 .update(cx, |editor, window, cx| {
9266 let snapshot = editor.snapshot(window, cx);
9267 element.calculate_relative_line_numbers(
9268 &snapshot,
9269 &(DisplayRow(0)..DisplayRow(3)),
9270 Some(DisplayRow(6)),
9271 )
9272 })
9273 .unwrap();
9274 assert_eq!(relative_rows.len(), 3);
9275 assert_eq!(relative_rows[&DisplayRow(0)], 5);
9276 assert_eq!(relative_rows[&DisplayRow(1)], 4);
9277 assert_eq!(relative_rows[&DisplayRow(2)], 3);
9278 }
9279
9280 #[gpui::test]
9281 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
9282 init_test(cx, |_| {});
9283
9284 let window = cx.add_window(|window, cx| {
9285 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
9286 Editor::new(EditorMode::full(), buffer, None, window, cx)
9287 });
9288 let cx = &mut VisualTestContext::from_window(*window, cx);
9289 let editor = window.root(cx).unwrap();
9290 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9291
9292 window
9293 .update(cx, |editor, window, cx| {
9294 editor.cursor_shape = CursorShape::Block;
9295 editor.change_selections(None, window, cx, |s| {
9296 s.select_ranges([
9297 Point::new(0, 0)..Point::new(1, 0),
9298 Point::new(3, 2)..Point::new(3, 3),
9299 Point::new(5, 6)..Point::new(6, 0),
9300 ]);
9301 });
9302 })
9303 .unwrap();
9304
9305 let (_, state) = cx.draw(
9306 point(px(500.), px(500.)),
9307 size(px(500.), px(500.)),
9308 |_, _| EditorElement::new(&editor, style),
9309 );
9310
9311 assert_eq!(state.selections.len(), 1);
9312 let local_selections = &state.selections[0].1;
9313 assert_eq!(local_selections.len(), 3);
9314 // moves cursor back one line
9315 assert_eq!(
9316 local_selections[0].head,
9317 DisplayPoint::new(DisplayRow(0), 6)
9318 );
9319 assert_eq!(
9320 local_selections[0].range,
9321 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
9322 );
9323
9324 // moves cursor back one column
9325 assert_eq!(
9326 local_selections[1].range,
9327 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
9328 );
9329 assert_eq!(
9330 local_selections[1].head,
9331 DisplayPoint::new(DisplayRow(3), 2)
9332 );
9333
9334 // leaves cursor on the max point
9335 assert_eq!(
9336 local_selections[2].range,
9337 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
9338 );
9339 assert_eq!(
9340 local_selections[2].head,
9341 DisplayPoint::new(DisplayRow(6), 0)
9342 );
9343
9344 // active lines does not include 1 (even though the range of the selection does)
9345 assert_eq!(
9346 state.active_rows.keys().cloned().collect::<Vec<_>>(),
9347 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
9348 );
9349 }
9350
9351 #[gpui::test]
9352 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
9353 init_test(cx, |_| {});
9354
9355 let window = cx.add_window(|window, cx| {
9356 let buffer = MultiBuffer::build_simple("", cx);
9357 Editor::new(EditorMode::full(), buffer, None, window, cx)
9358 });
9359 let cx = &mut VisualTestContext::from_window(*window, cx);
9360 let editor = window.root(cx).unwrap();
9361 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9362 window
9363 .update(cx, |editor, window, cx| {
9364 editor.set_placeholder_text("hello", cx);
9365 editor.insert_blocks(
9366 [BlockProperties {
9367 style: BlockStyle::Fixed,
9368 placement: BlockPlacement::Above(Anchor::min()),
9369 height: Some(3),
9370 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
9371 priority: 0,
9372 render_in_minimap: true,
9373 }],
9374 None,
9375 cx,
9376 );
9377
9378 // Blur the editor so that it displays placeholder text.
9379 window.blur();
9380 })
9381 .unwrap();
9382
9383 let (_, state) = cx.draw(
9384 point(px(500.), px(500.)),
9385 size(px(500.), px(500.)),
9386 |_, _| EditorElement::new(&editor, style),
9387 );
9388 assert_eq!(state.position_map.line_layouts.len(), 4);
9389 assert_eq!(state.line_numbers.len(), 1);
9390 assert_eq!(
9391 state
9392 .line_numbers
9393 .get(&MultiBufferRow(0))
9394 .map(|line_number| line_number.shaped_line.text.as_ref()),
9395 Some("1")
9396 );
9397 }
9398
9399 #[gpui::test]
9400 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
9401 const TAB_SIZE: u32 = 4;
9402
9403 let input_text = "\t \t|\t| a b";
9404 let expected_invisibles = vec![
9405 Invisible::Tab {
9406 line_start_offset: 0,
9407 line_end_offset: TAB_SIZE as usize,
9408 },
9409 Invisible::Whitespace {
9410 line_offset: TAB_SIZE as usize,
9411 },
9412 Invisible::Tab {
9413 line_start_offset: TAB_SIZE as usize + 1,
9414 line_end_offset: TAB_SIZE as usize * 2,
9415 },
9416 Invisible::Tab {
9417 line_start_offset: TAB_SIZE as usize * 2 + 1,
9418 line_end_offset: TAB_SIZE as usize * 3,
9419 },
9420 Invisible::Whitespace {
9421 line_offset: TAB_SIZE as usize * 3 + 1,
9422 },
9423 Invisible::Whitespace {
9424 line_offset: TAB_SIZE as usize * 3 + 3,
9425 },
9426 ];
9427 assert_eq!(
9428 expected_invisibles.len(),
9429 input_text
9430 .chars()
9431 .filter(|initial_char| initial_char.is_whitespace())
9432 .count(),
9433 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9434 );
9435
9436 for show_line_numbers in [true, false] {
9437 init_test(cx, |s| {
9438 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9439 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
9440 });
9441
9442 let actual_invisibles = collect_invisibles_from_new_editor(
9443 cx,
9444 EditorMode::full(),
9445 input_text,
9446 px(500.0),
9447 show_line_numbers,
9448 );
9449
9450 assert_eq!(expected_invisibles, actual_invisibles);
9451 }
9452 }
9453
9454 #[gpui::test]
9455 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
9456 init_test(cx, |s| {
9457 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9458 s.defaults.tab_size = NonZeroU32::new(4);
9459 });
9460
9461 for editor_mode_without_invisibles in [
9462 EditorMode::SingleLine { auto_width: false },
9463 EditorMode::AutoHeight { max_lines: 100 },
9464 ] {
9465 for show_line_numbers in [true, false] {
9466 let invisibles = collect_invisibles_from_new_editor(
9467 cx,
9468 editor_mode_without_invisibles.clone(),
9469 "\t\t\t| | a b",
9470 px(500.0),
9471 show_line_numbers,
9472 );
9473 assert!(
9474 invisibles.is_empty(),
9475 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
9476 );
9477 }
9478 }
9479 }
9480
9481 #[gpui::test]
9482 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
9483 let tab_size = 4;
9484 let input_text = "a\tbcd ".repeat(9);
9485 let repeated_invisibles = [
9486 Invisible::Tab {
9487 line_start_offset: 1,
9488 line_end_offset: tab_size as usize,
9489 },
9490 Invisible::Whitespace {
9491 line_offset: tab_size as usize + 3,
9492 },
9493 Invisible::Whitespace {
9494 line_offset: tab_size as usize + 4,
9495 },
9496 Invisible::Whitespace {
9497 line_offset: tab_size as usize + 5,
9498 },
9499 Invisible::Whitespace {
9500 line_offset: tab_size as usize + 6,
9501 },
9502 Invisible::Whitespace {
9503 line_offset: tab_size as usize + 7,
9504 },
9505 ];
9506 let expected_invisibles = std::iter::once(repeated_invisibles)
9507 .cycle()
9508 .take(9)
9509 .flatten()
9510 .collect::<Vec<_>>();
9511 assert_eq!(
9512 expected_invisibles.len(),
9513 input_text
9514 .chars()
9515 .filter(|initial_char| initial_char.is_whitespace())
9516 .count(),
9517 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
9518 );
9519 info!("Expected invisibles: {expected_invisibles:?}");
9520
9521 init_test(cx, |_| {});
9522
9523 // Put the same string with repeating whitespace pattern into editors of various size,
9524 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
9525 let resize_step = 10.0;
9526 let mut editor_width = 200.0;
9527 while editor_width <= 1000.0 {
9528 for show_line_numbers in [true, false] {
9529 update_test_language_settings(cx, |s| {
9530 s.defaults.tab_size = NonZeroU32::new(tab_size);
9531 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
9532 s.defaults.preferred_line_length = Some(editor_width as u32);
9533 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
9534 });
9535
9536 let actual_invisibles = collect_invisibles_from_new_editor(
9537 cx,
9538 EditorMode::full(),
9539 &input_text,
9540 px(editor_width),
9541 show_line_numbers,
9542 );
9543
9544 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
9545 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
9546 let mut i = 0;
9547 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
9548 i = actual_index;
9549 match expected_invisibles.get(i) {
9550 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
9551 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
9552 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
9553 _ => {
9554 panic!(
9555 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
9556 )
9557 }
9558 },
9559 None => {
9560 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
9561 }
9562 }
9563 }
9564 let missing_expected_invisibles = &expected_invisibles[i + 1..];
9565 assert!(
9566 missing_expected_invisibles.is_empty(),
9567 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
9568 );
9569
9570 editor_width += resize_step;
9571 }
9572 }
9573 }
9574
9575 fn collect_invisibles_from_new_editor(
9576 cx: &mut TestAppContext,
9577 editor_mode: EditorMode,
9578 input_text: &str,
9579 editor_width: Pixels,
9580 show_line_numbers: bool,
9581 ) -> Vec<Invisible> {
9582 info!(
9583 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
9584 editor_width.0
9585 );
9586 let window = cx.add_window(|window, cx| {
9587 let buffer = MultiBuffer::build_simple(input_text, cx);
9588 Editor::new(editor_mode, buffer, None, window, cx)
9589 });
9590 let cx = &mut VisualTestContext::from_window(*window, cx);
9591 let editor = window.root(cx).unwrap();
9592
9593 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
9594 window
9595 .update(cx, |editor, _, cx| {
9596 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
9597 editor.set_wrap_width(Some(editor_width), cx);
9598 editor.set_show_line_numbers(show_line_numbers, cx);
9599 })
9600 .unwrap();
9601 let (_, state) = cx.draw(
9602 point(px(500.), px(500.)),
9603 size(px(500.), px(500.)),
9604 |_, _| EditorElement::new(&editor, style),
9605 );
9606 state
9607 .position_map
9608 .line_layouts
9609 .iter()
9610 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
9611 .cloned()
9612 .collect()
9613 }
9614}