Skip to main content

nsh_core/scroll/
wheel_glide.rs

1//! A mouse wheel's smooth scroll, as Chromium animates one
2//! (`cc/animation/scroll_offset_animation_curve.cc`, `ScrollType::kMouseWheel`):
3//! each step eases in and out (`cubic-bezier(0.42, 0, 0.58, 1)`) to its
4//! target over 100–200 ms, shorter the farther it goes; a step during the
5//! glide moves the target on by its delta and starts a new segment from
6//! where the glide is, at the speed it has there, so a run of steps flows
7//! into one motion instead of restarting each time. Without it every step
8//! landed at once, a jump per event. Times are ms, offsets points.
9//!
10//! `smoothWheel` glides a scroll view's notches with it on every desktop:
11//! the shared scroll views (Linux, Windows, GPUI: [`super::wheel_smooth`])
12//! and macOS's own.
13
14use crate::geometry::{Point, Points, point};
15
16/// An offset or a change of one (points).
17#[derive(Debug, Default, Clone, Copy, PartialEq)]
18struct Offset {
19    x: f32,
20    y: f32,
21}
22
23impl Offset {
24    fn lerp(self, to: Self, k: f32) -> Self {
25        Self {
26            x: self.x + (to.x - self.x) * k,
27            y: self.y + (to.y - self.y) * k,
28        }
29    }
30}
31
32impl std::ops::Add for Offset {
33    type Output = Self;
34
35    fn add(self, o: Self) -> Self {
36        Self {
37            x: self.x + o.x,
38            y: self.y + o.y,
39        }
40    }
41}
42
43impl std::ops::Sub for Offset {
44    type Output = Self;
45
46    fn sub(self, o: Self) -> Self {
47        Self {
48            x: self.x - o.x,
49            y: self.y - o.y,
50        }
51    }
52}
53
54impl From<Point<Points>> for Offset {
55    fn from(p: Point<Points>) -> Self {
56        Self { x: p.x.0, y: p.y.0 }
57    }
58}
59
60impl From<Offset> for Point<Points> {
61    fn from(o: Offset) -> Self {
62        point(Points(o.x), Points(o.y))
63    }
64}
65
66/// One 60 Hz frame (ms): Chromium counts its durations in them.
67const FRAME: f64 = 1000.0 / 60.0;
68/// Chromium's `kInverseDelta*`: steps up to 120 points take 12 frames,
69/// from 480 points 6, linearly between.
70const RAMP_START: f64 = 120.0;
71const RAMP_END: f64 = 480.0;
72const MIN_FRAMES: f64 = 6.0;
73const MAX_FRAMES: f64 = 12.0;
74/// The ease-in-out curve's control points (`kEaseInOutControlPoints`).
75const X1: f64 = 0.42;
76const X2: f64 = 0.58;
77const Y2: f64 = 1.0;
78/// Chromium's `kEpsilon` (points, and seconds for durations).
79const EPSILON: f64 = 0.01;
80
81/// The glide in flight. `target` is kept by the caller (the wheel phase's
82/// `raw`), so a shift of the content moves it with the rest.
83#[derive(Debug, Default, Clone, Copy, PartialEq)]
84pub struct Glide {
85    /// Where the current segment starts.
86    initial: Offset,
87    /// The curve's time origin (ms, the frames' clock).
88    start: f64,
89    /// When the current segment began, from `start`.
90    retarget: f64,
91    /// When it ends, from `start`.
92    total: f64,
93    /// The segment's first control point's y: 0, or what carries the
94    /// previous segment's speed on.
95    y1: f64,
96}
97
98/// The larger component, with its sign (`MaximumDimension`).
99fn major(d: Offset) -> f64 {
100    if d.x.abs() > d.y.abs() {
101        d.x as f64
102    } else {
103        d.y as f64
104    }
105}
106
107/// How long a segment of `delta` takes, less what it is late by
108/// (`EaseInOutSegmentDuration`, `kInverseDelta`).
109fn segment(delta: Offset, late: f64) -> f64 {
110    let slope = (MIN_FRAMES - MAX_FRAMES) / (RAMP_END - RAMP_START);
111    let offset = MAX_FRAMES - RAMP_START * slope;
112    let frames = (offset + major(delta).abs() * slope).clamp(MIN_FRAMES, MAX_FRAMES);
113    (frames * FRAME - late).max(0.0)
114}
115
116impl Glide {
117    /// A glide from `initial` to `target` starting `now`: one frame in
118    /// already, as Chromium starts it (`animation_start_offset`), so the
119    /// first frame drawn has moved.
120    pub fn new(initial: Point<Points>, target: Point<Points>, now: f64) -> Self {
121        let (initial, target) = (Offset::from(initial), Offset::from(target));
122        Self {
123            initial,
124            start: now - FRAME,
125            retarget: 0.0,
126            total: segment(target - initial, 0.0),
127            y1: 0.0,
128        }
129    }
130
131    /// When it arrives (ms, the frames' clock).
132    pub fn end(&self) -> f64 {
133        self.start + self.total
134    }
135
136    /// Moved with the content by `d` (`ApplyAdjustment`).
137    pub fn shifted(self, d: Point<Points>) -> Self {
138        Self {
139            initial: self.initial + d.into(),
140            ..self
141        }
142    }
143
144    fn curve(&self) -> Bezier {
145        Bezier::new(X1, self.y1, X2, Y2)
146    }
147
148    /// Where it is at `now` on its way to `target` (`GetValue`).
149    pub fn value(&self, target: Point<Points>, now: f64) -> Point<Points> {
150        self.at(target.into(), now).into()
151    }
152
153    fn at(&self, target: Offset, now: f64) -> Offset {
154        let duration = self.total - self.retarget;
155        let t = now - self.start - self.retarget;
156        if duration <= 0.0 || t >= duration {
157            return target;
158        }
159        if t <= 0.0 {
160            return self.initial;
161        }
162        let p = self.curve().solve(t / duration);
163        self.initial.lerp(target, p as f32)
164    }
165
166    /// Its speed at curve time `t` (points per second, `CalculateVelocity`).
167    fn velocity(&self, target: Offset, t: f64) -> f64 {
168        let duration = self.total - self.retarget;
169        if duration <= 0.0 {
170            return 0.0;
171        }
172        let slope = self.curve().velocity((t - self.retarget) / duration);
173        slope * (major(target - self.initial) / (duration / 1000.0))
174    }
175
176    /// A step during the glide moved its target from `old` to `new` at
177    /// `now` (`UpdateTarget`).
178    pub fn retargeted(self, old: Point<Points>, new: Point<Points>, now: f64) -> Self {
179        self.moved_on(old.into(), new.into(), now)
180    }
181
182    fn moved_on(mut self, old: Offset, new: Offset, now: f64) -> Self {
183        let mut t = now - self.start;
184        let late = (self.retarget - t).max(0.0);
185        t = t.max(self.retarget);
186        if major(old - new).abs() < EPSILON {
187            return self;
188        }
189        let here = self.at(old, self.start + t);
190        let delta = new - here;
191        if major(delta).abs() < EPSILON {
192            self.initial = here;
193            self.retarget = t;
194            self.total = t;
195            return self;
196        }
197        let old_duration = self.total - self.retarget;
198        if old_duration <= 0.0 {
199            self.total = segment(delta, late);
200            return self;
201        }
202        let velocity = self.velocity(old, t);
203        // The speed it has bounds the new segment's length (less "rubber
204        // band" when a fast glide gets a short step)
205        let bound = if velocity.abs() < EPSILON {
206            f64::INFINITY
207        } else {
208            let b = major(delta) / velocity * 2.5 * 1000.0;
209            if b < 0.0 { f64::INFINITY } else { b }
210        };
211        let duration = segment(delta, late).min(bound);
212        if duration / 1000.0 < EPSILON {
213            self.total = t;
214            return self;
215        }
216        // The new segment starts at the speed the old one had there
217        let slope = (velocity * (duration / 1000.0) / major(delta)).clamp(-1000.0, 1000.0);
218        self.y1 = X1 * slope;
219        self.initial = here;
220        self.retarget = t;
221        self.total = t + duration;
222        self
223    }
224}
225
226/// A cubic Bézier timing function from (0, 0) to (1, 1) (`gfx::CubicBezier`).
227struct Bezier {
228    ax: f64,
229    bx: f64,
230    cx: f64,
231    ay: f64,
232    by: f64,
233    cy: f64,
234}
235
236impl Bezier {
237    fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
238        let cx = 3.0 * x1;
239        let bx = 3.0 * (x2 - x1) - cx;
240        let cy = 3.0 * y1;
241        let by = 3.0 * (y2 - y1) - cy;
242        Self {
243            ax: 1.0 - cx - bx,
244            bx,
245            cx,
246            ay: 1.0 - cy - by,
247            by,
248            cy,
249        }
250    }
251
252    fn x(&self, t: f64) -> f64 {
253        ((self.ax * t + self.bx) * t + self.cx) * t
254    }
255
256    fn y(&self, t: f64) -> f64 {
257        ((self.ay * t + self.by) * t + self.cy) * t
258    }
259
260    fn dx(&self, t: f64) -> f64 {
261        (3.0 * self.ax * t + 2.0 * self.bx) * t + self.cx
262    }
263
264    fn dy(&self, t: f64) -> f64 {
265        (3.0 * self.ay * t + 2.0 * self.by) * t + self.cy
266    }
267
268    /// The curve's parameter where its x is `x`: Newton, then bisection.
269    fn t_for(&self, x: f64) -> f64 {
270        let mut t = x;
271        for _ in 0..8 {
272            let err = self.x(t) - x;
273            if err.abs() < 1e-7 {
274                return t;
275            }
276            let d = self.dx(t);
277            if d.abs() < 1e-6 {
278                break;
279            }
280            t -= err / d;
281        }
282        let (mut lo, mut hi) = (0.0, 1.0);
283        t = x;
284        while lo < hi {
285            let v = self.x(t);
286            if (v - x).abs() < 1e-7 {
287                return t;
288            }
289            if x > v {
290                lo = t
291            } else {
292                hi = t
293            }
294            t = (hi - lo) / 2.0 + lo;
295            if hi - lo < 1e-9 {
296                break;
297            }
298        }
299        t
300    }
301
302    /// Progress at time fraction `x`.
303    fn solve(&self, x: f64) -> f64 {
304        self.y(self.t_for(x.clamp(0.0, 1.0)))
305    }
306
307    /// The curve's slope (progress per time fraction) at `x`.
308    fn velocity(&self, x: f64) -> f64 {
309        let t = self.t_for(x.clamp(0.0, 1.0));
310        let dx = self.dx(t);
311        if dx.abs() < 1e-9 {
312            0.0
313        } else {
314            self.dy(t) / dx
315        }
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    fn y(v: f32) -> Offset {
324        Offset { x: 0.0, y: v }
325    }
326
327    #[test]
328    fn durations_follow_the_step() {
329        let d = |v: f32| segment(y(v), 0.0);
330        assert!((d(40.0) - 200.0).abs() < 0.01);
331        assert!((d(300.0) - 150.0).abs() < 0.01);
332        assert!((d(1000.0) - 100.0).abs() < 0.01);
333    }
334
335    #[test]
336    fn eases_in_and_out_and_arrives() {
337        let to = y(100.0);
338        let g = Glide::new(Offset::default().into(), to.into(), 0.0);
339        assert_eq!(g.at(to, -FRAME), Offset::default());
340        let mid = g.at(to, g.start + g.total / 2.0).y;
341        assert!((mid - 50.0).abs() < 0.5);
342        assert_eq!(g.at(to, g.end()), to);
343    }
344
345    #[test]
346    fn a_step_mid_glide_keeps_its_speed() {
347        let (a, b) = (y(100.0), y(200.0));
348        let g = Glide::new(Offset::default().into(), a.into(), 0.0);
349        let now = g.start + g.total / 2.0;
350        let before = g.velocity(a, now - g.start);
351        let h = g.moved_on(a, b, now);
352        assert!((h.at(b, now).y - g.at(a, now).y).abs() < 0.01);
353        let after = h.velocity(b, now - h.start);
354        assert!((after - before).abs() / before < 0.02, "{before} {after}");
355        assert_eq!(h.at(b, h.end()), b);
356    }
357}