1mod actions;
2pub(crate) mod autoscroll;
3pub(crate) mod scroll_amount;
4
5use crate::editor_settings::ScrollBeyondLastLine;
6use crate::{
7 Anchor, DisplayPoint, DisplayRow, Editor, EditorEvent, EditorMode, EditorSettings,
8 InlayHintRefreshReason, MultiBufferSnapshot, RowExt, ToPoint,
9 display_map::{DisplaySnapshot, ToDisplayPoint},
10 hover_popover::hide_hover,
11 persistence::DB,
12};
13pub use autoscroll::{Autoscroll, AutoscrollStrategy};
14use core::fmt::Debug;
15use gpui::{App, Axis, Context, Global, Pixels, Task, Window, point, px};
16use language::{Bias, Point};
17pub use scroll_amount::ScrollAmount;
18use settings::Settings;
19use std::{
20 cmp::Ordering,
21 time::{Duration, Instant},
22};
23use util::ResultExt;
24use workspace::{ItemId, WorkspaceId};
25
26pub const SCROLL_EVENT_SEPARATION: Duration = Duration::from_millis(28);
27const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
28
29#[derive(Default)]
30pub struct ScrollbarAutoHide(pub bool);
31
32impl Global for ScrollbarAutoHide {}
33
34#[derive(Clone, Copy, Debug, PartialEq)]
35pub struct ScrollAnchor {
36 pub offset: gpui::Point<f32>,
37 pub anchor: Anchor,
38}
39
40impl ScrollAnchor {
41 pub(super) fn new() -> Self {
42 Self {
43 offset: gpui::Point::default(),
44 anchor: Anchor::min(),
45 }
46 }
47
48 pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> gpui::Point<f32> {
49 let mut scroll_position = self.offset;
50 if self.anchor == Anchor::min() {
51 scroll_position.y = 0.;
52 } else {
53 let scroll_top = self.anchor.to_display_point(snapshot).row().as_f32();
54 scroll_position.y += scroll_top;
55 }
56 scroll_position
57 }
58
59 pub fn top_row(&self, buffer: &MultiBufferSnapshot) -> u32 {
60 self.anchor.to_point(buffer).row
61 }
62}
63
64#[derive(Clone, Copy, Debug)]
65pub struct OngoingScroll {
66 last_event: Instant,
67 axis: Option<Axis>,
68}
69
70impl OngoingScroll {
71 fn new() -> Self {
72 Self {
73 last_event: Instant::now() - SCROLL_EVENT_SEPARATION,
74 axis: None,
75 }
76 }
77
78 pub fn filter(&self, delta: &mut gpui::Point<Pixels>) -> Option<Axis> {
79 const UNLOCK_PERCENT: f32 = 1.9;
80 const UNLOCK_LOWER_BOUND: Pixels = px(6.);
81 let mut axis = self.axis;
82
83 let x = delta.x.abs();
84 let y = delta.y.abs();
85 let duration = Instant::now().duration_since(self.last_event);
86 if duration > SCROLL_EVENT_SEPARATION {
87 //New ongoing scroll will start, determine axis
88 axis = if x <= y {
89 Some(Axis::Vertical)
90 } else {
91 Some(Axis::Horizontal)
92 };
93 } else if x.max(y) >= UNLOCK_LOWER_BOUND {
94 //Check if the current ongoing will need to unlock
95 match axis {
96 Some(Axis::Vertical) => {
97 if x > y && x >= y * UNLOCK_PERCENT {
98 axis = None;
99 }
100 }
101
102 Some(Axis::Horizontal) => {
103 if y > x && y >= x * UNLOCK_PERCENT {
104 axis = None;
105 }
106 }
107
108 None => {}
109 }
110 }
111
112 match axis {
113 Some(Axis::Vertical) => {
114 *delta = point(px(0.), delta.y);
115 }
116 Some(Axis::Horizontal) => {
117 *delta = point(delta.x, px(0.));
118 }
119 None => {}
120 }
121
122 axis
123 }
124}
125
126#[derive(Copy, Clone, Default, PartialEq, Eq)]
127pub enum ScrollbarThumbState {
128 #[default]
129 Idle,
130 Hovered,
131 Dragging,
132}
133
134#[derive(PartialEq, Eq)]
135pub struct ActiveScrollbarState {
136 axis: Axis,
137 thumb_state: ScrollbarThumbState,
138}
139
140impl ActiveScrollbarState {
141 pub fn new(axis: Axis, thumb_state: ScrollbarThumbState) -> Self {
142 ActiveScrollbarState { axis, thumb_state }
143 }
144
145 pub fn thumb_state_for_axis(&self, axis: Axis) -> Option<ScrollbarThumbState> {
146 (self.axis == axis).then_some(self.thumb_state)
147 }
148}
149
150pub struct ScrollManager {
151 pub(crate) vertical_scroll_margin: f32,
152 anchor: ScrollAnchor,
153 ongoing: OngoingScroll,
154 autoscroll_request: Option<(Autoscroll, bool)>,
155 last_autoscroll: Option<(gpui::Point<f32>, f32, f32, AutoscrollStrategy)>,
156 show_scrollbars: bool,
157 hide_scrollbar_task: Option<Task<()>>,
158 active_scrollbar: Option<ActiveScrollbarState>,
159 visible_line_count: Option<f32>,
160 forbid_vertical_scroll: bool,
161 minimap_thumb_state: Option<ScrollbarThumbState>,
162}
163
164impl ScrollManager {
165 pub fn new(cx: &mut App) -> Self {
166 ScrollManager {
167 vertical_scroll_margin: EditorSettings::get_global(cx).vertical_scroll_margin,
168 anchor: ScrollAnchor::new(),
169 ongoing: OngoingScroll::new(),
170 autoscroll_request: None,
171 show_scrollbars: true,
172 hide_scrollbar_task: None,
173 active_scrollbar: None,
174 last_autoscroll: None,
175 visible_line_count: None,
176 forbid_vertical_scroll: false,
177 minimap_thumb_state: None,
178 }
179 }
180
181 pub fn clone_state(&mut self, other: &Self) {
182 self.anchor = other.anchor;
183 self.ongoing = other.ongoing;
184 }
185
186 pub fn anchor(&self) -> ScrollAnchor {
187 self.anchor
188 }
189
190 pub fn ongoing_scroll(&self) -> OngoingScroll {
191 self.ongoing
192 }
193
194 pub fn update_ongoing_scroll(&mut self, axis: Option<Axis>) {
195 self.ongoing.last_event = Instant::now();
196 self.ongoing.axis = axis;
197 }
198
199 pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> gpui::Point<f32> {
200 self.anchor.scroll_position(snapshot)
201 }
202
203 fn set_scroll_position(
204 &mut self,
205 scroll_position: gpui::Point<f32>,
206 map: &DisplaySnapshot,
207 local: bool,
208 autoscroll: bool,
209 workspace_id: Option<WorkspaceId>,
210 window: &mut Window,
211 cx: &mut Context<Editor>,
212 ) {
213 let (new_anchor, top_row) = if scroll_position.y <= 0. {
214 (
215 ScrollAnchor {
216 anchor: Anchor::min(),
217 offset: scroll_position.max(&gpui::Point::default()),
218 },
219 0,
220 )
221 } else {
222 let scroll_top = scroll_position.y;
223 let scroll_top = match EditorSettings::get_global(cx).scroll_beyond_last_line {
224 ScrollBeyondLastLine::OnePage => scroll_top,
225 ScrollBeyondLastLine::Off => {
226 if let Some(height_in_lines) = self.visible_line_count {
227 let max_row = map.max_point().row().0 as f32;
228 scroll_top.min(max_row - height_in_lines + 1.).max(0.)
229 } else {
230 scroll_top
231 }
232 }
233 ScrollBeyondLastLine::VerticalScrollMargin => {
234 if let Some(height_in_lines) = self.visible_line_count {
235 let max_row = map.max_point().row().0 as f32;
236 scroll_top
237 .min(max_row - height_in_lines + 1. + self.vertical_scroll_margin)
238 .max(0.)
239 } else {
240 scroll_top
241 }
242 }
243 };
244
245 let scroll_top_buffer_point =
246 DisplayPoint::new(DisplayRow(scroll_top as u32), 0).to_point(map);
247 let top_anchor = map
248 .buffer_snapshot
249 .anchor_at(scroll_top_buffer_point, Bias::Right);
250
251 (
252 ScrollAnchor {
253 anchor: top_anchor,
254 offset: point(
255 scroll_position.x.max(0.),
256 scroll_top - top_anchor.to_display_point(map).row().as_f32(),
257 ),
258 },
259 scroll_top_buffer_point.row,
260 )
261 };
262
263 self.set_anchor(
264 new_anchor,
265 top_row,
266 local,
267 autoscroll,
268 workspace_id,
269 window,
270 cx,
271 );
272 }
273
274 fn set_anchor(
275 &mut self,
276 anchor: ScrollAnchor,
277 top_row: u32,
278 local: bool,
279 autoscroll: bool,
280 workspace_id: Option<WorkspaceId>,
281 window: &mut Window,
282 cx: &mut Context<Editor>,
283 ) {
284 let adjusted_anchor = if self.forbid_vertical_scroll {
285 ScrollAnchor {
286 offset: gpui::Point::new(anchor.offset.x, self.anchor.offset.y),
287 anchor: self.anchor.anchor,
288 }
289 } else {
290 anchor
291 };
292
293 self.anchor = adjusted_anchor;
294 cx.emit(EditorEvent::ScrollPositionChanged { local, autoscroll });
295 self.show_scrollbars(window, cx);
296 self.autoscroll_request.take();
297 if let Some(workspace_id) = workspace_id {
298 let item_id = cx.entity().entity_id().as_u64() as ItemId;
299
300 cx.foreground_executor()
301 .spawn(async move {
302 log::debug!(
303 "Saving scroll position for item {item_id:?} in workspace {workspace_id:?}"
304 );
305 DB.save_scroll_position(
306 item_id,
307 workspace_id,
308 top_row,
309 anchor.offset.x,
310 anchor.offset.y,
311 )
312 .await
313 .log_err()
314 })
315 .detach()
316 }
317 cx.notify();
318 }
319
320 pub fn show_scrollbars(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
321 if !self.show_scrollbars {
322 self.show_scrollbars = true;
323 cx.notify();
324 }
325
326 if cx.default_global::<ScrollbarAutoHide>().0 {
327 self.hide_scrollbar_task = Some(cx.spawn_in(window, async move |editor, cx| {
328 cx.background_executor()
329 .timer(SCROLLBAR_SHOW_INTERVAL)
330 .await;
331 editor
332 .update(cx, |editor, cx| {
333 editor.scroll_manager.show_scrollbars = false;
334 cx.notify();
335 })
336 .log_err();
337 }));
338 } else {
339 self.hide_scrollbar_task = None;
340 }
341 }
342
343 pub fn scrollbars_visible(&self) -> bool {
344 self.show_scrollbars
345 }
346
347 pub fn autoscroll_request(&self) -> Option<Autoscroll> {
348 self.autoscroll_request.map(|(autoscroll, _)| autoscroll)
349 }
350
351 pub fn active_scrollbar_state(&self) -> Option<&ActiveScrollbarState> {
352 self.active_scrollbar.as_ref()
353 }
354
355 pub fn dragging_scrollbar_axis(&self) -> Option<Axis> {
356 self.active_scrollbar
357 .as_ref()
358 .filter(|scrollbar| scrollbar.thumb_state == ScrollbarThumbState::Dragging)
359 .map(|scrollbar| scrollbar.axis)
360 }
361
362 pub fn any_scrollbar_dragged(&self) -> bool {
363 self.active_scrollbar
364 .as_ref()
365 .is_some_and(|scrollbar| scrollbar.thumb_state == ScrollbarThumbState::Dragging)
366 }
367
368 pub fn set_hovered_scroll_thumb_axis(&mut self, axis: Axis, cx: &mut Context<Editor>) {
369 self.update_active_scrollbar_state(
370 Some(ActiveScrollbarState::new(
371 axis,
372 ScrollbarThumbState::Hovered,
373 )),
374 cx,
375 );
376 }
377
378 pub fn set_dragged_scroll_thumb_axis(&mut self, axis: Axis, cx: &mut Context<Editor>) {
379 self.update_active_scrollbar_state(
380 Some(ActiveScrollbarState::new(
381 axis,
382 ScrollbarThumbState::Dragging,
383 )),
384 cx,
385 );
386 }
387
388 pub fn reset_scrollbar_state(&mut self, cx: &mut Context<Editor>) {
389 self.update_active_scrollbar_state(None, cx);
390 }
391
392 fn update_active_scrollbar_state(
393 &mut self,
394 new_state: Option<ActiveScrollbarState>,
395 cx: &mut Context<Editor>,
396 ) {
397 if self.active_scrollbar != new_state {
398 self.active_scrollbar = new_state;
399 cx.notify();
400 }
401 }
402
403 pub fn set_is_hovering_minimap_thumb(&mut self, hovered: bool, cx: &mut Context<Editor>) {
404 self.update_minimap_thumb_state(
405 Some(if hovered {
406 ScrollbarThumbState::Hovered
407 } else {
408 ScrollbarThumbState::Idle
409 }),
410 cx,
411 );
412 }
413
414 pub fn set_is_dragging_minimap(&mut self, cx: &mut Context<Editor>) {
415 self.update_minimap_thumb_state(Some(ScrollbarThumbState::Dragging), cx);
416 }
417
418 pub fn hide_minimap_thumb(&mut self, cx: &mut Context<Editor>) {
419 self.update_minimap_thumb_state(None, cx);
420 }
421
422 pub fn is_dragging_minimap(&self) -> bool {
423 self.minimap_thumb_state
424 .is_some_and(|state| state == ScrollbarThumbState::Dragging)
425 }
426
427 fn update_minimap_thumb_state(
428 &mut self,
429 thumb_state: Option<ScrollbarThumbState>,
430 cx: &mut Context<Editor>,
431 ) {
432 if self.minimap_thumb_state != thumb_state {
433 self.minimap_thumb_state = thumb_state;
434 cx.notify();
435 }
436 }
437
438 pub fn minimap_thumb_state(&self) -> Option<ScrollbarThumbState> {
439 self.minimap_thumb_state
440 }
441
442 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
443 if max < self.anchor.offset.x {
444 self.anchor.offset.x = max;
445 true
446 } else {
447 false
448 }
449 }
450
451 pub fn set_forbid_vertical_scroll(&mut self, forbid: bool) {
452 self.forbid_vertical_scroll = forbid;
453 }
454
455 pub fn forbid_vertical_scroll(&self) -> bool {
456 self.forbid_vertical_scroll
457 }
458}
459
460impl Editor {
461 pub fn vertical_scroll_margin(&self) -> usize {
462 self.scroll_manager.vertical_scroll_margin as usize
463 }
464
465 pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut Context<Self>) {
466 self.scroll_manager.vertical_scroll_margin = margin_rows as f32;
467 cx.notify();
468 }
469
470 pub fn visible_line_count(&self) -> Option<f32> {
471 self.scroll_manager.visible_line_count
472 }
473
474 pub fn visible_row_count(&self) -> Option<u32> {
475 self.visible_line_count()
476 .map(|line_count| line_count as u32 - 1)
477 }
478
479 pub(crate) fn set_visible_line_count(
480 &mut self,
481 lines: f32,
482 window: &mut Window,
483 cx: &mut Context<Self>,
484 ) {
485 let opened_first_time = self.scroll_manager.visible_line_count.is_none();
486 self.scroll_manager.visible_line_count = Some(lines);
487 if opened_first_time {
488 cx.spawn_in(window, async move |editor, cx| {
489 editor
490 .update(cx, |editor, cx| {
491 editor.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx)
492 })
493 .ok()
494 })
495 .detach()
496 }
497 }
498
499 pub fn apply_scroll_delta(
500 &mut self,
501 scroll_delta: gpui::Point<f32>,
502 window: &mut Window,
503 cx: &mut Context<Self>,
504 ) {
505 let mut delta = scroll_delta;
506 if self.scroll_manager.forbid_vertical_scroll {
507 delta.y = 0.0;
508 }
509 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
510 let position = self.scroll_manager.anchor.scroll_position(&display_map) + delta;
511 self.set_scroll_position_taking_display_map(position, true, false, display_map, window, cx);
512 }
513
514 pub fn set_scroll_position(
515 &mut self,
516 scroll_position: gpui::Point<f32>,
517 window: &mut Window,
518 cx: &mut Context<Self>,
519 ) {
520 let mut position = scroll_position;
521 if self.scroll_manager.forbid_vertical_scroll {
522 let current_position = self.scroll_position(cx);
523 position.y = current_position.y;
524 }
525 self.set_scroll_position_internal(position, true, false, window, cx);
526 }
527
528 /// Scrolls so that `row` is at the top of the editor view.
529 pub fn set_scroll_top_row(
530 &mut self,
531 row: DisplayRow,
532 window: &mut Window,
533 cx: &mut Context<Editor>,
534 ) {
535 let snapshot = self.snapshot(window, cx).display_snapshot;
536 let new_screen_top = DisplayPoint::new(row, 0);
537 let new_screen_top = new_screen_top.to_offset(&snapshot, Bias::Left);
538 let new_anchor = snapshot.buffer_snapshot.anchor_before(new_screen_top);
539
540 self.set_scroll_anchor(
541 ScrollAnchor {
542 anchor: new_anchor,
543 offset: Default::default(),
544 },
545 window,
546 cx,
547 );
548 }
549
550 pub(crate) fn set_scroll_position_internal(
551 &mut self,
552 scroll_position: gpui::Point<f32>,
553 local: bool,
554 autoscroll: bool,
555 window: &mut Window,
556 cx: &mut Context<Self>,
557 ) {
558 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
559 self.set_scroll_position_taking_display_map(
560 scroll_position,
561 local,
562 autoscroll,
563 map,
564 window,
565 cx,
566 );
567 }
568
569 fn set_scroll_position_taking_display_map(
570 &mut self,
571 scroll_position: gpui::Point<f32>,
572 local: bool,
573 autoscroll: bool,
574 display_map: DisplaySnapshot,
575 window: &mut Window,
576 cx: &mut Context<Self>,
577 ) {
578 hide_hover(self, cx);
579 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
580
581 self.edit_prediction_preview
582 .set_previous_scroll_position(None);
583
584 let adjusted_position = if self.scroll_manager.forbid_vertical_scroll {
585 let current_position = self.scroll_manager.anchor.scroll_position(&display_map);
586 gpui::Point::new(scroll_position.x, current_position.y)
587 } else {
588 scroll_position
589 };
590
591 self.scroll_manager.set_scroll_position(
592 adjusted_position,
593 &display_map,
594 local,
595 autoscroll,
596 workspace_id,
597 window,
598 cx,
599 );
600
601 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
602 }
603
604 pub fn scroll_position(&self, cx: &mut Context<Self>) -> gpui::Point<f32> {
605 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
606 self.scroll_manager.anchor.scroll_position(&display_map)
607 }
608
609 pub fn set_scroll_anchor(
610 &mut self,
611 scroll_anchor: ScrollAnchor,
612 window: &mut Window,
613 cx: &mut Context<Self>,
614 ) {
615 hide_hover(self, cx);
616 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
617 let top_row = scroll_anchor
618 .anchor
619 .to_point(&self.buffer().read(cx).snapshot(cx))
620 .row;
621 self.scroll_manager.set_anchor(
622 scroll_anchor,
623 top_row,
624 true,
625 false,
626 workspace_id,
627 window,
628 cx,
629 );
630 }
631
632 pub(crate) fn set_scroll_anchor_remote(
633 &mut self,
634 scroll_anchor: ScrollAnchor,
635 window: &mut Window,
636 cx: &mut Context<Self>,
637 ) {
638 hide_hover(self, cx);
639 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
640 let snapshot = &self.buffer().read(cx).snapshot(cx);
641 if !scroll_anchor.anchor.is_valid(snapshot) {
642 log::warn!("Invalid scroll anchor: {:?}", scroll_anchor);
643 return;
644 }
645 let top_row = scroll_anchor.anchor.to_point(snapshot).row;
646 self.scroll_manager.set_anchor(
647 scroll_anchor,
648 top_row,
649 false,
650 false,
651 workspace_id,
652 window,
653 cx,
654 );
655 }
656
657 pub fn scroll_screen(
658 &mut self,
659 amount: &ScrollAmount,
660 window: &mut Window,
661 cx: &mut Context<Self>,
662 ) {
663 if matches!(self.mode, EditorMode::SingleLine { .. }) {
664 cx.propagate();
665 return;
666 }
667
668 if self.take_rename(true, window, cx).is_some() {
669 return;
670 }
671
672 let cur_position = self.scroll_position(cx);
673 let Some(visible_line_count) = self.visible_line_count() else {
674 return;
675 };
676 let new_pos = cur_position + point(0., amount.lines(visible_line_count));
677 self.set_scroll_position(new_pos, window, cx);
678 }
679
680 /// Returns an ordering. The newest selection is:
681 /// Ordering::Equal => on screen
682 /// Ordering::Less => above the screen
683 /// Ordering::Greater => below the screen
684 pub fn newest_selection_on_screen(&self, cx: &mut App) -> Ordering {
685 let snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
686 let newest_head = self
687 .selections
688 .newest_anchor()
689 .head()
690 .to_display_point(&snapshot);
691 let screen_top = self
692 .scroll_manager
693 .anchor
694 .anchor
695 .to_display_point(&snapshot);
696
697 if screen_top > newest_head {
698 return Ordering::Less;
699 }
700
701 if let Some(visible_lines) = self.visible_line_count() {
702 if newest_head.row() <= DisplayRow(screen_top.row().0 + visible_lines as u32) {
703 return Ordering::Equal;
704 }
705 }
706
707 Ordering::Greater
708 }
709
710 pub fn read_scroll_position_from_db(
711 &mut self,
712 item_id: u64,
713 workspace_id: WorkspaceId,
714 window: &mut Window,
715 cx: &mut Context<Editor>,
716 ) {
717 let scroll_position = DB.get_scroll_position(item_id, workspace_id);
718 if let Ok(Some((top_row, x, y))) = scroll_position {
719 let top_anchor = self
720 .buffer()
721 .read(cx)
722 .snapshot(cx)
723 .anchor_at(Point::new(top_row, 0), Bias::Left);
724 let scroll_anchor = ScrollAnchor {
725 offset: gpui::Point::new(x, y),
726 anchor: top_anchor,
727 };
728 self.set_scroll_anchor(scroll_anchor, window, cx);
729 }
730 }
731}