scroll.rs

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