Skip to main content

mln_engine/gestures/
options.rs

1//! How gestures move each part of the camera, how individual gestures behave,
2//! and the recognizer's platform and accessibility metrics.
3
4use std::time::Duration;
5
6use crate::camera::{InvalidMomentum, MomentumDecay, MomentumSnap};
7
8/// Values every `spacing` from `offset`, in the part's unit, that report a
9/// [`GestureEvent::Notch`](crate::gestures::GestureEvent::Notch) as a gesture moves the
10/// part to or across one, for the host to play as haptic feedback. Bearing
11/// notches lie within one turn from the offset.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct Notch {
14    /// Positive.
15    pub spacing: f64,
16    pub offset: f64,
17    /// The host's name for the feedback, such as which haptic to play, which
18    /// the notch's events carry.
19    pub kind: u32,
20}
21
22impl Notch {
23    /// North.
24    pub(crate) const NORTH: Notch = Notch { spacing: 360.0, offset: 0.0, kind: 0 };
25}
26
27/// The point that a gesture's zoom or rotation holds in place.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum GestureAnchor {
30    /// The gesture's focal point: pointer position, pinch midpoint, or press
31    /// point.
32    #[default]
33    FocalPoint,
34    /// The camera's center, which the viewport's padding offsets.
35    CameraCenter,
36}
37
38/// How gestures move the map's content.
39#[derive(Clone, Copy, Debug, PartialEq)]
40pub struct PanOptions {
41    /// Whether gestures pan: drags, two fingers moving together, and deltas.
42    pub enabled: bool,
43    /// How a release glides; without it, the pan stops where the gesture
44    /// leaves it.
45    pub momentum: Option<MomentumDecay>,
46}
47
48/// How gestures move the zoom, the bearing or the pitch.
49#[derive(Clone, Debug, PartialEq)]
50pub struct AxisOptions {
51    /// Whether gestures move the part.
52    pub enabled: bool,
53    /// How a release glides; without it, the part stops where the gesture
54    /// leaves it.
55    pub momentum: Option<MomentumDecay>,
56    /// Where the part settles once its glide ends, after a gesture that
57    /// changed it.
58    pub snap: Option<MomentumSnap>,
59    /// Where the part reports notches while the recognizer's gestures, their
60    /// glides and their snaps move it. Several notches at one value report
61    /// one event, with the kind of the first in the list.
62    pub notches: Vec<Notch>,
63}
64
65/// One part of the camera that a gesture moves along a single value.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub enum Axis {
68    /// In zoom levels.
69    Zoom,
70    /// In degrees clockwise from north.
71    Bearing,
72    /// In degrees from looking straight down.
73    Pitch,
74}
75
76/// Camera-level rules: what each camera part is allowed to do, and how it
77/// glides, settles, and emits haptic notches regardless of which gesture moved
78/// it.
79#[derive(Clone, Debug, PartialEq)]
80pub struct GestureAxes {
81    pub pan: PanOptions,
82    pub zoom: AxisOptions,
83    pub bearing: AxisOptions,
84    pub pitch: AxisOptions,
85}
86
87impl Default for GestureAxes {
88    fn default() -> Self {
89        let axis = |momentum: MomentumDecay, snap: Option<MomentumSnap>, notches: Vec<Notch>| AxisOptions {
90            enabled: true,
91            momentum: Some(momentum),
92            snap,
93            notches,
94        };
95        GestureAxes {
96            pan: PanOptions { enabled: true, momentum: Some(MomentumDecay::PAN) },
97            zoom: axis(MomentumDecay::ZOOM, None, Vec::new()),
98            bearing: axis(MomentumDecay::BEARING, Some(MomentumSnap::BEARING), vec![Notch::NORTH]),
99            pitch: axis(MomentumDecay::PITCH, None, Vec::new()),
100        }
101    }
102}
103
104/// How single-pointer drags move the camera.
105#[derive(Clone, Copy, Debug, PartialEq)]
106pub struct DragOptions {
107    /// Whether single-pointer pan drags pan the map.
108    pub pan: bool,
109    /// Degrees of bearing per logical pixel of rightward rotate drag; negative
110    /// reverses.
111    pub rotate_bearing_per_px: f64,
112    /// Degrees of pitch per logical pixel of downward rotate drag; negative
113    /// tilts up as the pointer drags up.
114    pub rotate_pitch_per_px: f64,
115    /// The point held fixed while a rotate drag turns or tilts the map.
116    pub rotate_anchor: GestureAnchor,
117}
118
119impl Default for DragOptions {
120    fn default() -> Self {
121        DragOptions {
122            pan: true,
123            rotate_bearing_per_px: 0.5,
124            rotate_pitch_per_px: -0.5,
125            rotate_anchor: GestureAnchor::CameraCenter,
126        }
127    }
128}
129
130/// How two-pointer pinch, twist, and tilt gestures move the camera.
131#[derive(Clone, Copy, Debug, PartialEq)]
132pub struct PinchOptions {
133    /// Whether two fingers moving together pan the map.
134    pub pan: bool,
135    /// Whether spreading or closing two fingers zooms the map.
136    pub zoom: bool,
137    /// Whether twisting two fingers rotates the map.
138    pub rotate: bool,
139    /// Whether dragging two fingers vertically tilts the map.
140    pub pitch: bool,
141    /// When false, a pinch does not rotate once it starts zooming.
142    pub rotate_during_zoom: bool,
143    /// The point held fixed while a pinch zooms.
144    pub zoom_anchor: GestureAnchor,
145    /// The point held fixed while a pinch rotates.
146    pub rotate_anchor: GestureAnchor,
147    /// Degrees of pitch per logical pixel of downward two-finger drag;
148    /// negative tilts up as fingers move up.
149    pub pitch_per_px: f64,
150}
151
152impl Default for PinchOptions {
153    fn default() -> Self {
154        PinchOptions {
155            pan: true,
156            zoom: true,
157            rotate: true,
158            pitch: true,
159            rotate_during_zoom: true,
160            zoom_anchor: GestureAnchor::FocalPoint,
161            rotate_anchor: GestureAnchor::FocalPoint,
162            pitch_per_px: -0.5,
163        }
164    }
165}
166
167/// How a double-tap drag (quick zoom) zooms the camera.
168#[derive(Clone, Copy, Debug, PartialEq)]
169pub struct TapDragOptions {
170    /// Whether a held second press after a tap zooms on drag instead of
171    /// panning.
172    pub enabled: bool,
173    /// Zoom levels per logical pixel downward; negative zooms in as the
174    /// pointer moves up.
175    pub zoom_per_px: f64,
176    /// The point held fixed while zooming.
177    pub anchor: GestureAnchor,
178}
179
180impl Default for TapDragOptions {
181    fn default() -> Self {
182        TapDragOptions { enabled: true, zoom_per_px: 1.0 / 128.0, anchor: GestureAnchor::CameraCenter }
183    }
184}
185
186/// How a double tap or two-finger tap zooms the camera.
187#[derive(Clone, Copy, Debug, PartialEq)]
188pub struct TapZoomOptions {
189    /// Whether the tap zooms the camera. When false, the tap still reports its
190    /// [`GestureEvent`](crate::gestures::GestureEvent) for the host to handle.
191    pub enabled: bool,
192    /// Zoom levels added on tap; negative zooms out.
193    pub zoom_levels: f64,
194    /// The point held fixed while zooming.
195    pub anchor: GestureAnchor,
196}
197
198impl TapZoomOptions {
199    /// Default double-tap zoom: one level in around the tap.
200    pub const DOUBLE_TAP: Self = Self { enabled: true, zoom_levels: 1.0, anchor: GestureAnchor::FocalPoint };
201    /// Default two-finger-tap zoom: one level out around the fingers' middle.
202    pub const TWO_FINGER_TAP: Self = Self { enabled: true, zoom_levels: -1.0, anchor: GestureAnchor::FocalPoint };
203}
204
205/// How a box-zoom drag zooms the camera.
206#[derive(Clone, Copy, Debug, PartialEq)]
207pub struct BoxZoomOptions {
208    /// Whether box-zoom drags draw a box and zoom to it on release.
209    pub enabled: bool,
210    /// How long the ease into the boxed bounds lasts; zero jumps immediately.
211    pub duration: Duration,
212}
213
214impl Default for BoxZoomOptions {
215    fn default() -> Self {
216        BoxZoomOptions { enabled: true, duration: Duration::from_millis(500) }
217    }
218}
219
220/// How discrete and continuous deltas (wheel, trackpad, keys, rotary, tap
221/// zooms) step and end.
222#[derive(Clone, Copy, Debug, PartialEq)]
223pub struct DeltaOptions {
224    /// How long a discrete delta eases; zero applies the full delta immediately
225    /// within the zoom range without stepping across frames.
226    pub step_duration: Duration,
227    /// Maximum zoom levels applied in one step for continuous deltas and eased
228    /// discrete steps; eased discrete deltas carry the rest to later frames.
229    /// Does not cap immediate discrete deltas when `step_duration` is zero.
230    /// Finite and at least `1e-6`.
231    pub max_step_zoom: f64,
232    /// Deltas remain one gesture until this long after their last input and
233    /// ease.
234    pub idle: Duration,
235}
236
237impl Default for DeltaOptions {
238    fn default() -> Self {
239        DeltaOptions { step_duration: Duration::from_millis(200), max_step_zoom: 1.0, idle: Duration::from_millis(200) }
240    }
241}
242
243/// Per-gesture recognition and mapping rules.
244#[derive(Clone, Copy, Debug, PartialEq)]
245pub struct GestureBehavior {
246    pub drag: DragOptions,
247    pub pinch: PinchOptions,
248    pub tap_drag: TapDragOptions,
249    pub double_tap: TapZoomOptions,
250    pub two_finger_tap: TapZoomOptions,
251    pub box_zoom: BoxZoomOptions,
252    pub deltas: DeltaOptions,
253}
254
255impl Default for GestureBehavior {
256    fn default() -> Self {
257        GestureBehavior {
258            drag: DragOptions::default(),
259            pinch: PinchOptions::default(),
260            tap_drag: TapDragOptions::default(),
261            double_tap: TapZoomOptions::DOUBLE_TAP,
262            two_finger_tap: TapZoomOptions::TWO_FINGER_TAP,
263            box_zoom: BoxZoomOptions::default(),
264            deltas: DeltaOptions::default(),
265        }
266    }
267}
268
269/// Platform and accessibility metrics: slops, timeouts, and multi-touch
270/// recognition thresholds. Distances are in logical pixels.
271#[derive(Clone, Copy, Debug, PartialEq)]
272pub struct GestureMetrics {
273    /// How far a touch press may move and still be a tap; drags start past it.
274    pub touch_slop: f64,
275    /// How far a mouse or pen press may move and still be a tap; drags start
276    /// past it.
277    pub pointer_slop: f64,
278    /// Maximum distance between the two taps of a double tap, and maximum
279    /// travel of a two-finger tap's fingers.
280    pub double_tap_slop: f64,
281    /// Maximum time between the two taps of a double tap, and between the two
282    /// fingers of a two-finger tap.
283    pub double_tap_interval: Duration,
284    /// How long a press stays still to become a long press (positive).
285    pub long_press: Duration,
286    /// Zoom levels a pinch spreads or closes before it starts zooming.
287    pub pinch_zoom_threshold: f64,
288    /// Logical pixels along the fingers' circle a twist travels before it
289    /// starts rotating.
290    pub pinch_rotate_threshold: f64,
291    /// Logical pixels both fingers must move before two-finger tilt vs pinch
292    /// is decided.
293    pub pinch_pitch_slop: f64,
294}
295
296impl Default for GestureMetrics {
297    fn default() -> Self {
298        GestureMetrics {
299            touch_slop: 8.0,
300            pointer_slop: 3.0,
301            double_tap_slop: 40.0,
302            double_tap_interval: Duration::from_millis(300),
303            long_press: Duration::from_millis(500),
304            pinch_zoom_threshold: 0.1,
305            pinch_rotate_threshold: 25.0,
306            pinch_pitch_slop: 2.0,
307        }
308    }
309}
310
311/// Why [`GestureOptions`] are out of range.
312#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
313pub enum InvalidGestureOptions {
314    #[error("the momentum of {0}: {1}")]
315    Momentum(&'static str, InvalidMomentum),
316    #[error("the snap of {0}: {1}")]
317    Snap(&'static str, InvalidMomentum),
318    #[error("a notch of {0} needs a positive spacing and a finite offset")]
319    Notch(&'static str),
320    #[error("gesture rates and tap zoom levels must be finite")]
321    Rate,
322    #[error("deltas.max_step_zoom must be finite and at least 1e-6")]
323    MaxStepZoom,
324    #[error("gesture metric {0} must be finite and not negative")]
325    Metric(&'static str),
326    #[error("long_press must be positive")]
327    LongPress,
328}
329
330/// How the recognizer moves each part of the camera, interprets gestures, and
331/// applies platform slops and timeouts.
332#[derive(Clone, Debug, PartialEq)]
333pub struct GestureOptions {
334    pub axes: GestureAxes,
335    pub gestures: GestureBehavior,
336    pub metrics: GestureMetrics,
337
338    /// Whether a release that catches the recognizer's last glide (a flick
339    /// that interrupts a glide going its way) adds that glide's speed, as
340    /// `UIScrollView`, Android's scroll flywheel and Compose do. Each part's
341    /// decay still caps the speed.
342    pub(crate) carry_caught_glide: bool,
343    /// Whether a press stops every camera animation, so that the map holds
344    /// still under it, or only the recognizer's own.
345    pub(crate) interrupt_animations: bool,
346    /// The [`AnimationOptions::transition_id`](crate::camera::AnimationOptions::transition_id)
347    /// of the eases and momentum the recognizer starts.
348    pub(crate) transition_id: u64,
349}
350
351impl GestureOptions {
352    /// The options of `axis`.
353    #[must_use]
354    pub(crate) fn axis(&self, axis: Axis) -> &AxisOptions {
355        match axis {
356            Axis::Zoom => &self.axes.zoom,
357            Axis::Bearing => &self.axes.bearing,
358            Axis::Pitch => &self.axes.pitch,
359        }
360    }
361
362    /// Checks every axis's momentum, snap and notches, every gesture rate, and
363    /// every platform metric.
364    pub fn validate(&self) -> Result<(), InvalidGestureOptions> {
365        let momentum = |name, momentum: Option<MomentumDecay>| {
366            momentum
367                .map_or(Ok(()), |decay| decay.validate().map_err(|error| InvalidGestureOptions::Momentum(name, error)))
368        };
369        momentum("pan", self.axes.pan.momentum)?;
370        for (name, part) in [("zoom", &self.axes.zoom), ("bearing", &self.axes.bearing), ("pitch", &self.axes.pitch)] {
371            momentum(name, part.momentum)?;
372            if let Some(snap) = part.snap {
373                snap.validate().map_err(|error| InvalidGestureOptions::Snap(name, error))?;
374            }
375            let valid = |notch: &Notch| notch.spacing.is_finite() && notch.spacing > 0.0 && notch.offset.is_finite();
376            if !part.notches.iter().all(valid) {
377                return Err(InvalidGestureOptions::Notch(name));
378            }
379        }
380        let rates = [
381            self.gestures.drag.rotate_bearing_per_px,
382            self.gestures.drag.rotate_pitch_per_px,
383            self.gestures.pinch.pitch_per_px,
384            self.gestures.tap_drag.zoom_per_px,
385            self.gestures.double_tap.zoom_levels,
386            self.gestures.two_finger_tap.zoom_levels,
387        ];
388        if !rates.iter().all(|value| value.is_finite()) {
389            return Err(InvalidGestureOptions::Rate);
390        }
391        if !self.gestures.deltas.max_step_zoom.is_finite() || self.gestures.deltas.max_step_zoom < 1e-6 {
392            return Err(InvalidGestureOptions::MaxStepZoom);
393        }
394        for (name, value) in [
395            ("touch_slop", self.metrics.touch_slop),
396            ("pointer_slop", self.metrics.pointer_slop),
397            ("double_tap_slop", self.metrics.double_tap_slop),
398            ("pinch_zoom_threshold", self.metrics.pinch_zoom_threshold),
399            ("pinch_rotate_threshold", self.metrics.pinch_rotate_threshold),
400            ("pinch_pitch_slop", self.metrics.pinch_pitch_slop),
401        ] {
402            if !value.is_finite() || value < 0.0 {
403                return Err(InvalidGestureOptions::Metric(name));
404            }
405        }
406        if self.metrics.long_press.is_zero() {
407            return Err(InvalidGestureOptions::LongPress);
408        }
409        Ok(())
410    }
411}
412
413impl Default for GestureOptions {
414    fn default() -> Self {
415        GestureOptions {
416            axes: GestureAxes::default(),
417            gestures: GestureBehavior::default(),
418            metrics: GestureMetrics::default(),
419            carry_caught_glide: true,
420            interrupt_animations: true,
421            // "gestures" in ASCII.
422            transition_id: 0x6765_7374_7572_6573,
423        }
424    }
425}