Skip to main content

cosmic/
scroll.rs

1use iced::mouse::ScrollDelta;
2use std::time::{Duration, Instant};
3
4// Number of scroll pixels before changing workspace
5const SCROLL_PIXELS: f32 = 24.0;
6
7// Timeout for scroll accumulation; older partial scroll is dropped
8const SCROLL_TIMEOUT: Duration = Duration::from_millis(100);
9
10/// A scroll delta with discrete integer deltas
11#[derive(Debug, Default, Clone, Copy)]
12pub struct DiscreteScrollDelta {
13    pub x: isize,
14    pub y: isize,
15}
16
17/// Helper for accumulating and converting pixel/line scrolls into and integer
18/// delta between discrete options.
19#[derive(Debug, Default)]
20pub struct DiscreteScrollState {
21    x: Scroll,
22    y: Scroll,
23    rate_limit: Option<Duration>,
24}
25
26impl DiscreteScrollState {
27    /// Set a rate limit. If set, a call to `update()` will only not produce
28    /// values other than 1, -1, or 0 and a non-zero return value will not
29    /// occur more frequently than this duration.
30    pub fn rate_limit(mut self, rate_limit: Option<Duration>) -> Self {
31        self.rate_limit = rate_limit;
32        self
33    }
34
35    /// Reset, clearing any acculuated scroll events that haven't been
36    /// converted to discrete events yet.
37    pub fn reset(&mut self) {
38        self.x.reset();
39        self.y.reset();
40    }
41
42    /// Accumulate delta with a timer
43    pub fn update(&mut self, delta: ScrollDelta) -> DiscreteScrollDelta {
44        let (x, y) = match delta {
45            ScrollDelta::Pixels { x, y } => (x / SCROLL_PIXELS, y / SCROLL_PIXELS),
46            ScrollDelta::Lines { x, y } => (x, y),
47        };
48
49        DiscreteScrollDelta {
50            x: self.x.update(x, self.rate_limit),
51            y: self.y.update(y, self.rate_limit),
52        }
53    }
54}
55
56/// Scroll over a single axis
57#[derive(Debug, Default)]
58struct Scroll {
59    scroll: Option<(f32, Instant)>,
60    last_discrete: Option<Instant>,
61}
62
63impl Scroll {
64    fn reset(&mut self) {
65        *self = Default::default();
66    }
67
68    fn update(&mut self, delta: f32, rate_limit: Option<Duration>) -> isize {
69        if delta == 0. {
70            // If delta is 0, scroll is on other axis; clear accumulated scroll
71            self.reset();
72            0
73        } else {
74            let previous_scroll = if let Some((scroll, last_scroll_time)) = self.scroll {
75                if last_scroll_time.elapsed() > SCROLL_TIMEOUT {
76                    0.
77                } else {
78                    scroll
79                }
80            } else {
81                0.
82            };
83
84            let scroll = previous_scroll + delta;
85
86            if self
87                .last_discrete
88                .is_some_and(|time| time.elapsed() < rate_limit.unwrap_or(Duration::ZERO))
89            {
90                // If rate limit is hit, continute accumulating, but don't return
91                // a discrete event yet.
92                self.scroll = Some((scroll, Instant::now()));
93                0
94            } else {
95                // Return integer part of scroll, and keep remainder
96                self.scroll = Some((scroll.fract(), Instant::now()));
97                let discrete = scroll.trunc() as isize;
98                if discrete != 0 {
99                    self.last_discrete = Some(Instant::now());
100                }
101                if rate_limit.is_some() {
102                    // If we are rate limiting, don't return multiple discrete events
103                    // at once; drop extras.
104                    discrete.signum()
105                } else {
106                    discrete
107                }
108            }
109        }
110    }
111}