libbhoo 0.3.0

Minimal UI foundations for SpectreOS
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! 2D wallpaper crop & preview viewport physics modeling Android 13 `WallpaperPicker2`
//! (`SubsamplingScaleImageView`): pan, focal-point pinch zoom, rubber-band overscroll with
//! damped spring bounce-back, inertial 2D fling, double-tap zoom toggle, and parallax UVs.
use crate::{Input, MotionPreference, Rect};

const SPRING_STIFFNESS: f64 = 700.0;
const SPRING_DAMPING: f64 = 0.9;
const DOUBLE_TAP_DURATION: f64 = 0.26;
const DOUBLE_TAP_MAX_INTERVAL: f64 = 0.32;
const DOUBLE_TAP_MAX_DISTANCE: f32 = 48.0;
const DRAG_SLOP_PX: f32 = 6.0;
const FLING_DECAY_RATE: f64 = 4.2;

/// Outcome of a single `CropViewportState::update` step.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CropUpdate {
    /// Whether `zoom` or `center` changed during this frame.
    pub changed: bool,
    /// Whether an inertial fling, spring bounce-back, or double-tap zoom animation is still active.
    pub animating: bool,
    /// Whether a clean single tap completed inside the viewport on this frame.
    pub tapped: bool,
}

#[derive(Clone, Copy, Debug)]
struct DoubleTapAnim {
    start_time: f64,
    duration: f64,
    from_zoom: f32,
    to_zoom: f32,
    from_center: [f32; 2],
    to_center: [f32; 2],
}

/// Interactive 2D crop & preview viewport state.
#[derive(Clone, Copy, Debug)]
pub struct CropViewportState {
    /// Magnification factor (`1.0` = cover fit; rests in `1.0..=max_zoom`).
    pub zoom: f32,
    /// Normalized image center coordinate (`[0.5, 0.5]` = centered, rests in valid crop bounds).
    pub center: [f32; 2],
    /// Maximum resting zoom level (default `4.0`).
    pub max_zoom: f32,

    // Pointer / gesture tracking
    dragging: bool,
    pointer_down: bool,
    press_origin: [f32; 2],
    last_pointer: [f32; 2],
    last_drag_time: f64,
    pinching: bool,
    had_pinch: bool,
    last_pinch_center: Option<[f32; 2]>,

    // Double-tap tracking & animation
    last_tap: Option<(f64, [f32; 2])>,
    double_tap_anim: Option<DoubleTapAnim>,

    // 2D velocity (in normalized UV units / sec) and zoom spring velocity
    velocity: [f64; 2],
    zoom_velocity: f64,
    last_time: Option<f64>,
}

impl Default for CropViewportState {
    fn default() -> Self {
        Self::new()
    }
}

impl CropViewportState {
    pub const fn new() -> Self {
        Self {
            zoom: 1.0,
            center: [0.5, 0.5],
            max_zoom: 4.0,
            dragging: false,
            pointer_down: false,
            press_origin: [0.0, 0.0],
            last_pointer: [0.0, 0.0],
            last_drag_time: 0.0,
            pinching: false,
            had_pinch: false,
            last_pinch_center: None,
            last_tap: None,
            double_tap_anim: None,
            velocity: [0.0, 0.0],
            zoom_velocity: 0.0,
            last_time: None,
        }
    }

    /// Reset zoom, center, and any in-flight gestures or animations back to centered cover fit.
    pub fn reset(&mut self) {
        self.zoom = 1.0;
        self.center = [0.5, 0.5];
        self.dragging = false;
        self.pointer_down = false;
        self.pinching = false;
        self.had_pinch = false;
        self.last_pinch_center = None;
        self.last_tap = None;
        self.double_tap_anim = None;
        self.velocity = [0.0, 0.0];
        self.zoom_velocity = 0.0;
    }

