gpui-mobile 0.1.0

Mobile platform support for GPUI — iOS (Metal/Blade) and Android (wgpu/Vulkan)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Momentum scrolling (inertia / fling) for touch-based platforms.
//!
//! When a user drags their finger across the screen and lifts it, native
//! platforms continue scrolling with a decelerating velocity — this is
//! "momentum scrolling" or "fling". Without it, scrolling feels sluggish
//! and stops dead the moment the finger lifts.
//!
//! This module provides two components:
//!
//! 1. **`VelocityTracker`** — records recent touch positions and computes
//!    the release velocity when the finger lifts.
//!
//! 2. **`MomentumScroller`** — takes the release velocity and produces
//!    a stream of decelerating scroll deltas that should be emitted as
//!    `ScrollWheel` events on each frame tick.
//!
//! # Usage (platform integration)
//!
//! ```ignore
//! let mut tracker = VelocityTracker::new();
//! let mut scroller = MomentumScroller::new();
//!
//! // On each touch move:
//! tracker.record(logical_x, logical_y);
//!
//! // On finger lift:
//! let (vx, vy) = tracker.velocity();
//! scroller.fling(vx, vy, last_position);
//! tracker.reset();
//!
//! // On each frame tick (CADisplayLink / Choreographer):
//! if let Some(delta) = scroller.step() {
//!     emit(ScrollWheelEvent { delta, phase: Moved, .. });
//! }
//! // When step() returns None the fling is finished.
//! ```

use std::time::Instant;

// ── Configuration ────────────────────────────────────────────────────────────

/// Friction coefficient per second.  Higher = stops faster.
/// iOS UIScrollView uses ≈0.998 per-millisecond which works out to roughly
/// e^(−3.0·t) in continuous time.  We use a similar value tuned so that a
/// moderate flick (~1500 px/s) scrolls about 3–4 screen-lengths before
/// stopping — matching native feel on both iOS and Android.
/// Deceleration rate per millisecond.  Android's native `OverScroller` uses
/// a ViewConfiguration-derived friction that corresponds to roughly 0.985
/// per ms in continuous time.  iOS `UIScrollView` with its default
/// `decelerationRate = .normal` (0.998) is slightly floatier but still
/// much snappier than our previous 0.997.
///
/// **0.985** gives a moderate-fast fling (~2000 px/s) about 1.5–2 screen
/// lengths of travel before stopping — close to native Android feel.
/// The previous value of 0.997 was far too close to 1.0 (barely any
/// friction), making scrolls feel floaty and laggy.
const DECELERATION_RATE: f32 = 0.985;

/// Below this velocity (px/s) we consider the fling finished.
/// Raised from 20 → 50 to cut the long, barely-visible tail of the
/// deceleration curve that made scrolling feel like it "stuck" at the end.
const MIN_VELOCITY: f32 = 50.0;

/// Maximum velocity (px/s) we allow.  Caps extremely fast flings so they
/// don't overshoot wildly.
const MAX_VELOCITY: f32 = 8000.0;

/// Maximum number of recent touch samples kept for velocity estimation.
const MAX_SAMPLES: usize = 20;

/// Only samples within this time window (seconds) are used for velocity
/// estimation.  Older samples are ignored so that a slow-then-fast gesture
/// correctly captures the fast release velocity.
///
/// Widened from 100 ms → 150 ms to capture slightly more of the gesture
/// for smoother velocity estimation, especially on devices where touch
/// events may be batched or delayed under load.
const VELOCITY_WINDOW_SECS: f64 = 0.15; // 150 ms

/// Minimum number of samples needed to compute a meaningful velocity.
const MIN_SAMPLES_FOR_VELOCITY: usize = 2;

// ── VelocityTracker ──────────────────────────────────────────────────────────

/// A sample recorded during a touch drag.
#[derive(Clone, Copy, Debug)]
struct Sample {
    x: f32,
    y: f32,
    time: Instant,
}

