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, PointerEvent, PointerId, 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 // The first pointer that went down, which taps. A pointer that joins it only pinches.
262 leader: Option<PointerId>,
263 active: bool,
264 travel: f32,
265 tap_down: Option<Point>,
266 last_tap: Option<(PointerUptime, Point)>,
267}
268
269impl ZoomGestureState {
270 fn is_double_tap(&self, uptime: PointerUptime, position: Point) -> bool {
271 self.last_tap.is_some_and(|(tap_uptime, tap_position)| {
272 uptime
273 .millis_since(tap_uptime)
274 .is_some_and(|millis| millis <= DOUBLE_TAP_TIMEOUT_MS)
275 && (position - tap_position).distance() <= DOUBLE_TAP_SLOP
276 })
277 }
278
279 // The first pointer down starts a tap and leads the gesture.
280 fn begin_tap(&mut self, at: Point, pointer: PointerId) {
281 self.travel = 0.0;
282 self.tap_down = Some(at);
283 self.leader = Some(pointer);
284 }
285
286 // Whether `event` is from the leader, which gives the lead up when it lifts.
287 fn leads(&mut self, event: &PointerEvent) -> bool {
288 let leads = self.leader == Some(event.id);
289 if leads && event.kind == PointerEventKind::Up {
290 self.leader = None;
291 }
292 leads
293 }
294
295 fn abandon_tap(&mut self) {
296 self.tap_down = None;
297 self.last_tap = None;
298 self.leader = None;
299 }
300}
301
302impl Modifier {
303 /// Makes the element respond to transform gestures, updating `state`.
304 ///
305 /// Recognizes two-finger pinch/pan (touch), one-finger pan while the
306 /// content is zoomed in (`scale > 1`), a double-tap that resets a
307 /// transformed state to identity, and [`PointerEventKind::Zoom`] steps
308 /// (desktop ctrl+wheel, browser pinch). Pan — including the pinch
309 /// centroid — is inert while `scale <= 1`. Rendering is the app's
310 /// choice — typically `.graphics_layer(move || state.layer())` on the
311 /// same or a child element.
312 pub fn zoomable(self, state: ZoomState) -> Self {
313 let gesture_state = Rc::new(RefCell::new(ZoomGestureState::default()));
314 let key = state.id();
315
316 self.pointer_input(key, move |scope| {
317 let gesture_state = Rc::clone(&gesture_state);
318
319 async move {
320 scope
321 .await_pointer_event_scope(|await_scope| async move {
322 loop {
323 let event = await_scope.await_pointer_event().await;
324
325 match event.kind {
326 PointerEventKind::Zoom => {
327 if !event.is_consumed() && event.zoom_delta != 1.0 {
328 state.apply_transform(
329 event.global_position,
330 Point { x: 0.0, y: 0.0 },
331 event.zoom_delta,
332 );
333 event.consume();
334 }
335 }
336 PointerEventKind::Cancel => {
337 let mut gs = gesture_state.borrow_mut();
338 gs.tracker.reset();
339 gs.active = false;
340 gs.travel = 0.0;
341 gs.abandon_tap();
342 }
343 PointerEventKind::Down
344 | PointerEventKind::Move
345 | PointerEventKind::Up => {
346 let mut gs = gesture_state.borrow_mut();
347
348 if event.is_consumed() {
349 gs.tracker.reset();
350 gs.active = false;
351 gs.travel = 0.0;
352 gs.abandon_tap();
353 continue;
354 }
355
356 let tracked =
357 event.copy_with_local_position(event.global_position);
358 let step = gs.tracker.handle_event(&tracked);
359
360 if event.kind == PointerEventKind::Down {
361 if gs.tracker.pointer_count() >= 2 {
362 gs.active = true;
363 gs.tap_down = None;
364 } else {
365 gs.begin_tap(event.global_position, event.id);
366 }
367 if gs.leader != Some(event.id) {
368 event.consume();
369 }
370 continue;
371 }
372
373 let leads = gs.leads(&event);
374 if event.kind == PointerEventKind::Up && leads {
375 let up_position = event.global_position;
376 let is_tap = !gs.active
377 && gs.tap_down.is_some_and(|down| {
378 (up_position - down).distance() <= DRAG_THRESHOLD
379 });
380 gs.tap_down = None;
381 if is_tap {
382 let uptime = event.uptime();
383 if gs.is_double_tap(uptime, up_position) {
384 gs.last_tap = None;
385 if state.is_transformed() {
386 state.reset();
387 event.consume();
388 }
389 } else {
390 gs.last_tap = Some((uptime, up_position));
391 }
392 } else {
393 gs.last_tap = None;
394 }
395 }
396
397 match step {
398 TransformGestureEvent::Transform {
399 pan,
400 zoom,
401 centroid,
402 pointer_count,
403 } => {
404 if pointer_count >= 2 {
405 gs.active = true;
406 } else if !gs.active && state.is_zoomed_in() {
407 gs.travel += pan.distance();
408 if gs.travel > DRAG_THRESHOLD {
409 gs.active = true;
410 }
411 }
412
413 if gs.active {
414 state.apply_transform(centroid, pan, zoom);
415 event.consume();
416 }
417 }
418 TransformGestureEvent::Ended => {
419 let was_active = gs.active;
420 gs.active = false;
421 gs.travel = 0.0;
422 if was_active {
423 event.consume();
424 }
425 }
426 TransformGestureEvent::None => {
427 if !leads
428 || (gs.active
429 && matches!(
430 event.kind,
431 PointerEventKind::Up
432 | PointerEventKind::Cancel
433 ))
434 {
435 event.consume();
436 }
437 }
438 }
439 }
440 _ => {}
441 }
442 }
443 })
444 .await;
445 }
446 })
447 }
448}
449
450#[cfg(test)]
451#[path = "tests/zoom_tests.rs"]
452mod tests;