    /// Base normalized cover-fit span `[base_w, base_h]` at `zoom = 1.0`.
    fn base_span(img_w: u32, img_h: u32, aspect: f32) -> [f32; 2] {
        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
            return [1.0, 1.0];
        }
        let img_aspect = img_w as f32 / img_h as f32;
        if img_aspect > aspect {
            [(aspect / img_aspect).clamp(1e-5, 1.0), 1.0]
        } else {
            [1.0, (img_aspect / aspect).clamp(1e-5, 1.0)]
        }
    }

    fn visible_span(img_w: u32, img_h: u32, aspect: f32, zoom: f32) -> [f32; 2] {
        let [bw, bh] = Self::base_span(img_w, img_h, aspect);
        let z = zoom.max(0.25);
        [bw / z, bh / z]
    }

    fn center_bounds(img_w: u32, img_h: u32, aspect: f32, zoom: f32) -> ([f32; 2], [f32; 2]) {
        let [su, sv] = Self::visible_span(img_w, img_h, aspect, zoom);
        let min_x = (su * 0.5).min(0.5);
        let max_x = (1.0 - su * 0.5).max(0.5);
        let min_y = (sv * 0.5).min(0.5);
        let max_y = (1.0 - sv * 0.5).max(0.5);
        ([min_x, min_y], [max_x, max_y])
    }

    fn clamp_center(center: [f32; 2], img_w: u32, img_h: u32, aspect: f32, zoom: f32) -> [f32; 2] {
        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, zoom);
        [
            center[0].clamp(min_c[0], max_c[0]),
            center[1].clamp(min_c[1], max_c[1]),
        ]
    }

    /// Wheel/programmatic zoom helper multiplying `zoom` by `factor` around `focal` in `viewport`.
    /// Preserves the image pixel under `focal` (subject to valid resting crop bounds).
    pub fn zoom_at(
        &mut self,
        factor: f32,
        focal: [f32; 2],
        viewport: Rect,
        img_w: u32,
        img_h: u32,
    ) {
        if !factor.is_finite()
            || factor <= 0.0
            || viewport.width <= 0.0
            || viewport.height <= 0.0
            || img_w == 0
            || img_h == 0
        {
            return;
        }
        self.double_tap_anim = None;
        self.velocity = [0.0, 0.0];
        self.zoom_velocity = 0.0;
        let max_z = self.max_zoom.max(1.0);
        let aspect = viewport.width / viewport.height;
        let old_zoom = self.zoom.max(0.25);
        let new_zoom = (old_zoom * factor).clamp(1.0, max_z);
        let [old_su, old_sv] = Self::visible_span(img_w, img_h, aspect, old_zoom);
        let [new_su, new_sv] = Self::visible_span(img_w, img_h, aspect, new_zoom);
        let fx_rel = (focal[0] - viewport.x) / viewport.width - 0.5;
        let fy_rel = (focal[1] - viewport.y) / viewport.height - 0.5;
        let anchor_u = self.center[0] + fx_rel * old_su;
        let anchor_v = self.center[1] + fy_rel * old_sv;
        let raw_center = [anchor_u - fx_rel * new_su, anchor_v - fy_rel * new_sv];
        self.zoom = new_zoom;
        self.center = Self::clamp_center(raw_center, img_w, img_h, aspect, new_zoom);
    }

    /// Process one input frame and advance pan, pinch, fling, rubber-band spring, and double-tap zoom.
    pub fn update(
        &mut self,
        input: Input,
        viewport: Rect,
        img_w: u32,
        img_h: u32,
        motion: MotionPreference,
        anim_scale: f32,
    ) -> CropUpdate {
        let prev_zoom = self.zoom;
        let prev_center = self.center;
        let max_z = self.max_zoom.max(1.0);

        if viewport.width <= 0.0 || viewport.height <= 0.0 || img_w == 0 || img_h == 0 {
            return CropUpdate::default();
        }
        let aspect = viewport.width / viewport.height;
        let now = if input.time.is_finite() {
            match self.last_time {
                Some(prev) => input.time.max(prev),
                None => input.time,
            }
        } else {
            self.last_time.unwrap_or(0.0)
        };
        let raw_dt = match self.last_time {
            Some(prev) => (now - prev).max(0.0),
            None => 0.0,
        };
        self.last_time = Some(now);

        let reduced = motion == MotionPreference::Reduced || !anim_scale.is_finite() || anim_scale <= 0.0;
        let scale_mul = if reduced { 0.0 } else { anim_scale.max(0.0) as f64 };
        let mut tapped = false;

        // Handle cancellation / window blur cleanly.
        if input.cancelled || input.blurred {
            self.pointer_down = false;
            self.dragging = false;
            self.pinching = false;
            self.had_pinch = false;
            self.last_pinch_center = None;
            self.velocity = [0.0, 0.0];
        }

        // 1. Multi-touch pinch (or trackpad pinch_scale) takes priority over single-finger pan.
        let pinch_active = !input.cancelled
            && !input.blurred
            && (input.touch_count >= 2
                || (input.pinch_scale.is_finite() && (input.pinch_scale - 1.0).abs() > 1e-4));
        if pinch_active {
            let focal = input
                .pinch_center
                .or(input.pointer)
                .unwrap_or([
                    viewport.x + viewport.width * 0.5,
                    viewport.y + viewport.height * 0.5,
                ]);
            let prev_focal = self.last_pinch_center.unwrap_or(focal);
            self.pinching = true;
            self.had_pinch = true;
            self.dragging = false;
            self.double_tap_anim = None;
            self.velocity = [0.0, 0.0];
            self.zoom_velocity = 0.0;

            let old_zoom = self.zoom.max(0.25);
            let factor = if input.pinch_scale.is_finite() && input.pinch_scale > 0.0 {
                input.pinch_scale.clamp(0.25, 4.0)
            } else {
                1.0
            };
            let raw_zoom = old_zoom * factor;
            let new_zoom = if raw_zoom < 1.0 {
                (1.0 - (1.0 - raw_zoom) * 0.35).max(0.75)
            } else if raw_zoom > max_z {
                (max_z + (raw_zoom - max_z) * 0.35).min(max_z * 1.25)
            } else {
                raw_zoom
            };

            let [old_su, old_sv] = Self::visible_span(img_w, img_h, aspect, old_zoom);
            let [new_su, new_sv] = Self::visible_span(img_w, img_h, aspect, new_zoom);
            let prev_fx = (prev_focal[0] - viewport.x) / viewport.width - 0.5;
            let prev_fy = (prev_focal[1] - viewport.y) / viewport.height - 0.5;
            let curr_fx = (focal[0] - viewport.x) / viewport.width - 0.5;
            let curr_fy = (focal[1] - viewport.y) / viewport.height - 0.5;

            let anchor_u = self.center[0] + prev_fx * old_su;
            let anchor_v = self.center[1] + prev_fy * old_sv;
            let target_cx = anchor_u - curr_fx * new_su;
            let target_cy = anchor_v - curr_fy * new_sv;

            self.zoom = new_zoom;
            let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, new_zoom.clamp(1.0, max_z));
            let over_u = (new_su * 0.25).clamp(0.06, 0.2);
            let over_v = (new_sv * 0.25).clamp(0.06, 0.2);
            self.center = [
                rubber_band_clamp(target_cx, min_c[0], max_c[0], over_u),
                rubber_band_clamp(target_cy, min_c[1], max_c[1], over_v),
            ];
            self.last_pinch_center = Some(focal);
        } else {
            if self.pinching {
                self.pinching = false;
                self.last_pinch_center = None;
            }

            // 2. Single-pointer press / drag / release.
            if !input.cancelled && !input.blurred {
                if input.pressed
                    && let Some(p) = input.pointer
                    && viewport.contains(p)
                {
                    self.pointer_down = true;
                    self.dragging = false;
                    self.had_pinch = false;
                    self.press_origin = p;
                    self.last_pointer = p;
                    self.last_drag_time = now;
                    self.velocity = [0.0, 0.0];
                    self.double_tap_anim = None;
                }

                if self.pointer_down
                    && let Some(p) = input.pointer
                {
                    let total_dist = (p[0] - self.press_origin[0]).hypot(p[1] - self.press_origin[1]);
                    if total_dist > DRAG_SLOP_PX {
                        self.dragging = true;
                    }
                    let dx = p[0] - self.last_pointer[0];
                    let dy = p[1] - self.last_pointer[1];
                    if self.dragging && (dx.abs() > 1e-4 || dy.abs() > 1e-4) {
                        let [su, sv] = Self::visible_span(img_w, img_h, aspect, self.zoom);
                        let du = -dx / viewport.width * su;
                        let dv = -dy / viewport.height * sv;
                        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
                        let over = [(su * 0.25).clamp(0.06, 0.2), (sv * 0.25).clamp(0.06, 0.2)];
                        let delta = [du, dv];
                        let dt_drag = (now - self.last_drag_time).clamp(0.001, 0.15);
                        let alpha = 1.0 - (-dt_drag / 0.04).exp();
                        for i in 0..2 {
                            let outside = self.center[i] < min_c[i] || self.center[i] > max_c[i];
                            let step = if outside { delta[i] * 0.35 } else { delta[i] };
                            self.center[i] = (self.center[i] + step)
                                .clamp(min_c[i] - over[i], max_c[i] + over[i]);
                            if outside {
                                self.velocity[i] = 0.0;
                            } else {
                                let inst = (step as f64 / dt_drag).clamp(-12.0, 12.0);
                                self.velocity[i] += (inst - self.velocity[i]) * alpha;
                            }
                        }
                        self.last_drag_time = now;
                    } else if now - self.last_drag_time > 0.1 {
                        self.velocity = [0.0, 0.0];
                    }
                    self.last_pointer = p;
                }

                if input.released && self.pointer_down {
                    let release_pos = input.pointer.unwrap_or(self.last_pointer);
                    let was_dragging = self.dragging;
                    let was_pinch = self.had_pinch;
                    self.pointer_down = false;
                    self.dragging = false;
                    self.had_pinch = false;

                    if !was_dragging && !was_pinch && viewport.contains(release_pos) {
                        tapped = true;
                        let is_double_tap = self.last_tap.is_some_and(|(t0, p0)| {
                            (now - t0) <= DOUBLE_TAP_MAX_INTERVAL
                                && (release_pos[0] - p0[0]).hypot(release_pos[1] - p0[1])
                                    <= DOUBLE_TAP_MAX_DISTANCE
                        });
                        if is_double_tap {
                            self.last_tap = None;
                            let target_zoom = if self.zoom > 1.05 {
                                1.0
                            } else {
                                2.0_f32.min(max_z)
                            };
                            let [old_su, old_sv] = Self::visible_span(img_w, img_h, aspect, self.zoom);
                            let [new_su, new_sv] = Self::visible_span(img_w, img_h, aspect, target_zoom);
                            let fx_rel = (release_pos[0] - viewport.x) / viewport.width - 0.5;
                            let fy_rel = (release_pos[1] - viewport.y) / viewport.height - 0.5;
                            let anchor_u = self.center[0] + fx_rel * old_su;
                            let anchor_v = self.center[1] + fy_rel * old_sv;
                            let to_center = Self::clamp_center(
                                [anchor_u - fx_rel * new_su, anchor_v - fy_rel * new_sv],
                                img_w,
                                img_h,
                                aspect,
                                target_zoom,
                            );
                            self.velocity = [0.0, 0.0];
                            self.zoom_velocity = 0.0;
                            if reduced {
                                self.zoom = target_zoom;
                                self.center = to_center;
                                self.double_tap_anim = None;
                            } else {
                                self.double_tap_anim = Some(DoubleTapAnim {
                                    start_time: now,
                                    duration: DOUBLE_TAP_DURATION * scale_mul,
                                    from_zoom: self.zoom,
                                    to_zoom: target_zoom,
                                    from_center: self.center,
                                    to_center,
                                });
                            }
                        } else {
                            self.last_tap = Some((now, release_pos));
                        }
                    } else {
                        self.last_tap = None;
                        if now - self.last_drag_time > 0.1 || reduced {
                            self.velocity = [0.0, 0.0];
                        } else {
                            // Clear fling velocity on axes already past valid bounds so bounce-back dominates.
                            let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
                            for i in 0..2 {
                                if self.center[i] < min_c[i] || self.center[i] > max_c[i] {
                                    self.velocity[i] = 0.0;
                                }
                            }
                            if self.velocity[0].hypot(self.velocity[1]) < 0.04 {
                                self.velocity = [0.0, 0.0];
                            }
                        }
                    }
                }
            }
        }

        // 3. Advance animations / inertial fling / spring bounce-back when not actively dragging or pinching.
        let mut animating = false;
        if !self.pointer_down && !self.pinching {
            if reduced {
                if let Some(anim) = self.double_tap_anim.take() {
                    self.zoom = anim.to_zoom;
                    self.center = anim.to_center;
                }
                self.zoom = self.zoom.clamp(1.0, max_z);
                self.center = Self::clamp_center(self.center, img_w, img_h, aspect, self.zoom);
                self.velocity = [0.0, 0.0];
                self.zoom_velocity = 0.0;
            } else if let Some(anim) = self.double_tap_anim {
                let p = if anim.duration > 0.0 {
                    ((now - anim.start_time) / anim.duration).clamp(0.0, 1.0) as f32
                } else {
                    1.0
                };
                let e = crate::timing::Easing::Emphasized.sample(p);
                self.zoom = anim.from_zoom + (anim.to_zoom - anim.from_zoom) * e;
                self.center = [
                    anim.from_center[0] + (anim.to_center[0] - anim.from_center[0]) * e,
                    anim.from_center[1] + (anim.to_center[1] - anim.from_center[1]) * e,
                ];
                if p >= 1.0 {
                    self.zoom = anim.to_zoom;
                    self.center = anim.to_center;
                    self.double_tap_anim = None;
                } else {
                    animating = true;
                }
            } else {
                let sim_dt = raw_dt * scale_mul;
                let zoom_target = self.zoom.clamp(1.0, max_z) as f64;
                let zoom_out = (self.zoom as f64 - zoom_target).abs() > 1e-4
                    || self.zoom_velocity.abs() > 1e-3;
                if zoom_out && sim_dt > 0.0 {
                    let mut z = self.zoom as f64;
                    advance_spring(&mut z, &mut self.zoom_velocity, zoom_target, sim_dt);
                    self.zoom = z as f32;
                }

                // Integrate 2D fling & elastic boundary bounce-back cleanly even across large timestamps.
                if sim_dt > 0.0 {
                    let total_steps = ((sim_dt / 0.016).ceil() as usize).clamp(1, 250);
                    if sim_dt > 4.0 {
                        // Past 4s of scaled time, both fling (e^-16.8) and spring (e^-95) are fully settled.
                        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
                        for i in 0..2 {
                            let free_disp = (self.velocity[i] / FLING_DECAY_RATE) as f32;
                            self.center[i] = (self.center[i] + free_disp).clamp(min_c[i], max_c[i]);
                            self.velocity[i] = 0.0;
                        }
                    } else {
                        let step_dt = sim_dt / total_steps as f64;
                        let decay = (-FLING_DECAY_RATE * step_dt).exp();
                        let integral = (1.0 - decay) / FLING_DECAY_RATE;
                        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
                        for _ in 0..total_steps {
                            let mut any_active = false;
                            for i in 0..2 {
                                let lo = min_c[i] as f64;
                                let hi = max_c[i] as f64;
                                let mut c = self.center[i] as f64;
                                if c < lo || c > hi {
                                    let target = c.clamp(lo, hi);
                                    advance_spring(&mut c, &mut self.velocity[i], target, step_dt);
                                    self.center[i] = c as f32;
                                    if (c - target).abs() > 1e-4 || self.velocity[i].abs() > 1e-3 {
                                        any_active = true;
                                    }
                                } else if self.velocity[i].abs() > 1e-4 {
                                    let next = c + self.velocity[i] * integral;
                                    self.velocity[i] *= decay;
                                    if next < lo || next > hi {
                                        let edge = next.clamp(lo, hi);
                                        let overshoot = (next - edge) * 0.35;
                                        self.center[i] = (edge + overshoot) as f32;
                                        self.velocity[i] *= 0.35;
                                        any_active = true;
                                    } else {
                                        self.center[i] = next as f32;
                                        any_active = true;
                                    }
                                }
                            }
                            if !any_active {
                                break;
                            }
                        }
                    }
                }

                // Settle thresholds so idle state returns animating = false cleanly.
                let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
                let mut center_moving = false;
                for i in 0..2 {
                    let clamped = self.center[i].clamp(min_c[i], max_c[i]);
                    if (self.center[i] - clamped).abs() <= 1e-4 && self.velocity[i].abs() < 0.004 {
                        self.center[i] = clamped;
                        self.velocity[i] = 0.0;
                    } else if self.center[i] != clamped || self.velocity[i].abs() >= 0.004 {
                        center_moving = true;
                    }
                }
                let zoom_clamped = self.zoom.clamp(1.0, max_z);
                let zoom_moving = if (self.zoom - zoom_clamped).abs() <= 1e-4
                    && self.zoom_velocity.abs() < 1e-3
                {
                    self.zoom = zoom_clamped;
                    self.zoom_velocity = 0.0;
                    false
                } else {
                    true
                };
                animating = center_moving || zoom_moving;
            }
        }

        let changed = (self.zoom - prev_zoom).abs() > 1e-6
            || (self.center[0] - prev_center[0]).abs() > 1e-6
            || (self.center[1] - prev_center[1]).abs() > 1e-6;
        CropUpdate {
            changed,
            animating,
            tapped,
        }
    }

    /// Integer pixel crop rectangle `(x, y, width, height)` inside `(img_w, img_h)` for `aspect`.
    pub fn crop_rect(&self, img_w: u32, img_h: u32, aspect: f32) -> (u32, u32, u32, u32) {
        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
            return (0, 0, img_w, img_h);
        }
        let z = self.zoom.clamp(1.0, self.max_zoom.max(1.0));
        let [su, sv] = Self::visible_span(img_w, img_h, aspect, z);
        let c = Self::clamp_center(self.center, img_w, img_h, aspect, z);
        let u0 = (c[0] - su * 0.5).clamp(0.0, 1.0);
        let v0 = (c[1] - sv * 0.5).clamp(0.0, 1.0);
        let w = (su * img_w as f32).round().clamp(1.0, img_w as f32) as u32;
        let h = (sv * img_h as f32).round().clamp(1.0, img_h as f32) as u32;
        let x = (u0 * img_w as f32).round().clamp(0.0, (img_w - w) as f32) as u32;
        let y = (v0 * img_h as f32).round().clamp(0.0, (img_h - h) as f32) as u32;
        (x, y, w, h)
    }

    /// Normalized `[u0, v0, u1, v1]` UV coordinates currently visible in the viewport.
    pub fn visible_uv(&self, img_w: u32, img_h: u32, aspect: f32) -> [f32; 4] {
        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
            return [0.0, 0.0, 1.0, 1.0];
        }
        let [su, sv] = Self::visible_span(img_w, img_h, aspect, self.zoom);
        [
            self.center[0] - su * 0.5,
            self.center[1] - sv * 0.5,
            self.center[0] + su * 0.5,
            self.center[1] + sv * 0.5,
        ]
    }

    /// Compute normalized `[u0, v0, u1, v1]` UV coordinates for Android home-screen wallpaper parallax
    /// at horizontal page offset `x_offset` (`0.0..=1.0`) across `parallax_pages` screens.
    pub fn parallax_uv(
        img_w: u32,
        img_h: u32,
        aspect: f32,
        x_offset: f32,
        parallax_pages: u32,
    ) -> [f32; 4] {
        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
            return [0.0, 0.0, 1.0, 1.0];
        }
        let [base_w, base_h] = Self::base_span(img_w, img_h, aspect);
        let slack = (1.0 - base_w).max(0.0);
        let travel = if parallax_pages <= 1 {
            0.0
        } else {
            slack.min(base_w * 0.5 * (parallax_pages - 1) as f32)
        };
        let u_min = 0.5 - base_w * 0.5 - travel * 0.5;
        let t = if x_offset.is_finite() {
            x_offset.clamp(0.0, 1.0)
        } else {
            0.5
        };
        let u0 = (u_min + travel * t).clamp(0.0, (1.0 - base_w).max(0.0));
        let u1 = (u0 + base_w).min(1.0);
        let v0 = ((1.0 - base_h) * 0.5).clamp(0.0, 1.0);
        let v1 = (v0 + base_h).min(1.0);
        [u0, v0, u1, v1]
    }
}