/// Tracks recent touch positions and computes the release velocity.
///
/// Call [`record`](Self::record) on every `ACTION_MOVE` / `UITouchPhase::Moved`
/// event, then call [`velocity`](Self::velocity) when the finger lifts to get
/// the fling velocity in logical pixels per second.
pub struct VelocityTracker {
    /// Ring buffer of recent samples.
    samples: [Option<Sample>; MAX_SAMPLES],
    /// Next write index into `samples`.
    index: usize,
    /// Total number of samples recorded (may exceed MAX_SAMPLES).
    count: usize,
}

impl VelocityTracker {
    pub fn new() -> Self {
        Self {
            samples: [None; MAX_SAMPLES],
            index: 0,
            count: 0,
        }
    }

    /// Record a touch position.  Call on every move event.
    pub fn record(&mut self, x: f32, y: f32) {
        self.samples[self.index] = Some(Sample {
            x,
            y,
            time: Instant::now(),
        });
        self.index = (self.index + 1) % MAX_SAMPLES;
        self.count += 1;
    }

    /// Compute the release velocity in logical px/s.
    ///
    /// Uses a least-squares fit over recent samples within
    /// [`VELOCITY_WINDOW_SECS`] to produce a smooth estimate.
    /// Returns `(vx, vy)`.
    pub fn velocity(&self) -> (f32, f32) {
        let now = Instant::now();

        // Collect recent samples within the velocity window.
        let mut recent: Vec<&Sample> = Vec::with_capacity(MAX_SAMPLES);
        for slot in &self.samples {
            if let Some(s) = slot {
                let age = now.duration_since(s.time).as_secs_f64();
                if age <= VELOCITY_WINDOW_SECS {
                    recent.push(s);
                }
            }
        }

        if recent.len() < MIN_SAMPLES_FOR_VELOCITY {
            return (0.0, 0.0);
        }

        // Sort by time ascending.
        recent.sort_by(|a, b| a.time.cmp(&b.time));

        // Simple finite-difference: use oldest and newest in the window.
        let first = recent[0];
        let last = recent[recent.len() - 1];
        let dt = last.time.duration_since(first.time).as_secs_f64();

        if dt < 1e-6 {
            return (0.0, 0.0);
        }

        let vx = ((last.x - first.x) as f64 / dt) as f32;
        let vy = ((last.y - first.y) as f64 / dt) as f32;

        // For a more robust estimate with many samples, do a weighted
        // linear regression giving more weight to recent samples.
        if recent.len() >= 4 {
            let (wvx, wvy) = weighted_velocity(&recent);
            return (clamp_velocity(wvx), clamp_velocity(wvy));
        }

        (clamp_velocity(vx), clamp_velocity(vy))
    }

    /// Reset the tracker for a new gesture.
    pub fn reset(&mut self) {
        self.samples = [None; MAX_SAMPLES];
        self.index = 0;
        self.count = 0;
    }
}

/// Weighted least-squares velocity: more recent samples have higher weight.
fn weighted_velocity(samples: &[&Sample]) -> (f32, f32) {
    if samples.len() < 2 {
        return (0.0, 0.0);
    }

    let t0 = samples[0].time;
    let n = samples.len();

    // Weight increases linearly with index so that the most recent samples
    // dominate.  This prevents a slow start from dragging down a fast finish.
    let mut sum_w = 0.0_f64;
    let mut sum_wt = 0.0_f64;
    let mut sum_wt2 = 0.0_f64;
    let mut sum_wx = 0.0_f64;
    let mut sum_wy = 0.0_f64;
    let mut sum_wtx = 0.0_f64;
    let mut sum_wty = 0.0_f64;

    for (i, s) in samples.iter().enumerate() {
        let t = s.time.duration_since(t0).as_secs_f64();
        let w = (i + 1) as f64; // linearly increasing weight

        sum_w += w;
        sum_wt += w * t;
        sum_wt2 += w * t * t;
        sum_wx += w * s.x as f64;
        sum_wy += w * s.y as f64;
        sum_wtx += w * t * s.x as f64;
        sum_wty += w * t * s.y as f64;
    }

    let denom = sum_w * sum_wt2 - sum_wt * sum_wt;
    if denom.abs() < 1e-12 {
        // Degenerate — all samples at the same time.
        let first = samples[0];
        let last = samples[n - 1];
        let dt = last.time.duration_since(first.time).as_secs_f64();
        if dt < 1e-6 {
            return (0.0, 0.0);
        }
        return (
            ((last.x - first.x) as f64 / dt) as f32,
            ((last.y - first.y) as f64 / dt) as f32,
        );
    }

    // Slope of weighted linear fit = velocity in px/s.
    let vx = (sum_w * sum_wtx - sum_wt * sum_wx) / denom;
    let vy = (sum_w * sum_wty - sum_wt * sum_wy) / denom;

    (vx as f32, vy as f32)
}

