Skip to main content

bhoo/
crop.rs

1//! 2D wallpaper crop & preview viewport physics modeling Android 13 `WallpaperPicker2`
2//! (`SubsamplingScaleImageView`): pan, focal-point pinch zoom, rubber-band overscroll with
3//! damped spring bounce-back, inertial 2D fling, double-tap zoom toggle, and parallax UVs.
4use crate::{Input, MotionPreference, Rect};
5
6const SPRING_STIFFNESS: f64 = 700.0;
7const SPRING_DAMPING: f64 = 0.9;
8const DOUBLE_TAP_DURATION: f64 = 0.26;
9const DOUBLE_TAP_MAX_INTERVAL: f64 = 0.32;
10const DOUBLE_TAP_MAX_DISTANCE: f32 = 48.0;
11const DRAG_SLOP_PX: f32 = 6.0;
12const FLING_DECAY_RATE: f64 = 4.2;
13
14/// Outcome of a single `CropViewportState::update` step.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub struct CropUpdate {
17    /// Whether `zoom` or `center` changed during this frame.
18    pub changed: bool,
19    /// Whether an inertial fling, spring bounce-back, or double-tap zoom animation is still active.
20    pub animating: bool,
21    /// Whether a clean single tap completed inside the viewport on this frame.
22    pub tapped: bool,
23}
24
25#[derive(Clone, Copy, Debug)]
26struct DoubleTapAnim {
27    start_time: f64,
28    duration: f64,
29    from_zoom: f32,
30    to_zoom: f32,
31    from_center: [f32; 2],
32    to_center: [f32; 2],
33}
34
35/// Interactive 2D crop & preview viewport state.
36#[derive(Clone, Copy, Debug)]
37pub struct CropViewportState {
38    /// Magnification factor (`1.0` = cover fit; rests in `1.0..=max_zoom`).
39    pub zoom: f32,
40    /// Normalized image center coordinate (`[0.5, 0.5]` = centered, rests in valid crop bounds).
41    pub center: [f32; 2],
42    /// Maximum resting zoom level (default `4.0`).
43    pub max_zoom: f32,
44
45    // Pointer / gesture tracking
46    dragging: bool,
47    pointer_down: bool,
48    press_origin: [f32; 2],
49    last_pointer: [f32; 2],
50    last_drag_time: f64,
51    pinching: bool,
52    had_pinch: bool,
53    last_pinch_center: Option<[f32; 2]>,
54
55    // Double-tap tracking & animation
56    last_tap: Option<(f64, [f32; 2])>,
57    double_tap_anim: Option<DoubleTapAnim>,
58
59    // 2D velocity (in normalized UV units / sec) and zoom spring velocity
60    velocity: [f64; 2],
61    zoom_velocity: f64,
62    last_time: Option<f64>,
63}
64
65impl Default for CropViewportState {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl CropViewportState {
72    pub const fn new() -> Self {
73        Self {
74            zoom: 1.0,
75            center: [0.5, 0.5],
76            max_zoom: 4.0,
77            dragging: false,
78            pointer_down: false,
79            press_origin: [0.0, 0.0],
80            last_pointer: [0.0, 0.0],
81            last_drag_time: 0.0,
82            pinching: false,
83            had_pinch: false,
84            last_pinch_center: None,
85            last_tap: None,
86            double_tap_anim: None,
87            velocity: [0.0, 0.0],
88            zoom_velocity: 0.0,
89            last_time: None,
90        }
91    }
92
93    /// Reset zoom, center, and any in-flight gestures or animations back to centered cover fit.
94    pub fn reset(&mut self) {
95        self.zoom = 1.0;
96        self.center = [0.5, 0.5];
97        self.dragging = false;
98        self.pointer_down = false;
99        self.pinching = false;
100        self.had_pinch = false;
101        self.last_pinch_center = None;
102        self.last_tap = None;
103        self.double_tap_anim = None;
104        self.velocity = [0.0, 0.0];
105        self.zoom_velocity = 0.0;
106    }
107
108    /// Base normalized cover-fit span `[base_w, base_h]` at `zoom = 1.0`.
109    fn base_span(img_w: u32, img_h: u32, aspect: f32) -> [f32; 2] {
110        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
111            return [1.0, 1.0];
112        }
113        let img_aspect = img_w as f32 / img_h as f32;
114        if img_aspect > aspect {
115            [(aspect / img_aspect).clamp(1e-5, 1.0), 1.0]
116        } else {
117            [1.0, (img_aspect / aspect).clamp(1e-5, 1.0)]
118        }
119    }
120
121    fn visible_span(img_w: u32, img_h: u32, aspect: f32, zoom: f32) -> [f32; 2] {
122        let [bw, bh] = Self::base_span(img_w, img_h, aspect);
123        let z = zoom.max(0.25);
124        [bw / z, bh / z]
125    }
126
127    fn center_bounds(img_w: u32, img_h: u32, aspect: f32, zoom: f32) -> ([f32; 2], [f32; 2]) {
128        let [su, sv] = Self::visible_span(img_w, img_h, aspect, zoom);
129        let min_x = (su * 0.5).min(0.5);
130        let max_x = (1.0 - su * 0.5).max(0.5);
131        let min_y = (sv * 0.5).min(0.5);
132        let max_y = (1.0 - sv * 0.5).max(0.5);
133        ([min_x, min_y], [max_x, max_y])
134    }
135
136    fn clamp_center(center: [f32; 2], img_w: u32, img_h: u32, aspect: f32, zoom: f32) -> [f32; 2] {
137        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, zoom);
138        [
139            center[0].clamp(min_c[0], max_c[0]),
140            center[1].clamp(min_c[1], max_c[1]),
141        ]
142    }
143
144    /// Wheel/programmatic zoom helper multiplying `zoom` by `factor` around `focal` in `viewport`.
145    /// Preserves the image pixel under `focal` (subject to valid resting crop bounds).
146    pub fn zoom_at(
147        &mut self,
148        factor: f32,
149        focal: [f32; 2],
150        viewport: Rect,
151        img_w: u32,
152        img_h: u32,
153    ) {
154        if !factor.is_finite()
155            || factor <= 0.0
156            || viewport.width <= 0.0
157            || viewport.height <= 0.0
158            || img_w == 0
159            || img_h == 0
160        {
161            return;
162        }
163        self.double_tap_anim = None;
164        self.velocity = [0.0, 0.0];
165        self.zoom_velocity = 0.0;
166        let max_z = self.max_zoom.max(1.0);
167        let aspect = viewport.width / viewport.height;
168        let old_zoom = self.zoom.max(0.25);
169        let new_zoom = (old_zoom * factor).clamp(1.0, max_z);
170        let [old_su, old_sv] = Self::visible_span(img_w, img_h, aspect, old_zoom);
171        let [new_su, new_sv] = Self::visible_span(img_w, img_h, aspect, new_zoom);
172        let fx_rel = (focal[0] - viewport.x) / viewport.width - 0.5;
173        let fy_rel = (focal[1] - viewport.y) / viewport.height - 0.5;
174        let anchor_u = self.center[0] + fx_rel * old_su;
175        let anchor_v = self.center[1] + fy_rel * old_sv;
176        let raw_center = [anchor_u - fx_rel * new_su, anchor_v - fy_rel * new_sv];
177        self.zoom = new_zoom;
178        self.center = Self::clamp_center(raw_center, img_w, img_h, aspect, new_zoom);
179    }
180
181    /// Process one input frame and advance pan, pinch, fling, rubber-band spring, and double-tap zoom.
182    pub fn update(
183        &mut self,
184        input: Input,
185        viewport: Rect,
186        img_w: u32,
187        img_h: u32,
188        motion: MotionPreference,
189        anim_scale: f32,
190    ) -> CropUpdate {
191        let prev_zoom = self.zoom;
192        let prev_center = self.center;
193        let max_z = self.max_zoom.max(1.0);
194
195        if viewport.width <= 0.0 || viewport.height <= 0.0 || img_w == 0 || img_h == 0 {
196            return CropUpdate::default();
197        }
198        let aspect = viewport.width / viewport.height;
199        let now = if input.time.is_finite() {
200            match self.last_time {
201                Some(prev) => input.time.max(prev),
202                None => input.time,
203            }
204        } else {
205            self.last_time.unwrap_or(0.0)
206        };
207        let raw_dt = match self.last_time {
208            Some(prev) => (now - prev).max(0.0),
209            None => 0.0,
210        };
211        self.last_time = Some(now);
212
213        let reduced = motion == MotionPreference::Reduced || !anim_scale.is_finite() || anim_scale <= 0.0;
214        let scale_mul = if reduced { 0.0 } else { anim_scale.max(0.0) as f64 };
215        let mut tapped = false;
216
217        // Handle cancellation / window blur cleanly.
218        if input.cancelled || input.blurred {
219            self.pointer_down = false;
220            self.dragging = false;
221            self.pinching = false;
222            self.had_pinch = false;
223            self.last_pinch_center = None;
224            self.velocity = [0.0, 0.0];
225        }
226
227        // 1. Multi-touch pinch (or trackpad pinch_scale) takes priority over single-finger pan.
228        let pinch_active = !input.cancelled
229            && !input.blurred
230            && (input.touch_count >= 2
231                || (input.pinch_scale.is_finite() && (input.pinch_scale - 1.0).abs() > 1e-4));
232        if pinch_active {
233            let focal = input
234                .pinch_center
235                .or(input.pointer)
236                .unwrap_or([
237                    viewport.x + viewport.width * 0.5,
238                    viewport.y + viewport.height * 0.5,
239                ]);
240            let prev_focal = self.last_pinch_center.unwrap_or(focal);
241            self.pinching = true;
242            self.had_pinch = true;
243            self.dragging = false;
244            self.double_tap_anim = None;
245            self.velocity = [0.0, 0.0];
246            self.zoom_velocity = 0.0;
247
248            let old_zoom = self.zoom.max(0.25);
249            let factor = if input.pinch_scale.is_finite() && input.pinch_scale > 0.0 {
250                input.pinch_scale.clamp(0.25, 4.0)
251            } else {
252                1.0
253            };
254            let raw_zoom = old_zoom * factor;
255            let new_zoom = if raw_zoom < 1.0 {
256                (1.0 - (1.0 - raw_zoom) * 0.35).max(0.75)
257            } else if raw_zoom > max_z {
258                (max_z + (raw_zoom - max_z) * 0.35).min(max_z * 1.25)
259            } else {
260                raw_zoom
261            };
262
263            let [old_su, old_sv] = Self::visible_span(img_w, img_h, aspect, old_zoom);
264            let [new_su, new_sv] = Self::visible_span(img_w, img_h, aspect, new_zoom);
265            let prev_fx = (prev_focal[0] - viewport.x) / viewport.width - 0.5;
266            let prev_fy = (prev_focal[1] - viewport.y) / viewport.height - 0.5;
267            let curr_fx = (focal[0] - viewport.x) / viewport.width - 0.5;
268            let curr_fy = (focal[1] - viewport.y) / viewport.height - 0.5;
269
270            let anchor_u = self.center[0] + prev_fx * old_su;
271            let anchor_v = self.center[1] + prev_fy * old_sv;
272            let target_cx = anchor_u - curr_fx * new_su;
273            let target_cy = anchor_v - curr_fy * new_sv;
274
275            self.zoom = new_zoom;
276            let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, new_zoom.clamp(1.0, max_z));
277            let over_u = (new_su * 0.25).clamp(0.06, 0.2);
278            let over_v = (new_sv * 0.25).clamp(0.06, 0.2);
279            self.center = [
280                rubber_band_clamp(target_cx, min_c[0], max_c[0], over_u),
281                rubber_band_clamp(target_cy, min_c[1], max_c[1], over_v),
282            ];
283            self.last_pinch_center = Some(focal);
284        } else {
285            if self.pinching {
286                self.pinching = false;
287                self.last_pinch_center = None;
288            }
289
290            // 2. Single-pointer press / drag / release.
291            if !input.cancelled && !input.blurred {
292                if input.pressed
293                    && let Some(p) = input.pointer
294                    && viewport.contains(p)
295                {
296                    self.pointer_down = true;
297                    self.dragging = false;
298                    self.had_pinch = false;
299                    self.press_origin = p;
300                    self.last_pointer = p;
301                    self.last_drag_time = now;
302                    self.velocity = [0.0, 0.0];
303                    self.double_tap_anim = None;
304                }
305
306                if self.pointer_down
307                    && let Some(p) = input.pointer
308                {
309                    let total_dist = (p[0] - self.press_origin[0]).hypot(p[1] - self.press_origin[1]);
310                    if total_dist > DRAG_SLOP_PX {
311                        self.dragging = true;
312                    }
313                    let dx = p[0] - self.last_pointer[0];
314                    let dy = p[1] - self.last_pointer[1];
315                    if self.dragging && (dx.abs() > 1e-4 || dy.abs() > 1e-4) {
316                        let [su, sv] = Self::visible_span(img_w, img_h, aspect, self.zoom);
317                        let du = -dx / viewport.width * su;
318                        let dv = -dy / viewport.height * sv;
319                        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
320                        let over = [(su * 0.25).clamp(0.06, 0.2), (sv * 0.25).clamp(0.06, 0.2)];
321                        let delta = [du, dv];
322                        let dt_drag = (now - self.last_drag_time).clamp(0.001, 0.15);
323                        let alpha = 1.0 - (-dt_drag / 0.04).exp();
324                        for i in 0..2 {
325                            let outside = self.center[i] < min_c[i] || self.center[i] > max_c[i];
326                            let step = if outside { delta[i] * 0.35 } else { delta[i] };
327                            self.center[i] = (self.center[i] + step)
328                                .clamp(min_c[i] - over[i], max_c[i] + over[i]);
329                            if outside {
330                                self.velocity[i] = 0.0;
331                            } else {
332                                let inst = (step as f64 / dt_drag).clamp(-12.0, 12.0);
333                                self.velocity[i] += (inst - self.velocity[i]) * alpha;
334                            }
335                        }
336                        self.last_drag_time = now;
337                    } else if now - self.last_drag_time > 0.1 {
338                        self.velocity = [0.0, 0.0];
339                    }
340                    self.last_pointer = p;
341                }
342
343                if input.released && self.pointer_down {
344                    let release_pos = input.pointer.unwrap_or(self.last_pointer);
345                    let was_dragging = self.dragging;
346                    let was_pinch = self.had_pinch;
347                    self.pointer_down = false;
348                    self.dragging = false;
349                    self.had_pinch = false;
350
351                    if !was_dragging && !was_pinch && viewport.contains(release_pos) {
352                        tapped = true;
353                        let is_double_tap = self.last_tap.is_some_and(|(t0, p0)| {
354                            (now - t0) <= DOUBLE_TAP_MAX_INTERVAL
355                                && (release_pos[0] - p0[0]).hypot(release_pos[1] - p0[1])
356                                    <= DOUBLE_TAP_MAX_DISTANCE
357                        });
358                        if is_double_tap {
359                            self.last_tap = None;
360                            let target_zoom = if self.zoom > 1.05 {
361                                1.0
362                            } else {
363                                2.0_f32.min(max_z)
364                            };
365                            let [old_su, old_sv] = Self::visible_span(img_w, img_h, aspect, self.zoom);
366                            let [new_su, new_sv] = Self::visible_span(img_w, img_h, aspect, target_zoom);
367                            let fx_rel = (release_pos[0] - viewport.x) / viewport.width - 0.5;
368                            let fy_rel = (release_pos[1] - viewport.y) / viewport.height - 0.5;
369                            let anchor_u = self.center[0] + fx_rel * old_su;
370                            let anchor_v = self.center[1] + fy_rel * old_sv;
371                            let to_center = Self::clamp_center(
372                                [anchor_u - fx_rel * new_su, anchor_v - fy_rel * new_sv],
373                                img_w,
374                                img_h,
375                                aspect,
376                                target_zoom,
377                            );
378                            self.velocity = [0.0, 0.0];
379                            self.zoom_velocity = 0.0;
380                            if reduced {
381                                self.zoom = target_zoom;
382                                self.center = to_center;
383                                self.double_tap_anim = None;
384                            } else {
385                                self.double_tap_anim = Some(DoubleTapAnim {
386                                    start_time: now,
387                                    duration: DOUBLE_TAP_DURATION * scale_mul,
388                                    from_zoom: self.zoom,
389                                    to_zoom: target_zoom,
390                                    from_center: self.center,
391                                    to_center,
392                                });
393                            }
394                        } else {
395                            self.last_tap = Some((now, release_pos));
396                        }
397                    } else {
398                        self.last_tap = None;
399                        if now - self.last_drag_time > 0.1 || reduced {
400                            self.velocity = [0.0, 0.0];
401                        } else {
402                            // Clear fling velocity on axes already past valid bounds so bounce-back dominates.
403                            let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
404                            for i in 0..2 {
405                                if self.center[i] < min_c[i] || self.center[i] > max_c[i] {
406                                    self.velocity[i] = 0.0;
407                                }
408                            }
409                            if self.velocity[0].hypot(self.velocity[1]) < 0.04 {
410                                self.velocity = [0.0, 0.0];
411                            }
412                        }
413                    }
414                }
415            }
416        }
417
418        // 3. Advance animations / inertial fling / spring bounce-back when not actively dragging or pinching.
419        let mut animating = false;
420        if !self.pointer_down && !self.pinching {
421            if reduced {
422                if let Some(anim) = self.double_tap_anim.take() {
423                    self.zoom = anim.to_zoom;
424                    self.center = anim.to_center;
425                }
426                self.zoom = self.zoom.clamp(1.0, max_z);
427                self.center = Self::clamp_center(self.center, img_w, img_h, aspect, self.zoom);
428                self.velocity = [0.0, 0.0];
429                self.zoom_velocity = 0.0;
430            } else if let Some(anim) = self.double_tap_anim {
431                let p = if anim.duration > 0.0 {
432                    ((now - anim.start_time) / anim.duration).clamp(0.0, 1.0) as f32
433                } else {
434                    1.0
435                };
436                let e = crate::timing::Easing::Emphasized.sample(p);
437                self.zoom = anim.from_zoom + (anim.to_zoom - anim.from_zoom) * e;
438                self.center = [
439                    anim.from_center[0] + (anim.to_center[0] - anim.from_center[0]) * e,
440                    anim.from_center[1] + (anim.to_center[1] - anim.from_center[1]) * e,
441                ];
442                if p >= 1.0 {
443                    self.zoom = anim.to_zoom;
444                    self.center = anim.to_center;
445                    self.double_tap_anim = None;
446                } else {
447                    animating = true;
448                }
449            } else {
450                let sim_dt = raw_dt * scale_mul;
451                let zoom_target = self.zoom.clamp(1.0, max_z) as f64;
452                let zoom_out = (self.zoom as f64 - zoom_target).abs() > 1e-4
453                    || self.zoom_velocity.abs() > 1e-3;
454                if zoom_out && sim_dt > 0.0 {
455                    let mut z = self.zoom as f64;
456                    advance_spring(&mut z, &mut self.zoom_velocity, zoom_target, sim_dt);
457                    self.zoom = z as f32;
458                }
459
460                // Integrate 2D fling & elastic boundary bounce-back cleanly even across large timestamps.
461                if sim_dt > 0.0 {
462                    let total_steps = ((sim_dt / 0.016).ceil() as usize).clamp(1, 250);
463                    if sim_dt > 4.0 {
464                        // Past 4s of scaled time, both fling (e^-16.8) and spring (e^-95) are fully settled.
465                        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
466                        for i in 0..2 {
467                            let free_disp = (self.velocity[i] / FLING_DECAY_RATE) as f32;
468                            self.center[i] = (self.center[i] + free_disp).clamp(min_c[i], max_c[i]);
469                            self.velocity[i] = 0.0;
470                        }
471                    } else {
472                        let step_dt = sim_dt / total_steps as f64;
473                        let decay = (-FLING_DECAY_RATE * step_dt).exp();
474                        let integral = (1.0 - decay) / FLING_DECAY_RATE;
475                        let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
476                        for _ in 0..total_steps {
477                            let mut any_active = false;
478                            for i in 0..2 {
479                                let lo = min_c[i] as f64;
480                                let hi = max_c[i] as f64;
481                                let mut c = self.center[i] as f64;
482                                if c < lo || c > hi {
483                                    let target = c.clamp(lo, hi);
484                                    advance_spring(&mut c, &mut self.velocity[i], target, step_dt);
485                                    self.center[i] = c as f32;
486                                    if (c - target).abs() > 1e-4 || self.velocity[i].abs() > 1e-3 {
487                                        any_active = true;
488                                    }
489                                } else if self.velocity[i].abs() > 1e-4 {
490                                    let next = c + self.velocity[i] * integral;
491                                    self.velocity[i] *= decay;
492                                    if next < lo || next > hi {
493                                        let edge = next.clamp(lo, hi);
494                                        let overshoot = (next - edge) * 0.35;
495                                        self.center[i] = (edge + overshoot) as f32;
496                                        self.velocity[i] *= 0.35;
497                                        any_active = true;
498                                    } else {
499                                        self.center[i] = next as f32;
500                                        any_active = true;
501                                    }
502                                }
503                            }
504                            if !any_active {
505                                break;
506                            }
507                        }
508                    }
509                }
510
511                // Settle thresholds so idle state returns animating = false cleanly.
512                let (min_c, max_c) = Self::center_bounds(img_w, img_h, aspect, self.zoom.clamp(1.0, max_z));
513                let mut center_moving = false;
514                for i in 0..2 {
515                    let clamped = self.center[i].clamp(min_c[i], max_c[i]);
516                    if (self.center[i] - clamped).abs() <= 1e-4 && self.velocity[i].abs() < 0.004 {
517                        self.center[i] = clamped;
518                        self.velocity[i] = 0.0;
519                    } else if self.center[i] != clamped || self.velocity[i].abs() >= 0.004 {
520                        center_moving = true;
521                    }
522                }
523                let zoom_clamped = self.zoom.clamp(1.0, max_z);
524                let zoom_moving = if (self.zoom - zoom_clamped).abs() <= 1e-4
525                    && self.zoom_velocity.abs() < 1e-3
526                {
527                    self.zoom = zoom_clamped;
528                    self.zoom_velocity = 0.0;
529                    false
530                } else {
531                    true
532                };
533                animating = center_moving || zoom_moving;
534            }
535        }
536
537        let changed = (self.zoom - prev_zoom).abs() > 1e-6
538            || (self.center[0] - prev_center[0]).abs() > 1e-6
539            || (self.center[1] - prev_center[1]).abs() > 1e-6;
540        CropUpdate {
541            changed,
542            animating,
543            tapped,
544        }
545    }
546
547    /// Integer pixel crop rectangle `(x, y, width, height)` inside `(img_w, img_h)` for `aspect`.
548    pub fn crop_rect(&self, img_w: u32, img_h: u32, aspect: f32) -> (u32, u32, u32, u32) {
549        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
550            return (0, 0, img_w, img_h);
551        }
552        let z = self.zoom.clamp(1.0, self.max_zoom.max(1.0));
553        let [su, sv] = Self::visible_span(img_w, img_h, aspect, z);
554        let c = Self::clamp_center(self.center, img_w, img_h, aspect, z);
555        let u0 = (c[0] - su * 0.5).clamp(0.0, 1.0);
556        let v0 = (c[1] - sv * 0.5).clamp(0.0, 1.0);
557        let w = (su * img_w as f32).round().clamp(1.0, img_w as f32) as u32;
558        let h = (sv * img_h as f32).round().clamp(1.0, img_h as f32) as u32;
559        let x = (u0 * img_w as f32).round().clamp(0.0, (img_w - w) as f32) as u32;
560        let y = (v0 * img_h as f32).round().clamp(0.0, (img_h - h) as f32) as u32;
561        (x, y, w, h)
562    }
563
564    /// Normalized `[u0, v0, u1, v1]` UV coordinates currently visible in the viewport.
565    pub fn visible_uv(&self, img_w: u32, img_h: u32, aspect: f32) -> [f32; 4] {
566        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
567            return [0.0, 0.0, 1.0, 1.0];
568        }
569        let [su, sv] = Self::visible_span(img_w, img_h, aspect, self.zoom);
570        [
571            self.center[0] - su * 0.5,
572            self.center[1] - sv * 0.5,
573            self.center[0] + su * 0.5,
574            self.center[1] + sv * 0.5,
575        ]
576    }
577
578    /// Compute normalized `[u0, v0, u1, v1]` UV coordinates for Android home-screen wallpaper parallax
579    /// at horizontal page offset `x_offset` (`0.0..=1.0`) across `parallax_pages` screens.
580    pub fn parallax_uv(
581        img_w: u32,
582        img_h: u32,
583        aspect: f32,
584        x_offset: f32,
585        parallax_pages: u32,
586    ) -> [f32; 4] {
587        if img_w == 0 || img_h == 0 || !aspect.is_finite() || aspect <= 0.0 {
588            return [0.0, 0.0, 1.0, 1.0];
589        }
590        let [base_w, base_h] = Self::base_span(img_w, img_h, aspect);
591        let slack = (1.0 - base_w).max(0.0);
592        let travel = if parallax_pages <= 1 {
593            0.0
594        } else {
595            slack.min(base_w * 0.5 * (parallax_pages - 1) as f32)
596        };
597        let u_min = 0.5 - base_w * 0.5 - travel * 0.5;
598        let t = if x_offset.is_finite() {
599            x_offset.clamp(0.0, 1.0)
600        } else {
601            0.5
602        };
603        let u0 = (u_min + travel * t).clamp(0.0, (1.0 - base_w).max(0.0));
604        let u1 = (u0 + base_w).min(1.0);
605        let v0 = ((1.0 - base_h) * 0.5).clamp(0.0, 1.0);
606        let v1 = (v0 + base_h).min(1.0);
607        [u0, v0, u1, v1]
608    }
609}
610
611fn rubber_band_clamp(value: f32, min: f32, max: f32, max_over: f32) -> f32 {
612    if value < min {
613        let excess = min - value;
614        min - (excess * 0.35).min(max_over)
615    } else if value > max {
616        let excess = value - max;
617        max + (excess * 0.35).min(max_over)
618    } else {
619        value
620    }
621}
622
623/// Exact analytic damped harmonic oscillator matching Bhoo's Standard spatial spring
624/// (`stiffness = 700.0`, `damping = 0.9`).
625fn advance_spring(value: &mut f64, velocity: &mut f64, target: f64, dt: f64) {
626    let omega = SPRING_STIFFNESS.sqrt();
627    let disp = *value - target;
628    let rate = SPRING_DAMPING * omega;
629    let freq = omega * (1.0 - SPRING_DAMPING * SPRING_DAMPING).sqrt();
630    let c = (*velocity + rate * disp) / freq;
631    let phase = freq * dt;
632    let wave = disp * phase.cos() + c * phase.sin();
633    let decay = (-rate * dt).exp();
634    *value = target + wave * decay;
635    *velocity = (freq * (-disp * phase.sin() + c * phase.cos()) - rate * wave) * decay;
636    if (*value - target).abs() < 1e-4 && velocity.abs() < 1e-3 {
637        *value = target;
638        *velocity = 0.0;
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645    use crate::PointerKind;
646
647    const VP: Rect = Rect {
648        x: 0.0,
649        y: 0.0,
650        width: 360.0,
651        height: 800.0,
652    };
653
654    fn touch(p: [f32; 2], pressed: bool, released: bool, time: f64) -> Input {
655        Input {
656            pointer: Some(p),
657            pointer_kind: PointerKind::Touch,
658            pressed,
659            released,
660            time,
661            touch_count: if released { 0 } else { 1 },
662            ..Input::default()
663        }
664    }
665
666    #[test]
667    fn pan_shifts_crop_center_and_bounds_crop_rect() {
668        let mut s = CropViewportState::new();
669        // Wide 2000x1000 image in portrait 360x800 viewport -> wide horizontal pan room.
670        s.update(touch([200.0, 400.0], true, false, 0.0), VP, 2000, 1000, MotionPreference::Full, 1.0);
671        let u1 = s.update(touch([100.0, 400.0], false, false, 0.05), VP, 2000, 1000, MotionPreference::Full, 1.0);
672        assert!(u1.changed);
673        // Dragging finger left moves viewport right across the image -> center[0] increases.
674        assert!(s.center[0] > 0.5);
675        s.update(touch([100.0, 400.0], false, true, 0.25), VP, 2000, 1000, MotionPreference::Full, 1.0);
676        let (x, y, w, h) = s.crop_rect(2000, 1000, VP.width / VP.height);
677        assert_eq!(h, 1000);
678        assert_eq!(w, 450);
679        assert!(x + w <= 2000 && y + h <= 1000);
680        assert!(x > (2000 - w) / 2);
681    }
682
683    #[test]
684    fn pinch_preserves_focal_image_pixel() {
685        let mut s = CropViewportState::new();
686        let focal = [270.0, 200.0]; // off-center focal point
687        let aspect = VP.width / VP.height;
688        let uv_before = s.visible_uv(2000, 2000, aspect);
689        let fx = (focal[0] - VP.x) / VP.width;
690        let fy = (focal[1] - VP.y) / VP.height;
691        let pixel_u_before = uv_before[0] + fx * (uv_before[2] - uv_before[0]);
692        let pixel_v_before = uv_before[1] + fy * (uv_before[3] - uv_before[1]);
693
694        let pinch = Input {
695            pinch_scale: 2.0,
696            pinch_center: Some(focal),
697            touch_count: 2,
698            time: 0.1,
699            ..Input::default()
700        };
701        let u = s.update(pinch, VP, 2000, 2000, MotionPreference::Full, 1.0);
702        assert!(u.changed);
703        assert!((s.zoom - 2.0).abs() < 1e-4);
704
705        let uv_after = s.visible_uv(2000, 2000, aspect);
706        let pixel_u_after = uv_after[0] + fx * (uv_after[2] - uv_after[0]);
707        let pixel_v_after = uv_after[1] + fy * (uv_after[3] - uv_after[1]);
708        assert!((pixel_u_after - pixel_u_before).abs() < 1e-4);
709        assert!((pixel_v_after - pixel_v_before).abs() < 1e-4);
710
711        // Wheel helper also preserves focal point cleanly.
712        let mut w = CropViewportState::new();
713        w.zoom_at(2.0, focal, VP, 2000, 2000);
714        let uv_w = w.visible_uv(2000, 2000, aspect);
715        let pu = uv_w[0] + fx * (uv_w[2] - uv_w[0]);
716        let pv = uv_w[1] + fy * (uv_w[3] - uv_w[1]);
717        assert!((pu - pixel_u_before).abs() < 1e-4);
718        assert!((pv - pixel_v_before).abs() < 1e-4);
719    }
720
721    #[test]
722    fn rubber_band_overscroll_bounces_back_to_valid_bounds() {
723        let mut s = CropViewportState::new();
724        // Image matches viewport aspect -> valid center is strictly [0.5, 0.5] at zoom=1.0.
725        s.update(touch([180.0, 400.0], true, false, 0.0), VP, 360, 800, MotionPreference::Full, 1.0);
726        s.update(touch([320.0, 400.0], false, false, 0.05), VP, 360, 800, MotionPreference::Full, 1.0);
727        assert!(s.center[0] < 0.5, "rubber band should allow overscroll during drag");
728        s.update(touch([320.0, 400.0], false, true, 0.25), VP, 360, 800, MotionPreference::Full, 1.0);
729
730        let mid = s.update(Input { time: 0.30, ..Input::default() }, VP, 360, 800, MotionPreference::Full, 1.0);
731        assert!(mid.animating);
732
733        let mut settled = false;
734        for step in 1..=90 {
735            let res = s.update(
736                Input {
737                    time: 0.30 + step as f64 / 60.0,
738                    ..Input::default()
739                },
740                VP,
741                360,
742                800,
743                MotionPreference::Full,
744                1.0,
745            );
746            if !res.animating {
747                settled = true;
748                break;
749            }
750        }
751        assert!(settled, "spring bounce-back should settle to idle");
752        assert!((s.center[0] - 0.5).abs() < 1e-4);
753        assert!((s.center[1] - 0.5).abs() < 1e-4);
754    }
755
756    #[test]
757    fn fling_coasts_and_settles_to_idle() {
758        let mut s = CropViewportState::new();
759        s.zoom = 2.5;
760        s.update(touch([260.0, 500.0], true, false, 0.0), VP, 2000, 2000, MotionPreference::Full, 1.0);
761        s.update(touch([180.0, 430.0], false, false, 0.02), VP, 2000, 2000, MotionPreference::Full, 1.0);
762        s.update(touch([100.0, 360.0], false, false, 0.04), VP, 2000, 2000, MotionPreference::Full, 1.0);
763        let at_release = s.center;
764        let rel = s.update(touch([100.0, 360.0], false, true, 0.04), VP, 2000, 2000, MotionPreference::Full, 1.0);
765        assert!(rel.animating);
766
767        let mut settled = false;
768        for i in 1..=180 {
769            let r = s.update(
770                Input {
771                    time: 0.04 + i as f64 / 60.0,
772                    ..Input::default()
773                },
774                VP,
775                2000,
776                2000,
777                MotionPreference::Full,
778                1.0,
779            );
780            if !r.animating {
781                settled = true;
782                break;
783            }
784        }
785        assert!(settled, "inertial fling must settle cleanly to idle");
786        assert!(s.center[0] > at_release[0]);
787        assert!(s.center[1] > at_release[1]);
788    }
789
790    #[test]
791    fn double_tap_toggles_zoom_and_respects_reduced_motion() {
792        let mut s = CropViewportState::new();
793        let tap_pt = [260.0, 300.0];
794        // First tap
795        s.update(touch(tap_pt, true, false, 0.0), VP, 1000, 2000, MotionPreference::Full, 1.0);
796        let t1 = s.update(touch(tap_pt, false, true, 0.05), VP, 1000, 2000, MotionPreference::Full, 1.0);
797        assert!(t1.tapped);
798        assert!((s.zoom - 1.0).abs() < 1e-4);
799
800        // Second tap within 0.32s triggers 1.0x -> 2.0x over 0.26s
801        s.update(touch(tap_pt, true, false, 0.16), VP, 1000, 2000, MotionPreference::Full, 1.0);
802        let t2 = s.update(touch(tap_pt, false, true, 0.20), VP, 1000, 2000, MotionPreference::Full, 1.0);
803        assert!(t2.tapped);
804        assert!(t2.animating);
805
806        let mid = s.update(Input { time: 0.33, ..Input::default() }, VP, 1000, 2000, MotionPreference::Full, 1.0);
807        assert!(mid.animating && s.zoom > 1.2 && s.zoom < 2.0);
808        let end = s.update(Input { time: 0.47, ..Input::default() }, VP, 1000, 2000, MotionPreference::Full, 1.0);
809        assert!(!end.animating);
810        assert!((s.zoom - 2.0).abs() < 1e-4);
811        assert!(s.center[0] > 0.5, "double-tap anchor shifts center toward tap point");
812
813        // Second double-tap under Reduced motion snaps immediately back to 1.0x!
814        s.update(touch(tap_pt, true, false, 1.0), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
815        s.update(touch(tap_pt, false, true, 1.04), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
816        s.update(touch(tap_pt, true, false, 1.12), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
817        let snap = s.update(touch(tap_pt, false, true, 1.16), VP, 1000, 2000, MotionPreference::Reduced, 1.0);
818        assert!(!snap.animating);
819        assert!((s.zoom - 1.0).abs() < 1e-4);
820    }
821
822    #[test]
823    fn parallax_uv_stays_within_unit_bounds_and_pans_smoothly() {
824        let aspect = 9.0 / 20.0;
825        let single = CropViewportState::parallax_uv(2048, 1024, aspect, 0.0, 1);
826        let single_end = CropViewportState::parallax_uv(2048, 1024, aspect, 1.0, 1);
827        assert_eq!(single, single_end);
828
829        let left = CropViewportState::parallax_uv(2048, 1024, aspect, 0.0, 3);
830        let mid = CropViewportState::parallax_uv(2048, 1024, aspect, 0.5, 3);
831        let right = CropViewportState::parallax_uv(2048, 1024, aspect, 1.0, 3);
832        for uv in [left, mid, right] {
833            assert!(uv[0] >= 0.0 && uv[2] <= 1.0 && uv[0] < uv[2]);
834            assert!(uv[1] >= 0.0 && uv[3] <= 1.0 && uv[1] < uv[3]);
835        }
836        assert!(left[0] < mid[0] && mid[0] < right[0]);
837        assert!(((left[2] - left[0]) - (right[2] - right[0])).abs() < 1e-5);
838        assert!(((mid[0] + mid[2]) * 0.5 - 0.5).abs() < 1e-5);
839    }
840}