Skip to main content

cranpose_ui/
zoom.rs

1//! Pinch-to-zoom / pan state and the `Modifier::zoomable` gesture modifier.
2//!
3//! # Overview
4//! [`ZoomState`] is a pure transform model (scale + offset) mirroring the
5//! [`ScrollState`](crate::ScrollState) pattern: reactive `MutableState`
6//! internals so composables and lazy `graphics_layer` closures observe
7//! changes, plus non-reactive accessors for gesture handlers.
8//!
9//! The app renders the transform with the existing graphics-layer pipeline:
10//!
11//! ```text
12//! let zoom = ZoomState::new();
13//! Image(
14//!     Modifier::empty()
15//!         .fill_max_size()
16//!         .zoomable(zoom.clone())
17//!         .graphics_layer(move || zoom.layer()),
18//!     ...
19//! );
20//! ```
21//!
22//! # Gestures
23//! - **Two-finger pinch** (Android/touch): scale about the finger centroid,
24//!   plus centroid pan. Activates immediately when the second finger lands.
25//! - **One-finger pan**: activates after the drag threshold, and only while
26//!   the content is zoomed in (`scale > 1`) so an unzoomed zoomable never
27//!   steals drags from an enclosing scrollable.
28//! - **Double tap**: resets a transformed state back to identity.
29//! - **Ctrl+wheel / trackpad pinch** (desktop, web): discrete
30//!   [`PointerEventKind::Zoom`] steps about the cursor.
31//!
32//! # Pan gating
33//! ALL pan — one-finger drags and the two-finger pinch centroid — is inert
34//! while `scale <= 1`: [`ZoomState::apply_transform`] clamps the offset back
35//! to zero whenever the resulting scale is at (or below) identity, so a pinch
36//! that zooms back out never strands the content at a stray offset.
37//!
38//! # Coordinate space
39//! Gesture math runs in window (global) coordinates, which stay stable while
40//! the element's own graphics layer is being transformed. The focal-point
41//! anchoring is therefore exact for zoomable surfaces positioned at the
42//! window origin (the fullscreen viewer case) and approximate otherwise.
43
44use std::{
45    cell::{Cell, RefCell},
46    hash::{Hash, Hasher},
47    rc::Rc,
48};
49
50use cranpose_core::{OwnedMutableState, RuntimeCell};
51use cranpose_foundation::{
52    DRAG_THRESHOLD, PointerUptime,
53    nodes::input::gestures::{TransformGesture, TransformGestureEvent},
54};
55use cranpose_ui_graphics::{GraphicsLayer, Point, TransformOrigin};
56
57use crate::modifier::{Modifier, PointerEventKind};
58
59const SCALE_EPSILON: f32 = 1e-3;
60
61const DOUBLE_TAP_TIMEOUT_MS: i64 = 300;
62
63const DOUBLE_TAP_SLOP: f32 = 100.0;
64
65/// Shared zoom/pan transform state for `Modifier::zoomable`.
66///
67/// Cloning shares the same underlying state (like `ScrollState`).
68#[derive(Clone, Copy)]
69pub struct ZoomState {
70    inner: RuntimeCell<ZoomStateInner>,
71}
72
73struct ZoomStateInner {
74    scale: OwnedMutableState<f32>,
75    offset_x: OwnedMutableState<f32>,
76    offset_y: OwnedMutableState<f32>,
77    min_scale: Cell<f32>,
78    max_scale: Cell<f32>,
79}
80
81impl Default for ZoomState {
82    fn default() -> Self {
83        Self::new()
84    }
85}
86
87impl ZoomState {
88    /// Creates a state at scale 1.0 with a 1.0..=8.0 zoom range.
89    pub fn new() -> Self {
90        Self::with_scale_range(1.0, 8.0)
91    }
92
93    /// Creates a state at scale 1.0 clamping zoom to `min_scale..=max_scale`.
94    pub fn with_scale_range(min_scale: f32, max_scale: f32) -> Self {
95        assert!(
96            min_scale > 0.0 && max_scale >= min_scale,
97            "invalid zoom range {min_scale}..{max_scale}"
98        );
99        let runtime = cranpose_core::current_runtime_handle()
100            .expect("ZoomState::with_scale_range requires an active runtime");
101        Self {
102            inner: RuntimeCell::with_runtime(
103                ZoomStateInner {
104                    scale: OwnedMutableState::with_runtime(
105                        1.0f32.clamp(min_scale, max_scale),
106                        runtime.clone(),
107                    ),
108                    offset_x: OwnedMutableState::with_runtime(0.0f32, runtime.clone()),
109                    offset_y: OwnedMutableState::with_runtime(0.0f32, runtime.clone()),
110                    min_scale: Cell::new(min_scale),
111                    max_scale: Cell::new(max_scale),
112                },
113                runtime,
114            ),
115        }
116    }
117
118    fn inner(&self) -> Rc<ZoomStateInner> {
119        self.inner.get()
120    }
121
122    /// Stable identity of this state (shared across clones).
123    pub fn id(&self) -> u64 {
124        let mut hasher = cranpose_core::hash::default::new();
125        self.inner.hash(&mut hasher);
126        hasher.finish()
127    }
128
129    /// Current scale (reactive — subscribes the caller to changes).
130    pub fn scale(&self) -> f32 {
131        self.inner().scale.with(|s| *s)
132    }
133
134    /// Current scale without snapshot subscription.
135    pub fn scale_non_reactive(&self) -> f32 {
136        self.inner().scale.get_non_reactive()
137    }
138
139    /// Current pan offset in dp (reactive).
140    pub fn offset(&self) -> Point {
141        let inner = self.inner();
142        Point {
143            x: inner.offset_x.with(|v| *v),
144            y: inner.offset_y.with(|v| *v),
145        }
146    }
147
148    /// Current pan offset without snapshot subscription.
149    pub fn offset_non_reactive(&self) -> Point {
150        let inner = self.inner();
151        Point {
152            x: inner.offset_x.get_non_reactive(),
153            y: inner.offset_y.get_non_reactive(),
154        }
155    }
156
157    /// Returns the smallest scale this state allows.
158    pub fn min_scale(&self) -> f32 {
159        self.inner().min_scale.get()
160    }
161
162    /// Returns the largest scale this state allows.
163    pub fn max_scale(&self) -> f32 {
164        self.inner().max_scale.get()
165    }
166
167    /// Whether the content is currently transformed away from identity.
168    pub fn is_transformed(&self) -> bool {
169        let offset = self.offset_non_reactive();
170        (self.scale_non_reactive() - 1.0).abs() > SCALE_EPSILON
171            || offset.x != 0.0
172            || offset.y != 0.0
173    }
174
175    /// Whether the content is currently zoomed in beyond identity.
176    ///
177    /// Pan gestures only apply while this is `true`: an image at (or below)
178    /// its natural size has nothing to pan, and drags over it belong to
179    /// enclosing scrollables.
180    pub fn is_zoomed_in(&self) -> bool {
181        self.scale_non_reactive() > 1.0 + SCALE_EPSILON
182    }
183
184    /// Sets the scale directly (clamped to the configured range).
185    pub fn set_scale(&self, scale: f32) {
186        let clamped = scale.clamp(self.min_scale(), self.max_scale());
187        self.inner().scale.set(clamped);
188    }
189
190    /// Sets the pan offset directly.
191    pub fn set_offset(&self, offset: Point) {
192        let inner = self.inner();
193        inner.offset_x.set(offset.x);
194        inner.offset_y.set(offset.y);
195    }
196
197    /// Resets to identity (scale clamped into range, zero offset).
198    pub fn reset(&self) {
199        self.set_scale(1.0);
200        self.set_offset(Point { x: 0.0, y: 0.0 });
201    }
202
203    /// Applies one gesture step: zoom by `zoom` about `centroid`, then pan.
204    ///
205    /// `centroid` and `pan` are in the element's display frame; for finger
206    /// gestures the anchor must be the centroid of the pointers BEFORE the
207    /// step (as reported by `TransformGestureEvent::Transform`). With the
208    /// top-left-origin layer produced by [`ZoomState::layer`], a content
209    /// point `c` renders at `p = c * scale + offset`; this update applies
210    /// `p' = zoom * (p - centroid) + centroid + pan`, which keeps the
211    /// content glued to the fingers.
212    ///
213    /// Pan is inert while not zoomed in: whenever the resulting scale is at
214    /// (or below) identity the offset is clamped back to zero, so a pinch
215    /// that zooms out to `scale <= 1` — or a pure centroid pan at identity —
216    /// never leaves the content stranded at a stray offset.
217    pub fn apply_transform(&self, centroid: Point, pan: Point, zoom: f32) {
218        let old_scale = self.scale_non_reactive();
219        let new_scale = (old_scale * zoom).clamp(self.min_scale(), self.max_scale());
220        let effective_zoom = new_scale / old_scale;
221        let old_offset = self.offset_non_reactive();
222
223        let new_offset = if new_scale <= 1.0 + SCALE_EPSILON {
224            Point { x: 0.0, y: 0.0 }
225        } else {
226            Point {
227                x: centroid.x - (centroid.x - old_offset.x) * effective_zoom + pan.x,
228                y: centroid.y - (centroid.y - old_offset.y) * effective_zoom + pan.y,
229            }
230        };
231
232        if new_scale != old_scale {
233            self.inner().scale.set(new_scale);
234        }
235        if new_offset != old_offset {
236            self.set_offset(new_offset);
237        }
238    }
239
240    /// Builds the [`GraphicsLayer`] rendering this transform.
241    ///
242    /// Reads the state reactively, so it is meant for the lazy
243    /// `Modifier::graphics_layer(move || state.layer())` form.
244    pub fn layer(&self) -> GraphicsLayer {
245        let scale = self.scale();
246        let offset = self.offset();
247        GraphicsLayer {
248            scale_x: scale,
249            scale_y: scale,
250            translation_x: offset.x,
251            translation_y: offset.y,
252            transform_origin: TransformOrigin::new(0.0, 0.0),
253            ..Default::default()
254        }
255    }
256}
257
258#[derive(Default)]
259struct ZoomGestureState {
260    tracker: TransformGesture,
261    active: bool,
262    travel: f32,
263    tap_down: Option<Point>,
264    last_tap: Option<(PointerUptime, Point)>,
265}
266
267impl ZoomGestureState {
268    fn is_double_tap(&self, uptime: PointerUptime, position: Point) -> bool {
269        self.last_tap.is_some_and(|(tap_uptime, tap_position)| {
270            uptime
271                .millis_since(tap_uptime)
272                .is_some_and(|millis| millis <= DOUBLE_TAP_TIMEOUT_MS)
273                && (position - tap_position).distance() <= DOUBLE_TAP_SLOP
274        })
275    }
276
277    fn abandon_tap(&mut self) {
278        self.tap_down = None;
279        self.last_tap = None;
280    }
281}
282
283impl Modifier {
284    /// Makes the element respond to transform gestures, updating `state`.
285    ///
286    /// Recognizes two-finger pinch/pan (touch), one-finger pan while the
287    /// content is zoomed in (`scale > 1`), a double-tap that resets a
288    /// transformed state to identity, and [`PointerEventKind::Zoom`] steps
289    /// (desktop ctrl+wheel, browser pinch). Pan — including the pinch
290    /// centroid — is inert while `scale <= 1`. Rendering is the app's
291    /// choice — typically `.graphics_layer(move || state.layer())` on the
292    /// same or a child element.
293    pub fn zoomable(self, state: ZoomState) -> Self {
294        let gesture_state = Rc::new(RefCell::new(ZoomGestureState::default()));
295        let key = state.id();
296
297        self.pointer_input(key, move |scope| {
298            let gesture_state = Rc::clone(&gesture_state);
299
300            async move {
301                scope
302                    .await_pointer_event_scope(|await_scope| async move {
303                        loop {
304                            let event = await_scope.await_pointer_event().await;
305
306                            match event.kind {
307                                PointerEventKind::Zoom => {
308                                    if !event.is_consumed() && event.zoom_delta != 1.0 {
309                                        state.apply_transform(
310                                            event.global_position,
311                                            Point { x: 0.0, y: 0.0 },
312                                            event.zoom_delta,
313                                        );
314                                        event.consume();
315                                    }
316                                }
317                                PointerEventKind::Cancel => {
318                                    let mut gs = gesture_state.borrow_mut();
319                                    gs.tracker.reset();
320                                    gs.active = false;
321                                    gs.travel = 0.0;
322                                    gs.abandon_tap();
323                                }
324                                PointerEventKind::Down
325                                | PointerEventKind::Move
326                                | PointerEventKind::Up => {
327                                    let mut gs = gesture_state.borrow_mut();
328
329                                    if event.is_consumed() {
330                                        gs.tracker.reset();
331                                        gs.active = false;
332                                        gs.travel = 0.0;
333                                        gs.abandon_tap();
334                                        continue;
335                                    }
336
337                                    let tracked =
338                                        event.copy_with_local_position(event.global_position);
339                                    let step = gs.tracker.handle_event(&tracked);
340
341                                    if event.kind == PointerEventKind::Down {
342                                        if gs.tracker.pointer_count() >= 2 {
343                                            gs.active = true;
344                                            gs.tap_down = None;
345                                        } else {
346                                            gs.travel = 0.0;
347                                            gs.tap_down = Some(event.global_position);
348                                        }
349                                        if !event.id.is_primary() {
350                                            event.consume();
351                                        }
352                                        continue;
353                                    }
354
355                                    if event.kind == PointerEventKind::Up && event.id.is_primary() {
356                                        let up_position = event.global_position;
357                                        let is_tap = !gs.active
358                                            && gs.tap_down.is_some_and(|down| {
359                                                (up_position - down).distance() <= DRAG_THRESHOLD
360                                            });
361                                        gs.tap_down = None;
362                                        if is_tap {
363                                            let uptime = event.uptime();
364                                            if gs.is_double_tap(uptime, up_position) {
365                                                gs.last_tap = None;
366                                                if state.is_transformed() {
367                                                    state.reset();
368                                                    event.consume();
369                                                }
370                                            } else {
371                                                gs.last_tap = Some((uptime, up_position));
372                                            }
373                                        } else {
374                                            gs.last_tap = None;
375                                        }
376                                    }
377
378                                    match step {
379                                        TransformGestureEvent::Transform {
380                                            pan,
381                                            zoom,
382                                            centroid,
383                                            pointer_count,
384                                        } => {
385                                            if pointer_count >= 2 {
386                                                gs.active = true;
387                                            } else if !gs.active && state.is_zoomed_in() {
388                                                gs.travel += pan.distance();
389                                                if gs.travel > DRAG_THRESHOLD {
390                                                    gs.active = true;
391                                                }
392                                            }
393
394                                            if gs.active {
395                                                state.apply_transform(centroid, pan, zoom);
396                                                event.consume();
397                                            }
398                                        }
399                                        TransformGestureEvent::Ended => {
400                                            let was_active = gs.active;
401                                            gs.active = false;
402                                            gs.travel = 0.0;
403                                            if was_active {
404                                                event.consume();
405                                            }
406                                        }
407                                        TransformGestureEvent::None => {
408                                            if !event.id.is_primary()
409                                                || (gs.active
410                                                    && matches!(
411                                                        event.kind,
412                                                        PointerEventKind::Up
413                                                            | PointerEventKind::Cancel
414                                                    ))
415                                            {
416                                                event.consume();
417                                            }
418                                        }
419                                    }
420                                }
421                                _ => {}
422                            }
423                        }
424                    })
425                    .await;
426            }
427        })
428    }
429}
430
431#[cfg(test)]
432#[path = "tests/zoom_tests.rs"]
433mod tests;