fn clamp_velocity(v: f32) -> f32 {
    v.clamp(-MAX_VELOCITY, MAX_VELOCITY)
}

// ── MomentumScroller ─────────────────────────────────────────────────────────

/// A momentum/inertia scroller that produces decelerating scroll deltas.
///
/// After calling [`fling`](Self::fling) with the release velocity, call
/// [`step`](Self::step) on every frame tick.  It returns `Some((dx, dy))`
/// as long as the scroller is animating, and `None` when finished.
pub struct MomentumScroller {
    /// Current velocity in logical px/s.
    vx: f32,
    vy: f32,
    /// Last position of the finger / last emitted position (logical px).
    last_x: f32,
    last_y: f32,
    /// Whether a fling is currently active.
    active: bool,
    /// Last step timestamp.
    last_time: Instant,
}

impl MomentumScroller {
    pub fn new() -> Self {
        Self {
            vx: 0.0,
            vy: 0.0,
            last_x: 0.0,
            last_y: 0.0,
            active: false,
            last_time: Instant::now(),
        }
    }

    /// Start a fling animation from the given velocity (px/s) and
    /// last finger position.
    pub fn fling(&mut self, vx: f32, vy: f32, last_x: f32, last_y: f32) {
        let speed = (vx * vx + vy * vy).sqrt();
        if speed < MIN_VELOCITY {
            self.active = false;
            return;
        }
        self.vx = vx;
        self.vy = vy;
        self.last_x = last_x;
        self.last_y = last_y;
        self.active = true;
        self.last_time = Instant::now();
    }

    /// Advance the momentum animation by one frame.
    ///
    /// Returns `Some(MomentumDelta)` — the scroll delta in logical pixels
    /// and the current position — or `None` if the fling has finished
    /// (velocity dropped below threshold).
    ///
    /// The caller should emit a `ScrollWheel` event with the returned delta.
    pub fn step(&mut self) -> Option<MomentumDelta> {
        if !self.active {
            return None;
        }

        let now = Instant::now();
        let dt = now.duration_since(self.last_time).as_secs_f64() as f32;
        self.last_time = now;

        // Guard against huge dt (e.g. app was suspended or a GC pause).
        // Cap at 50ms (~20 fps) instead of 100ms — if we've been stalled
        // that long the user probably noticed; don't teleport the content.
        let dt = dt.min(0.05);

        if dt < 1e-6 {
            return None;
        }

        // Apply exponential deceleration: v *= DECELERATION_RATE^(dt_ms)
        // where dt_ms = dt * 1000.
        let dt_ms = dt * 1000.0;
        let decay = DECELERATION_RATE.powf(dt_ms);

        // Compute displacement using the analytical integral of
        // v * r^t over [0, dt_ms]:
        //   ∫₀^{dt_ms} v·r^t dt = v · (r^dt_ms − 1) / ln(r)
        //
        // This is more accurate than the simple v*dt approximation,
        // especially during the high-velocity early phase where v*dt
        // overshoot can make scrolling feel jumpy.
        let ln_r = DECELERATION_RATE.ln();
        let displacement_factor = if ln_r.abs() > 1e-9 {
            (decay - 1.0) / (ln_r * 1000.0) // divide by 1000 to convert ms→s
        } else {
            dt // degenerate: r≈1, integral ≈ v*dt
        };

        let dx = self.vx * displacement_factor;
        let dy = self.vy * displacement_factor;

        // Now apply decay to velocity for the next frame.
        self.vx *= decay;
        self.vy *= decay;

        let speed = (self.vx * self.vx + self.vy * self.vy).sqrt();
        if speed < MIN_VELOCITY {
            self.active = false;
            // Include the final displacement so the last frame isn't lost.
            if dx.abs() < 0.1 && dy.abs() < 0.1 {
                return None;
            }
        }

        self.last_x += dx;
        self.last_y += dy;

        Some(MomentumDelta {
            dx,
            dy,
            position_x: self.last_x,
            position_y: self.last_y,
        })
    }

