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