fn rubber_band_clamp(value: f32, min: f32, max: f32, max_over: f32) -> f32 {
    if value < min {
        let excess = min - value;
        min - (excess * 0.35).min(max_over)
    } else if value > max {
        let excess = value - max;
        max + (excess * 0.35).min(max_over)
    } else {
        value
    }
}

/// Exact analytic damped harmonic oscillator matching Bhoo's Standard spatial spring
/// (`stiffness = 700.0`, `damping = 0.9`).
fn advance_spring(value: &mut f64, velocity: &mut f64, target: f64, dt: f64) {
    let omega = SPRING_STIFFNESS.sqrt();
    let disp = *value - target;
    let rate = SPRING_DAMPING * omega;
    let freq = omega * (1.0 - SPRING_DAMPING * SPRING_DAMPING).sqrt();
    let c = (*velocity + rate * disp) / freq;
    let phase = freq * dt;
    let wave = disp * phase.cos() + c * phase.sin();
    let decay = (-rate * dt).exp();
    *value = target + wave * decay;
    *velocity = (freq * (-disp * phase.sin() + c * phase.cos()) - rate * wave) * decay;
    if (*value - target).abs() < 1e-4 && velocity.abs() < 1e-3 {
        *value = target;
        *velocity = 0.0;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::PointerKind;

    const VP: Rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 360.0,
        height: 800.0,
    };

    fn touch(p: [f32; 2], pressed: bool, released: bool, time: f64) -> Input {
        Input {
            pointer: Some(p),
            pointer_kind: PointerKind::Touch,
            pressed,
            released,
            time,
            touch_count: if released { 0 } else { 1 },
            ..Input::default()
        }
    }

    #[test]
    fn pan_shifts_crop_center_and_bounds_crop_rect() {
        let mut s = CropViewportState::new();
        // Wide 2000x1000 image in portrait 360x800 viewport -> wide horizontal pan room.
        s.update(touch([200.0, 400.0], true, false, 0.0), VP, 2000, 1000, MotionPreference::Full, 1.0);
        let u1 = s.update(touch([100.0, 400.0], false, false, 0.05), VP, 2000, 1000, MotionPreference::Full, 1.0);
        assert!(u1.changed);
        // Dragging finger left moves viewport right across the image -> center[0] increases.
        assert!(s.center[0] > 0.5);
        s.update(touch([100.0, 400.0], false, true, 0.25), VP, 2000, 1000, MotionPreference::Full, 1.0);
        let (x, y, w, h) = s.crop_rect(2000, 1000, VP.width / VP.height);
        assert_eq!(h, 1000);
        assert_eq!(w, 450);
        assert!(x + w <= 2000 && y + h <= 1000);
        assert!(x > (2000 - w) / 2);
    }

    #[test]
    fn pinch_preserves_focal_image_pixel() {
        let mut s = CropViewportState::new();
        let focal = [270.0, 200.0]; // off-center focal point
        let aspect = VP.width / VP.height;
        let uv_before = s.visible_uv(2000, 2000, aspect);
        let fx = (focal[0] - VP.x) / VP.width;
        let fy = (focal[1] - VP.y) / VP.height;
        let pixel_u_before = uv_before[0] + fx * (uv_before[2] - uv_before[0]);
        let pixel_v_before = uv_before[1] + fy * (uv_before[3] - uv_before[1]);

        let pinch = Input {
            pinch_scale: 2.0,
            pinch_center: Some(focal),
            touch_count: 2,
            time: 0.1,
            ..Input::default()
        };
        let u = s.update(pinch, VP, 2000, 2000, MotionPreference::Full, 1.0);
        assert!(u.changed);
        assert!((s.zoom - 2.0).abs() < 1e-4);

        let uv_after = s.visible_uv(2000, 2000, aspect);
        let pixel_u_after = uv_after[0] + fx * (uv_after[2] - uv_after[0]);
        let pixel_v_after = uv_after[1] + fy * (uv_after[3] - uv_after[1]);
        assert!((pixel_u_after - pixel_u_before).abs() < 1e-4);
        assert!((pixel_v_after - pixel_v_before).abs() < 1e-4);

        // Wheel helper also preserves focal point cleanly.
        let mut w = CropViewportState::new();
        w.zoom_at(2.0, focal, VP, 2000, 2000);
        let uv_w = w.visible_uv(2000, 2000, aspect);
        let pu = uv_w[0] + fx * (uv_w[2] - uv_w[0]);
        let pv = uv_w[1] + fy * (uv_w[3] - uv_w[1]);
        assert!((pu - pixel_u_before).abs() < 1e-4);
        assert!((pv - pixel_v_before).abs() < 1e-4);
    }

    #[test]
    fn rubber_band_overscroll_bounces_back_to_valid_bounds() {
        let mut s = CropViewportState::new();
        // Image matches viewport aspect -> valid center is strictly [0.5, 0.5] at zoom=1.0.
        s.update(touch([180.0, 400.0], true, false, 0.0), VP, 360, 800, MotionPreference::Full, 1.0);
        s.update(touch([320.0, 400.0], false, false, 0.05), VP, 360, 800, MotionPreference::Full, 1.0);
        assert!(s.center[0] < 0.5, "rubber band should allow overscroll during drag");
        s.update(touch([320.0, 400.0], false, true, 0.25), VP, 360, 800, MotionPreference::Full, 1.0);

        let mid = s.update(Input { time: 0.30, ..Input::default() }, VP, 360, 800, MotionPreference::Full, 1.0);
        assert!(mid.animating);

        let mut settled = false;
        for step in 1..=90 {
            let res = s.update(
                Input {
                    time: 0.30 + step as f64 / 60.0,
                    ..Input::default()
                },
                VP,
                360,
                800,
                MotionPreference::Full,
                1.0,
            );
            if !res.animating {
                settled = true;
                break;
            }
        }
        assert!(settled, "spring bounce-back should settle to idle");
        assert!((s.center[0] - 0.5).abs() < 1e-4);
        assert!((s.center[1] - 0.5).abs() < 1e-4);
    }

    #[test]
    fn fling_coasts_and_settles_to_idle() {
        let mut s = CropViewportState::new();
        s.zoom = 2.5;
        s.update(touch([260.0, 500.0], true, false, 0.0), VP, 2000, 2000, MotionPreference::Full, 1.0);
        s.update(touch([180.0, 430.0], false, false, 0.02), VP, 2000, 2000, MotionPreference::Full, 1.0);
        s.update(touch([100.0, 360.0], false, false, 0.04), VP, 2000, 2000, MotionPreference::Full, 1.0);
        let at_release = s.center;
        let rel = s.update(touch([100.0, 360.0], false, true, 0.04), VP, 2000, 2000, MotionPreference::Full, 1.0);
        assert!(rel.animating);

        let mut settled = false;
        for i in 1..=180 {
            let r = s.update(
                Input {
                    time: 0.04 + i as f64 / 60.0,
                    ..Input::default()
                },
                VP,
                2000,
                2000,
                MotionPreference::Full,
                1.0,
            );
            if !r.animating {
                settled = true;
                break;
            }
        }
        assert!(settled, "inertial fling must settle cleanly to idle");
        assert!(s.center[0] > at_release[0]);
        assert!(s.center[1] > at_release[1]);
    }

    #[test]
    fn double_tap_toggles_zoom_and_respects_reduced_motion() {
        let mut s = CropViewportState::new();
        let tap_pt = [260.0, 300.0];
        // First tap
        s.update(touch(tap_pt, true, false, 0.0), VP, 1000, 2000, MotionPreference::Full, 1.0);
        let t1 = s.update(touch(tap_pt, false, true, 0.05), VP, 1000, 2000, MotionPreference::Full, 1.0);
        assert!(t1.tapped);
        assert!((s.zoom - 1.0).abs() < 1e-4);

        // Second tap within 0.32s triggers 1.0x -> 2.0x over 0.26s
        s.update(touch(tap_pt, true, false, 0.16), VP, 1000, 2000, MotionPreference::Full, 1.0);
        let t2 = s.update(touch(tap_pt, false, true, 0.20), VP, 1000, 2000, MotionPreference::Full, 1.0);
        assert!(t2.tapped);
        assert!(t2.animating);

        let mid = s.update(Input { time: 0.33, ..Input::default() }, VP, 1000, 2000, MotionPreference::Full, 1.0);
        assert!(mid.animating && s.zoom > 1.2 && s.zoom < 2.0);
        let end = s.update(Input { time: 0.47, ..Input::default() }, VP, 1000, 2000, MotionPreference::Full, 1.0);
        assert!(!end.animating);
        assert!((s.zoom - 2.0).abs() < 1e-4);
        assert!(s.center[0] > 0.5, "double-tap anchor shifts center toward tap point");

        // Second double-tap under Reduced motion snaps immediately back to 1.0x!
        s.update(touch(tap_pt, true, false, 1.0), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
        s.update(touch(tap_pt, false, true, 1.04), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
        s.update(touch(tap_pt, true, false, 1.12), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
        let snap = s.update(touch(tap_pt, false, true, 1.16), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
        assert!(!snap.animating);
        assert!((s.zoom - 1.0).abs() < 1e-4);
    }

    #[test]
    fn parallax_uv_stays_within_unit_bounds_and_pans_smoothly() {
        let aspect = 9.0 / 20.0;
        let single = CropViewportState::parallax_uv(2048, 1024, aspect, 0.0, 1);
        let single_end = CropViewportState::parallax_uv(2048, 1024, aspect, 1.0, 1);
        assert_eq!(single, single_end);

        let left = CropViewportState::parallax_uv(2048, 1024, aspect, 0.0, 3);
        let mid = CropViewportState::parallax_uv(2048, 1024, aspect, 0.5, 3);
        let right = CropViewportState::parallax_uv(2048, 1024, aspect, 1.0, 3);
        for uv in [left, mid, right] {
            assert!(uv[0] >= 0.0 && uv[2] <= 1.0 && uv[0] < uv[2]);
            assert!(uv[1] >= 0.0 && uv[3] <= 1.0 && uv[1] < uv[3]);
        }
        assert!(left[0] < mid[0] && mid[0] < right[0]);
        assert!(((left[2] - left[0]) - (right[2] - right[0])).abs() < 1e-5);
        assert!(((mid[0] + mid[2]) * 0.5 - 0.5).abs() < 1e-5);
    }
}