    /// Cancel any active fling (e.g. when a new touch begins).
    pub fn cancel(&mut self) {
        self.active = false;
        self.vx = 0.0;
        self.vy = 0.0;
    }

    /// Whether a fling animation is currently active.
    pub fn is_active(&self) -> bool {
        self.active
    }
}

/// The output of a single momentum step.
#[derive(Clone, Copy, Debug)]
pub struct MomentumDelta {
    /// Scroll delta X in logical pixels (positive = scroll right).
    pub dx: f32,
    /// Scroll delta Y in logical pixels (positive = scroll down).
    pub dy: f32,
    /// Current logical position X (for the ScrollWheel event's `position`).
    pub position_x: f32,
    /// Current logical position Y.
    pub position_y: f32,
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn velocity_tracker_no_samples() {
        let tracker = VelocityTracker::new();
        let (vx, vy) = tracker.velocity();
        assert_eq!(vx, 0.0);
        assert_eq!(vy, 0.0);
    }

    #[test]
    fn velocity_tracker_single_sample() {
        let mut tracker = VelocityTracker::new();
        tracker.record(100.0, 200.0);
        let (vx, vy) = tracker.velocity();
        // Only one sample → cannot compute velocity.
        assert_eq!(vx, 0.0);
        assert_eq!(vy, 0.0);
    }

    #[test]
    fn velocity_tracker_multiple_samples() {
        let mut tracker = VelocityTracker::new();
        // Simulate a ~1000 px/s vertical scroll by recording samples
        // spaced ~5 ms apart.
        for i in 0..10 {
            tracker.record(100.0, 100.0 + i as f32 * 5.0);
            thread::sleep(Duration::from_millis(5));
        }
        let (_vx, vy) = tracker.velocity();
        // We expect vy roughly around 1000 px/s (5 px / 5 ms = 1000 px/s).
        // Allow generous tolerance because thread::sleep is not precise.
        assert!(vy.abs() > 200.0, "vy={vy} should be > 200 px/s");
        assert!(vy > 0.0, "vy should be positive (scrolling down)");
    }

    #[test]
    fn velocity_tracker_reset() {
        let mut tracker = VelocityTracker::new();
        tracker.record(0.0, 0.0);
        thread::sleep(Duration::from_millis(5));
        tracker.record(50.0, 50.0);
        tracker.reset();
        let (vx, vy) = tracker.velocity();
        assert_eq!(vx, 0.0);
        assert_eq!(vy, 0.0);
    }

    #[test]
    fn velocity_clamped() {
        let mut tracker = VelocityTracker::new();
        // Two samples extremely close in time but far apart in space →
        // extremely high velocity that should be clamped.
        tracker.record(0.0, 0.0);
        // Record immediately (no sleep) — dt ≈ 0 → huge velocity.
        tracker.record(10000.0, 10000.0);
        thread::sleep(Duration::from_micros(100));
        tracker.record(20000.0, 20000.0);
        let (vx, vy) = tracker.velocity();
        assert!(vx.abs() <= MAX_VELOCITY, "vx should be clamped");
        assert!(vy.abs() <= MAX_VELOCITY, "vy should be clamped");
    }

    #[test]
    fn momentum_scroller_no_fling() {
        let mut scroller = MomentumScroller::new();
        assert!(!scroller.is_active());
        assert!(scroller.step().is_none());
    }

