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