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, PartialEq, Eq)]
127pub enum ScrollbarThumbState {
128 Idle,
129 Hovered,
130 Dragging,
131}
132
133#[derive(PartialEq, Eq)]
134pub struct ActiveScrollbarState {
135 axis: Axis,
136 thumb_state: ScrollbarThumbState,
137}
138
139impl ActiveScrollbarState {
140 pub fn new(axis: Axis, thumb_state: ScrollbarThumbState) -> Self {
141 ActiveScrollbarState { axis, thumb_state }
142 }
143
144 pub fn thumb_state_for_axis(&self, axis: Axis) -> Option<ScrollbarThumbState> {
145 (self.axis == axis).then_some(self.thumb_state)
146 }
147}
148
149pub struct ScrollManager {
150 pub(crate) vertical_scroll_margin: f32,
151 anchor: ScrollAnchor,
152 ongoing: OngoingScroll,
153 autoscroll_request: Option<(Autoscroll, bool)>,
154 last_autoscroll: Option<(gpui::Point<f32>, f32, f32, AutoscrollStrategy)>,
155 show_scrollbars: bool,
156 hide_scrollbar_task: Option<Task<()>>,
157 active_scrollbar: Option<ActiveScrollbarState>,
158 visible_line_count: Option<f32>,
159 forbid_vertical_scroll: bool,
160 dragging_minimap: bool,
161 show_minimap_thumb: bool,
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 dragging_minimap: false,
178 show_minimap_thumb: false,
179 }
180 }
181
182 pub fn clone_state(&mut self, other: &Self) {
183 self.anchor = other.anchor;
184 self.ongoing = other.ongoing;
185 }
186
187 pub fn anchor(&self) -> ScrollAnchor {
188 self.anchor
189 }
190
191 pub fn ongoing_scroll(&self) -> OngoingScroll {
192 self.ongoing
193 }
194
195 pub fn update_ongoing_scroll(&mut self, axis: Option<Axis>) {
196 self.ongoing.last_event = Instant::now();
197 self.ongoing.axis = axis;
198 }
199
200 pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> gpui::Point<f32> {
201 self.anchor.scroll_position(snapshot)
202 }
203
204 fn set_scroll_position(
205 &mut self,
206 scroll_position: gpui::Point<f32>,
207 map: &DisplaySnapshot,
208 local: bool,
209 autoscroll: bool,
210 workspace_id: Option<WorkspaceId>,
211 window: &mut Window,
212 cx: &mut Context<Editor>,
213 ) {
214 let (new_anchor, top_row) = if scroll_position.y <= 0. {
215 (
216 ScrollAnchor {
217 anchor: Anchor::min(),
218 offset: scroll_position.max(&gpui::Point::default()),
219 },
220 0,
221 )
222 } else {
223 let scroll_top = scroll_position.y;
224 let scroll_top = match EditorSettings::get_global(cx).scroll_beyond_last_line {
225 ScrollBeyondLastLine::OnePage => scroll_top,
226 ScrollBeyondLastLine::Off => {
227 if let Some(height_in_lines) = self.visible_line_count {
228 let max_row = map.max_point().row().0 as f32;
229 scroll_top.min(max_row - height_in_lines + 1.).max(0.)
230 } else {
231 scroll_top
232 }
233 }
234 ScrollBeyondLastLine::VerticalScrollMargin => {
235 if let Some(height_in_lines) = self.visible_line_count {
236 let max_row = map.max_point().row().0 as f32;
237 scroll_top
238 .min(max_row - height_in_lines + 1. + self.vertical_scroll_margin)
239 .max(0.)
240 } else {
241 scroll_top
242 }
243 }
244 };
245
246 let scroll_top_buffer_point =
247 DisplayPoint::new(DisplayRow(scroll_top as u32), 0).to_point(map);
248 let top_anchor = map
249 .buffer_snapshot
250 .anchor_at(scroll_top_buffer_point, Bias::Right);
251
252 (
253 ScrollAnchor {
254 anchor: top_anchor,
255 offset: point(
256 scroll_position.x.max(0.),
257 scroll_top - top_anchor.to_display_point(map).row().as_f32(),
258 ),
259 },
260 scroll_top_buffer_point.row,
261 )
262 };
263
264 self.set_anchor(
265 new_anchor,
266 top_row,
267 local,
268 autoscroll,
269 workspace_id,
270 window,
271 cx,
272 );
273 }
274
275 fn set_anchor(
276 &mut self,
277 anchor: ScrollAnchor,
278 top_row: u32,
279 local: bool,
280 autoscroll: bool,
281 workspace_id: Option<WorkspaceId>,
282 window: &mut Window,
283 cx: &mut Context<Editor>,
284 ) {
285 let adjusted_anchor = if self.forbid_vertical_scroll {
286 ScrollAnchor {
287 offset: gpui::Point::new(anchor.offset.x, self.anchor.offset.y),
288 anchor: self.anchor.anchor,
289 }
290 } else {
291 anchor
292 };
293
294 self.anchor = adjusted_anchor;
295 cx.emit(EditorEvent::ScrollPositionChanged { local, autoscroll });
296 self.show_scrollbars(window, cx);
297 self.autoscroll_request.take();
298 if let Some(workspace_id) = workspace_id {
299 let item_id = cx.entity().entity_id().as_u64() as ItemId;
300
301 cx.foreground_executor()
302 .spawn(async move {
303 log::debug!(
304 "Saving scroll position for item {item_id:?} in workspace {workspace_id:?}"
305 );
306 DB.save_scroll_position(
307 item_id,
308 workspace_id,
309 top_row,
310 anchor.offset.x,
311 anchor.offset.y,
312 )
313 .await
314 .log_err()
315 })
316 .detach()
317 }
318 cx.notify();
319 }
320
321 pub fn show_scrollbars(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
322 if !self.show_scrollbars {
323 self.show_scrollbars = true;
324 cx.notify();
325 }
326
327 if cx.default_global::<ScrollbarAutoHide>().0 {
328 self.hide_scrollbar_task = Some(cx.spawn_in(window, async move |editor, cx| {
329 cx.background_executor()
330 .timer(SCROLLBAR_SHOW_INTERVAL)
331 .await;
332 editor
333 .update(cx, |editor, cx| {
334 editor.scroll_manager.show_scrollbars = false;
335 cx.notify();
336 })
337 .log_err();
338 }));
339 } else {
340 self.hide_scrollbar_task = None;
341 }
342 }
343
344 pub fn scrollbars_visible(&self) -> bool {
345 self.show_scrollbars
346 }
347
348 pub fn show_minimap_thumb(&mut self, cx: &mut Context<Editor>) {
349 if !self.show_minimap_thumb {
350 self.show_minimap_thumb = true;
351 cx.notify();
352 }
353 }
354
355 pub fn hide_minimap_thumb(&mut self, cx: &mut Context<Editor>) {
356 if self.show_minimap_thumb {
357 self.show_minimap_thumb = false;
358 cx.notify();
359 }
360 }
361
362 pub fn minimap_thumb_visible(&mut self) -> bool {
363 self.show_minimap_thumb
364 }
365
366 pub fn autoscroll_request(&self) -> Option<Autoscroll> {
367 self.autoscroll_request.map(|(autoscroll, _)| autoscroll)
368 }
369
370 pub fn active_scrollbar_state(&self) -> Option<&ActiveScrollbarState> {
371 self.active_scrollbar.as_ref()
372 }
373
374 pub fn dragging_scrollbar_axis(&self) -> Option<Axis> {
375 self.active_scrollbar
376 .as_ref()
377 .map(|scrollbar| scrollbar.axis)
378 }
379
380 pub fn any_scrollbar_dragged(&self) -> bool {
381 self.active_scrollbar
382 .as_ref()
383 .is_some_and(|scrollbar| scrollbar.thumb_state == ScrollbarThumbState::Dragging)
384 }
385
386 pub fn set_hovered_scroll_thumb_axis(&mut self, axis: Axis, cx: &mut Context<Editor>) {
387 self.update_active_scrollbar_state(
388 Some(ActiveScrollbarState::new(
389 axis,
390 ScrollbarThumbState::Hovered,
391 )),
392 cx,
393 );
394 }
395
396 pub fn set_dragged_scroll_thumb_axis(&mut self, axis: Axis, cx: &mut Context<Editor>) {
397 self.update_active_scrollbar_state(
398 Some(ActiveScrollbarState::new(
399 axis,
400 ScrollbarThumbState::Dragging,
401 )),
402 cx,
403 );
404 }
405
406 pub fn reset_scrollbar_state(&mut self, cx: &mut Context<Editor>) {
407 self.update_active_scrollbar_state(None, cx);
408 }
409
410 fn update_active_scrollbar_state(
411 &mut self,
412 new_state: Option<ActiveScrollbarState>,
413 cx: &mut Context<Editor>,
414 ) {
415 if self.active_scrollbar != new_state {
416 self.active_scrollbar = new_state;
417 cx.notify();
418 }
419 }
420
421 pub fn is_dragging_minimap(&self) -> bool {
422 self.dragging_minimap
423 }
424
425 pub fn set_is_dragging_minimap(&mut self, dragging: bool, cx: &mut Context<Editor>) {
426 self.dragging_minimap = dragging;
427 cx.notify();
428 }
429
430 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
431 if max < self.anchor.offset.x {
432 self.anchor.offset.x = max;
433 true
434 } else {
435 false
436 }
437 }
438
439 pub fn set_forbid_vertical_scroll(&mut self, forbid: bool) {
440 self.forbid_vertical_scroll = forbid;
441 }
442
443 pub fn forbid_vertical_scroll(&self) -> bool {
444 self.forbid_vertical_scroll
445 }
446}
447
448impl Editor {
449 pub fn vertical_scroll_margin(&self) -> usize {
450 self.scroll_manager.vertical_scroll_margin as usize
451 }
452
453 pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut Context<Self>) {
454 self.scroll_manager.vertical_scroll_margin = margin_rows as f32;
455 cx.notify();
456 }
457
458 pub fn visible_line_count(&self) -> Option<f32> {
459 self.scroll_manager.visible_line_count
460 }
461
462 pub fn visible_row_count(&self) -> Option<u32> {
463 self.visible_line_count()
464 .map(|line_count| line_count as u32 - 1)
465 }
466
467 pub(crate) fn set_visible_line_count(
468 &mut self,
469 lines: f32,
470 window: &mut Window,
471 cx: &mut Context<Self>,
472 ) {
473 let opened_first_time = self.scroll_manager.visible_line_count.is_none();
474 self.scroll_manager.visible_line_count = Some(lines);
475 if opened_first_time {
476 cx.spawn_in(window, async move |editor, cx| {
477 editor
478 .update(cx, |editor, cx| {
479 editor.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx)
480 })
481 .ok()
482 })
483 .detach()
484 }
485 }
486
487 pub fn apply_scroll_delta(
488 &mut self,
489 scroll_delta: gpui::Point<f32>,
490 window: &mut Window,
491 cx: &mut Context<Self>,
492 ) {
493 let mut delta = scroll_delta;
494 if self.scroll_manager.forbid_vertical_scroll {
495 delta.y = 0.0;
496 }
497 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
498 let position = self.scroll_manager.anchor.scroll_position(&display_map) + delta;
499 self.set_scroll_position_taking_display_map(position, true, false, display_map, window, cx);
500 }
501
502 pub fn set_scroll_position(
503 &mut self,
504 scroll_position: gpui::Point<f32>,
505 window: &mut Window,
506 cx: &mut Context<Self>,
507 ) {
508 let mut position = scroll_position;
509 if self.scroll_manager.forbid_vertical_scroll {
510 let current_position = self.scroll_position(cx);
511 position.y = current_position.y;
512 }
513 self.set_scroll_position_internal(position, true, false, window, cx);
514 }
515
516 /// Scrolls so that `row` is at the top of the editor view.
517 pub fn set_scroll_top_row(
518 &mut self,
519 row: DisplayRow,
520 window: &mut Window,
521 cx: &mut Context<Editor>,
522 ) {
523 let snapshot = self.snapshot(window, cx).display_snapshot;
524 let new_screen_top = DisplayPoint::new(row, 0);
525 let new_screen_top = new_screen_top.to_offset(&snapshot, Bias::Left);
526 let new_anchor = snapshot.buffer_snapshot.anchor_before(new_screen_top);
527
528 self.set_scroll_anchor(
529 ScrollAnchor {
530 anchor: new_anchor,
531 offset: Default::default(),
532 },
533 window,
534 cx,
535 );
536 }
537
538 pub(crate) fn set_scroll_position_internal(
539 &mut self,
540 scroll_position: gpui::Point<f32>,
541 local: bool,
542 autoscroll: bool,
543 window: &mut Window,
544 cx: &mut Context<Self>,
545 ) {
546 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
547 self.set_scroll_position_taking_display_map(
548 scroll_position,
549 local,
550 autoscroll,
551 map,
552 window,
553 cx,
554 );
555 }
556
557 fn set_scroll_position_taking_display_map(
558 &mut self,
559 scroll_position: gpui::Point<f32>,
560 local: bool,
561 autoscroll: bool,
562 display_map: DisplaySnapshot,
563 window: &mut Window,
564 cx: &mut Context<Self>,
565 ) {
566 hide_hover(self, cx);
567 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
568
569 self.edit_prediction_preview
570 .set_previous_scroll_position(None);
571
572 let adjusted_position = if self.scroll_manager.forbid_vertical_scroll {
573 let current_position = self.scroll_manager.anchor.scroll_position(&display_map);
574 gpui::Point::new(scroll_position.x, current_position.y)
575 } else {
576 scroll_position
577 };
578
579 self.scroll_manager.set_scroll_position(
580 adjusted_position,
581 &display_map,
582 local,
583 autoscroll,
584 workspace_id,
585 window,
586 cx,
587 );
588
589 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
590 }
591
592 pub fn scroll_position(&self, cx: &mut Context<Self>) -> gpui::Point<f32> {
593 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
594 self.scroll_manager.anchor.scroll_position(&display_map)
595 }
596
597 pub fn set_scroll_anchor(
598 &mut self,
599 scroll_anchor: ScrollAnchor,
600 window: &mut Window,
601 cx: &mut Context<Self>,
602 ) {
603 hide_hover(self, cx);
604 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
605 let top_row = scroll_anchor
606 .anchor
607 .to_point(&self.buffer().read(cx).snapshot(cx))
608 .row;
609 self.scroll_manager.set_anchor(
610 scroll_anchor,
611 top_row,
612 true,
613 false,
614 workspace_id,
615 window,
616 cx,
617 );
618 }
619
620 pub(crate) fn set_scroll_anchor_remote(
621 &mut self,
622 scroll_anchor: ScrollAnchor,
623 window: &mut Window,
624 cx: &mut Context<Self>,
625 ) {
626 hide_hover(self, cx);
627 let workspace_id = self.workspace.as_ref().and_then(|workspace| workspace.1);
628 let snapshot = &self.buffer().read(cx).snapshot(cx);
629 if !scroll_anchor.anchor.is_valid(snapshot) {
630 log::warn!("Invalid scroll anchor: {:?}", scroll_anchor);
631 return;
632 }
633 let top_row = scroll_anchor.anchor.to_point(snapshot).row;
634 self.scroll_manager.set_anchor(
635 scroll_anchor,
636 top_row,
637 false,
638 false,
639 workspace_id,
640 window,
641 cx,
642 );
643 }
644
645 pub fn scroll_screen(
646 &mut self,
647 amount: &ScrollAmount,
648 window: &mut Window,
649 cx: &mut Context<Self>,
650 ) {
651 if matches!(self.mode, EditorMode::SingleLine { .. }) {
652 cx.propagate();
653 return;
654 }
655
656 if self.take_rename(true, window, cx).is_some() {
657 return;
658 }
659
660 let cur_position = self.scroll_position(cx);
661 let Some(visible_line_count) = self.visible_line_count() else {
662 return;
663 };
664 let new_pos = cur_position + point(0., amount.lines(visible_line_count));
665 self.set_scroll_position(new_pos, window, cx);
666 }
667
668 /// Returns an ordering. The newest selection is:
669 /// Ordering::Equal => on screen
670 /// Ordering::Less => above the screen
671 /// Ordering::Greater => below the screen
672 pub fn newest_selection_on_screen(&self, cx: &mut App) -> Ordering {
673 let snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
674 let newest_head = self
675 .selections
676 .newest_anchor()
677 .head()
678 .to_display_point(&snapshot);
679 let screen_top = self
680 .scroll_manager
681 .anchor
682 .anchor
683 .to_display_point(&snapshot);
684
685 if screen_top > newest_head {
686 return Ordering::Less;
687 }
688
689 if let Some(visible_lines) = self.visible_line_count() {
690 if newest_head.row() <= DisplayRow(screen_top.row().0 + visible_lines as u32) {
691 return Ordering::Equal;
692 }
693 }
694
695 Ordering::Greater
696 }
697
698 pub fn read_scroll_position_from_db(
699 &mut self,
700 item_id: u64,
701 workspace_id: WorkspaceId,
702 window: &mut Window,
703 cx: &mut Context<Editor>,
704 ) {
705 let scroll_position = DB.get_scroll_position(item_id, workspace_id);
706 if let Ok(Some((top_row, x, y))) = scroll_position {
707 let top_anchor = self
708 .buffer()
709 .read(cx)
710 .snapshot(cx)
711 .anchor_at(Point::new(top_row, 0), Bias::Left);
712 let scroll_anchor = ScrollAnchor {
713 offset: gpui::Point::new(x, y),
714 anchor: top_anchor,
715 };
716 self.set_scroll_anchor(scroll_anchor, window, cx);
717 }
718 }
719}