    #[test]
    fn momentum_scroller_below_threshold() {
        let mut scroller = MomentumScroller::new();
        // Velocity below MIN_VELOCITY → should not start.
        scroller.fling(5.0, 5.0, 100.0, 100.0);
        assert!(!scroller.is_active());
        assert!(scroller.step().is_none());
    }

    #[test]
    fn momentum_scroller_decelerates() {
        let mut scroller = MomentumScroller::new();
        scroller.fling(0.0, 2000.0, 100.0, 100.0);
        assert!(scroller.is_active());

        // Run for several "frames" (sleeping ~16ms each to simulate 60fps).
        // Because thread::sleep is imprecise, individual frame deltas can
        // jitter (a longer sleep → larger dt → bigger displacement even
        // though velocity is lower).  Instead of checking strict per-frame
        // monotonicity we verify:
        //   1. All deltas are non-negative (direction preserved).
        //   2. The first quarter's average delta > the last quarter's average
        //      (overall deceleration).
        //   3. The scroller eventually stops.
        let mut deltas = Vec::new();
        let mut total_dy = 0.0_f32;
        let mut frame_count = 0;

        loop {
            thread::sleep(Duration::from_millis(16));
            match scroller.step() {
                Some(delta) => {
                    // dy should be non-negative (scrolling down).
                    assert!(delta.dy >= 0.0, "dy should be >= 0, got {}", delta.dy);
                    deltas.push(delta.dy);
                    total_dy += delta.dy;
                    frame_count += 1;
                }
                None => break,
            }
            // Safety: don't run forever.
            if frame_count > 600 {
                break;
            }
        }

        assert!(!scroller.is_active());
        assert!(total_dy > 50.0, "total_dy={total_dy} should be > 50 px");
        assert!(frame_count > 5, "should have run for multiple frames");

        // Verify overall deceleration: the average delta in the first
        // quarter of frames should be larger than the last quarter.
        let q = deltas.len() / 4;
        if q > 0 {
            let first_avg: f32 = deltas[..q].iter().sum::<f32>() / q as f32;
            let last_avg: f32 = deltas[deltas.len() - q..].iter().sum::<f32>() / q as f32;
            assert!(
                first_avg > last_avg,
                "first quarter avg ({first_avg}) should be > last quarter avg ({last_avg})"
            );
        }
    }

    #[test]
    fn momentum_scroller_cancel() {
        let mut scroller = MomentumScroller::new();
        scroller.fling(0.0, 3000.0, 100.0, 100.0);
        assert!(scroller.is_active());

        thread::sleep(Duration::from_millis(16));
        assert!(scroller.step().is_some());

        scroller.cancel();
        assert!(!scroller.is_active());
        assert!(scroller.step().is_none());
    }

    #[test]
    fn momentum_scroller_fling_replaces_previous() {
        let mut scroller = MomentumScroller::new();
        scroller.fling(0.0, 2000.0, 100.0, 100.0);
        assert!(scroller.is_active());

        // Starting a new fling should replace the old one.
        scroller.fling(1000.0, 0.0, 50.0, 50.0);
        assert!(scroller.is_active());

        thread::sleep(Duration::from_millis(16));
        if let Some(delta) = scroller.step() {
            // Should be moving mostly in X now, not Y.
            assert!(
                delta.dx.abs() > delta.dy.abs(),
                "dx={} should dominate dy={}",
                delta.dx,
                delta.dy
            );
        }
    }

    #[test]
    fn ring_buffer_wraps() {
        let mut tracker = VelocityTracker::new();
        // Record more than MAX_SAMPLES to ensure wrapping works.
        for i in 0..(MAX_SAMPLES * 2) {
            tracker.record(i as f32, i as f32);
            thread::sleep(Duration::from_millis(1));
        }
        // Should still produce a reasonable velocity.
        let (vx, vy) = tracker.velocity();
        assert!(vx.abs() > 0.0 || vy.abs() > 0.0);
    }
}