scroll.rs

  1pub mod actions;
  2pub mod autoscroll;
  3pub mod scroll_amount;
  4
  5use std::{
  6    cmp::Ordering,
  7    time::{Duration, Instant},
  8};
  9
 10use gpui::{
 11    geometry::vector::{vec2f, Vector2F},
 12    AppContext, Axis, Task, ViewContext,
 13};
 14use language::{Bias, Point};
 15use util::ResultExt;
 16use workspace::WorkspaceId;
 17
 18use crate::{
 19    display_map::{DisplaySnapshot, ToDisplayPoint},
 20    hover_popover::hide_hover,
 21    persistence::DB,
 22    Anchor, DisplayPoint, Editor, EditorMode, Event, MultiBufferSnapshot, ToPoint,
 23};
 24
 25use self::{
 26    autoscroll::{Autoscroll, AutoscrollStrategy},
 27    scroll_amount::ScrollAmount,
 28};
 29
 30pub const SCROLL_EVENT_SEPARATION: Duration = Duration::from_millis(28);
 31const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
 32
 33#[derive(Default)]
 34pub struct ScrollbarAutoHide(pub bool);
 35
 36#[derive(Clone, Copy, Debug, PartialEq)]
 37pub struct ScrollAnchor {
 38    pub offset: Vector2F,
 39    pub top_anchor: Anchor,
 40}
 41
 42impl ScrollAnchor {
 43    fn new() -> Self {
 44        Self {
 45            offset: Vector2F::zero(),
 46            top_anchor: Anchor::min(),
 47        }
 48    }
 49
 50    pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> Vector2F {
 51        let mut scroll_position = self.offset;
 52        if self.top_anchor != Anchor::min() {
 53            let scroll_top = self.top_anchor.to_display_point(snapshot).row() as f32;
 54            scroll_position.set_y(scroll_top + scroll_position.y());
 55        } else {
 56            scroll_position.set_y(0.);
 57        }
 58        scroll_position
 59    }
 60
 61    pub fn top_row(&self, buffer: &MultiBufferSnapshot) -> u32 {
 62        self.top_anchor.to_point(buffer).row
 63    }
 64}
 65
 66#[derive(Clone, Copy, Debug)]
 67pub struct OngoingScroll {
 68    last_event: Instant,
 69    axis: Option<Axis>,
 70}
 71
 72impl OngoingScroll {
 73    fn new() -> Self {
 74        Self {
 75            last_event: Instant::now() - SCROLL_EVENT_SEPARATION,
 76            axis: None,
 77        }
 78    }
 79
 80    pub fn filter(&self, delta: &mut Vector2F) -> Option<Axis> {
 81        const UNLOCK_PERCENT: f32 = 1.9;
 82        const UNLOCK_LOWER_BOUND: f32 = 6.;
 83        let mut axis = self.axis;
 84
 85        let x = delta.x().abs();
 86        let y = delta.y().abs();
 87        let duration = Instant::now().duration_since(self.last_event);
 88        if duration > SCROLL_EVENT_SEPARATION {
 89            //New ongoing scroll will start, determine axis
 90            axis = if x <= y {
 91                Some(Axis::Vertical)
 92            } else {
 93                Some(Axis::Horizontal)
 94            };
 95        } else if x.max(y) >= UNLOCK_LOWER_BOUND {
 96            //Check if the current ongoing will need to unlock
 97            match axis {
 98                Some(Axis::Vertical) => {
 99                    if x > y && x >= y * UNLOCK_PERCENT {
100                        axis = None;
101                    }
102                }
103
104                Some(Axis::Horizontal) => {
105                    if y > x && y >= x * UNLOCK_PERCENT {
106                        axis = None;
107                    }
108                }
109
110                None => {}
111            }
112        }
113
114        match axis {
115            Some(Axis::Vertical) => *delta = vec2f(0., delta.y()),
116            Some(Axis::Horizontal) => *delta = vec2f(delta.x(), 0.),
117            None => {}
118        }
119
120        axis
121    }
122}
123
124pub struct ScrollManager {
125    vertical_scroll_margin: f32,
126    anchor: ScrollAnchor,
127    ongoing: OngoingScroll,
128    autoscroll_request: Option<(Autoscroll, bool)>,
129    last_autoscroll: Option<(Vector2F, f32, f32, AutoscrollStrategy)>,
130    show_scrollbars: bool,
131    hide_scrollbar_task: Option<Task<()>>,
132    visible_line_count: Option<f32>,
133}
134
135impl ScrollManager {
136    pub fn new() -> Self {
137        ScrollManager {
138            vertical_scroll_margin: 3.0,
139            anchor: ScrollAnchor::new(),
140            ongoing: OngoingScroll::new(),
141            autoscroll_request: None,
142            show_scrollbars: true,
143            hide_scrollbar_task: None,
144            last_autoscroll: None,
145            visible_line_count: None,
146        }
147    }
148
149    pub fn clone_state(&mut self, other: &Self) {
150        self.anchor = other.anchor;
151        self.ongoing = other.ongoing;
152    }
153
154    pub fn anchor(&self) -> ScrollAnchor {
155        self.anchor
156    }
157
158    pub fn ongoing_scroll(&self) -> OngoingScroll {
159        self.ongoing
160    }
161
162    pub fn update_ongoing_scroll(&mut self, axis: Option<Axis>) {
163        self.ongoing.last_event = Instant::now();
164        self.ongoing.axis = axis;
165    }
166
167    pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> Vector2F {
168        self.anchor.scroll_position(snapshot)
169    }
170
171    fn set_scroll_position(
172        &mut self,
173        scroll_position: Vector2F,
174        map: &DisplaySnapshot,
175        local: bool,
176        workspace_id: Option<i64>,
177        cx: &mut ViewContext<Editor>,
178    ) {
179        let (new_anchor, top_row) = if scroll_position.y() <= 0. {
180            (
181                ScrollAnchor {
182                    top_anchor: Anchor::min(),
183                    offset: scroll_position.max(vec2f(0., 0.)),
184                },
185                0,
186            )
187        } else {
188            let scroll_top_buffer_point =
189                DisplayPoint::new(scroll_position.y() as u32, 0).to_point(&map);
190            let top_anchor = map
191                .buffer_snapshot
192                .anchor_at(scroll_top_buffer_point, Bias::Right);
193
194            (
195                ScrollAnchor {
196                    top_anchor,
197                    offset: vec2f(
198                        scroll_position.x(),
199                        scroll_position.y() - top_anchor.to_display_point(&map).row() as f32,
200                    ),
201                },
202                scroll_top_buffer_point.row,
203            )
204        };
205
206        self.set_anchor(new_anchor, top_row, local, workspace_id, cx);
207    }
208
209    fn set_anchor(
210        &mut self,
211        anchor: ScrollAnchor,
212        top_row: u32,
213        local: bool,
214        workspace_id: Option<i64>,
215        cx: &mut ViewContext<Editor>,
216    ) {
217        self.anchor = anchor;
218        cx.emit(Event::ScrollPositionChanged { local });
219        self.show_scrollbar(cx);
220        self.autoscroll_request.take();
221        if let Some(workspace_id) = workspace_id {
222            let item_id = cx.view_id();
223
224            cx.background()
225                .spawn(async move {
226                    DB.save_scroll_position(
227                        item_id,
228                        workspace_id,
229                        top_row,
230                        anchor.offset.x(),
231                        anchor.offset.y(),
232                    )
233                    .await
234                    .log_err()
235                })
236                .detach()
237        }
238        cx.notify();
239    }
240
241    pub fn show_scrollbar(&mut self, cx: &mut ViewContext<Editor>) {
242        if !self.show_scrollbars {
243            self.show_scrollbars = true;
244            cx.notify();
245        }
246
247        if cx.default_global::<ScrollbarAutoHide>().0 {
248            self.hide_scrollbar_task = Some(cx.spawn(|editor, mut cx| async move {
249                cx.background().timer(SCROLLBAR_SHOW_INTERVAL).await;
250                editor
251                    .update(&mut cx, |editor, cx| {
252                        editor.scroll_manager.show_scrollbars = false;
253                        cx.notify();
254                    })
255                    .log_err();
256            }));
257        } else {
258            self.hide_scrollbar_task = None;
259        }
260    }
261
262    pub fn scrollbars_visible(&self) -> bool {
263        self.show_scrollbars
264    }
265
266    pub fn has_autoscroll_request(&self) -> bool {
267        self.autoscroll_request.is_some()
268    }
269
270    pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
271        if max < self.anchor.offset.x() {
272            self.anchor.offset.set_x(max);
273            true
274        } else {
275            false
276        }
277    }
278}
279
280impl Editor {
281    pub fn vertical_scroll_margin(&mut self) -> usize {
282        self.scroll_manager.vertical_scroll_margin as usize
283    }
284
285    pub fn set_vertical_scroll_margin(&mut self, margin_rows: usize, cx: &mut ViewContext<Self>) {
286        self.scroll_manager.vertical_scroll_margin = margin_rows as f32;
287        cx.notify();
288    }
289
290    pub fn visible_line_count(&self) -> Option<f32> {
291        self.scroll_manager.visible_line_count
292    }
293
294    pub(crate) fn set_visible_line_count(&mut self, lines: f32) {
295        self.scroll_manager.visible_line_count = Some(lines)
296    }
297
298    pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
299        self.set_scroll_position_internal(scroll_position, true, cx);
300    }
301
302    pub(crate) fn set_scroll_position_internal(
303        &mut self,
304        scroll_position: Vector2F,
305        local: bool,
306        cx: &mut ViewContext<Self>,
307    ) {
308        let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
309
310        hide_hover(self, cx);
311        let workspace_id = self.workspace.as_ref().map(|workspace| workspace.1);
312        self.scroll_manager
313            .set_scroll_position(scroll_position, &map, local, workspace_id, cx);
314    }
315
316    pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
318        self.scroll_manager.anchor.scroll_position(&display_map)
319    }
320
321    pub fn set_scroll_anchor(&mut self, scroll_anchor: ScrollAnchor, cx: &mut ViewContext<Self>) {
322        hide_hover(self, cx);
323        let workspace_id = self.workspace.as_ref().map(|workspace| workspace.1);
324        let top_row = scroll_anchor
325            .top_anchor
326            .to_point(&self.buffer().read(cx).snapshot(cx))
327            .row;
328        self.scroll_manager
329            .set_anchor(scroll_anchor, top_row, true, workspace_id, cx);
330    }
331
332    pub(crate) fn set_scroll_anchor_remote(
333        &mut self,
334        scroll_anchor: ScrollAnchor,
335        cx: &mut ViewContext<Self>,
336    ) {
337        hide_hover(self, cx);
338        let workspace_id = self.workspace.as_ref().map(|workspace| workspace.1);
339        let top_row = scroll_anchor
340            .top_anchor
341            .to_point(&self.buffer().read(cx).snapshot(cx))
342            .row;
343        self.scroll_manager
344            .set_anchor(scroll_anchor, top_row, false, workspace_id, cx);
345    }
346
347    pub fn scroll_screen(&mut self, amount: &ScrollAmount, cx: &mut ViewContext<Self>) {
348        if matches!(self.mode, EditorMode::SingleLine) {
349            cx.propagate_action();
350            return;
351        }
352
353        if self.take_rename(true, cx).is_some() {
354            return;
355        }
356
357        if amount.move_context_menu_selection(self, cx) {
358            return;
359        }
360
361        let cur_position = self.scroll_position(cx);
362        let new_pos = cur_position + vec2f(0., amount.lines(self) - 1.);
363        self.set_scroll_position(new_pos, cx);
364    }
365
366    /// Returns an ordering. The newest selection is:
367    ///     Ordering::Equal => on screen
368    ///     Ordering::Less => above the screen
369    ///     Ordering::Greater => below the screen
370    pub fn newest_selection_on_screen(&self, cx: &mut AppContext) -> Ordering {
371        let snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
372        let newest_head = self
373            .selections
374            .newest_anchor()
375            .head()
376            .to_display_point(&snapshot);
377        let screen_top = self
378            .scroll_manager
379            .anchor
380            .top_anchor
381            .to_display_point(&snapshot);
382
383        if screen_top > newest_head {
384            return Ordering::Less;
385        }
386
387        if let Some(visible_lines) = self.visible_line_count() {
388            if newest_head.row() < screen_top.row() + visible_lines as u32 {
389                return Ordering::Equal;
390            }
391        }
392
393        Ordering::Greater
394    }
395
396    pub fn read_scroll_position_from_db(
397        &mut self,
398        item_id: usize,
399        workspace_id: WorkspaceId,
400        cx: &mut ViewContext<Editor>,
401    ) {
402        let scroll_position = DB.get_scroll_position(item_id, workspace_id);
403        if let Ok(Some((top_row, x, y))) = scroll_position {
404            let top_anchor = self
405                .buffer()
406                .read(cx)
407                .snapshot(cx)
408                .anchor_at(Point::new(top_row as u32, 0), Bias::Left);
409            let scroll_anchor = ScrollAnchor {
410                offset: Vector2F::new(x, y),
411                top_anchor,
412            };
413            self.set_scroll_anchor(scroll_anchor, cx);
414        }
415    }
416}