Skip to main content

waft_gestures/
scale.rs

1//! Flutter counterpart: `gestures/scale.dart`.
2//!
3//! Leaf object. Superclass bags and `super` namespaces are in `recognizer.rs`.
4
5use std::collections::{HashMap, HashSet};
6use std::fmt::{self, Debug};
7use std::rc::Rc;
8use std::time::Duration;
9
10use indexmap::IndexMap;
11use waft_embedder::{Matrix4, Offset, PointerDeviceKind};
12use waft_foundation::{App, Handle, OptionRetained, ValueChanged};
13
14use crate::arena::GestureDisposition;
15use crate::constants::{K_MAX_FLING_VELOCITY, K_MIN_FLING_VELOCITY};
16use crate::events::{
17    PointerDownEvent, PointerEvent, PointerPanZoomStartEvent, PointerPanZoomUpdateEvent,
18    compute_pan_slop, compute_scale_slop, transform_position,
19};
20use crate::gesture_settings::DeviceGestureSettings;
21use crate::recognizer::{
22    DragStartBehavior, GestureRecognizer, GestureRecognizerData, OneSequenceData,
23    OneSequenceGestureRecognizer, OneSequenceLeafData, RecognizerLeaf, RecognizerLeafData,
24};
25use crate::team::GestureArenaTeam;
26use crate::velocity::Velocity;
27use crate::velocity_tracker::VelocityTracker;
28use waft_foundation::Ref;
29
30/// The default conversion factor when treating mouse scrolling as scaling.
31///
32/// The value was arbitrarily chosen to feel natural for most mousewheels on
33/// all supported platforms.
34pub const K_DEFAULT_MOUSE_SCROLL_TO_SCALE_FACTOR: f64 = 200.0;
35
36/// The default conversion factor when treating trackpad scrolling as scaling.
37///
38/// This factor matches the default [`K_DEFAULT_MOUSE_SCROLL_TO_SCALE_FACTOR`] of 200 to
39/// feel natural for most trackpads, and the convention that scrolling up means
40/// zooming in.
41pub const K_DEFAULT_TRACKPAD_SCROLL_TO_SCALE_FACTOR: Offset =
42    Offset::new(0.0, -1.0 / K_DEFAULT_MOUSE_SCROLL_TO_SCALE_FACTOR);
43
44/// The possible states of a [`ScaleGestureRecognizer`].
45#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
46enum ScaleState {
47    /// The recognizer is ready to start recognizing a gesture.
48    Ready,
49
50    /// The sequence of pointer events seen thus far is consistent with a scale
51    /// gesture but the gesture has not been accepted definitively.
52    Possible,
53
54    /// The sequence of pointer events seen thus far has been accepted
55    /// definitively as a scale gesture.
56    Accepted,
57
58    /// The sequence of pointer events seen thus far has been accepted
59    /// definitively as a scale gesture and the pointers established a focal point
60    /// and initial scale.
61    Started,
62}
63
64/// Dart's `_PointerPanZoomData`. Its getters read the recognizer that owns it, which Dart
65/// holds as `parent`.
66#[derive(Clone, Copy, Debug)]
67struct PointerPanZoomData {
68    position: Offset,
69    pan: Offset,
70    scale: f64,
71    rotation: f64,
72}
73
74impl PointerPanZoomData {
75    fn from_start_event(event: &PointerPanZoomStartEvent) -> PointerPanZoomData {
76        PointerPanZoomData {
77            position: event.position,
78            pan: Offset::ZERO,
79            scale: 1.0,
80            rotation: 0.0,
81        }
82    }
83
84    fn from_update_event(event: &PointerPanZoomUpdateEvent) -> PointerPanZoomData {
85        PointerPanZoomData {
86            position: event.position,
87            pan: event.pan,
88            scale: event.scale,
89            rotation: event.rotation,
90        }
91    }
92
93    fn focal_point(&self, parent: &ScaleGestureRecognizer) -> Offset {
94        if parent.trackpad_scroll_causes_scale {
95            return self.position;
96        }
97        self.position + self.pan
98    }
99
100    fn scale(&self, parent: &ScaleGestureRecognizer) -> f64 {
101        if parent.trackpad_scroll_causes_scale {
102            return self.scale
103                * ((self.pan.dx() * parent.trackpad_scroll_to_scale_factor.dx())
104                    + (self.pan.dy() * parent.trackpad_scroll_to_scale_factor.dy()))
105                .exp();
106        }
107        self.scale
108    }
109
110    fn rotation(&self) -> f64 {
111        self.rotation
112    }
113}
114
115/// Details for [`GestureScaleStartCallback`].
116#[derive(Clone)]
117pub struct ScaleStartDetails {
118    /// The initial focal point of the pointers in contact with the screen.
119    ///
120    /// Reported in global coordinates.
121    ///
122    /// See also:
123    ///
124    ///  * [`local_focal_point`](Self::local_focal_point), which is the same value reported in local
125    ///    coordinates.
126    pub focal_point: Offset,
127
128    /// The initial focal point of the pointers in contact with the screen.
129    ///
130    /// Reported in local coordinates. Defaults to [`focal_point`](Self::focal_point) if not set in the
131    /// constructor.
132    ///
133    /// See also:
134    ///
135    ///  * [`focal_point`](Self::focal_point), which is the same value reported in global
136    ///    coordinates.
137    pub local_focal_point: Offset,
138
139    /// The number of pointers being tracked by the gesture recognizer.
140    ///
141    /// Typically this is the number of fingers being used to pan the widget using the gesture
142    /// recognizer.
143    pub pointer_count: usize,
144
145    /// Recorded timestamp of the source pointer event that triggered the scale
146    /// event.
147    ///
148    /// Could be `None` if triggered from proxied events such as accessibility.
149    pub source_time_stamp: Option<Duration>,
150
151    /// The kind of the device that initiated the event.
152    ///
153    /// If multiple pointers are touching the screen, the kind of the pointer
154    /// device that first initiated the event is used.
155    pub kind: Option<PointerDeviceKind>,
156}
157
158impl ScaleStartDetails {
159    /// Creates details for [`GestureScaleStartCallback`].
160    pub fn new(
161        focal_point: Offset,
162        local_focal_point: Option<Offset>,
163        pointer_count: usize,
164        source_time_stamp: Option<Duration>,
165        kind: Option<PointerDeviceKind>,
166    ) -> ScaleStartDetails {
167        ScaleStartDetails {
168            focal_point,
169            local_focal_point: local_focal_point.unwrap_or(focal_point),
170            pointer_count,
171            source_time_stamp,
172            kind,
173        }
174    }
175}
176
177impl Default for ScaleStartDetails {
178    fn default() -> ScaleStartDetails {
179        ScaleStartDetails::new(Offset::ZERO, None, 0, None, None)
180    }
181}
182
183impl Debug for ScaleStartDetails {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.debug_struct("ScaleStartDetails")
186            .field("focalPoint", &self.focal_point)
187            .field("localFocalPoint", &self.local_focal_point)
188            .field("pointerCount", &self.pointer_count)
189            .field("sourceTimeStamp", &self.source_time_stamp)
190            .finish()
191    }
192}
193
194/// Details for [`GestureScaleUpdateCallback`].
195#[derive(Clone)]
196pub struct ScaleUpdateDetails {
197    /// The amount the gesture's focal point has moved in the coordinate space of
198    /// the event receiver since the previous update.
199    ///
200    /// Defaults to zero if not specified in the constructor.
201    pub focal_point_delta: Offset,
202
203    /// The focal point of the pointers in contact with the screen.
204    ///
205    /// Reported in global coordinates.
206    ///
207    /// See also:
208    ///
209    ///  * [`local_focal_point`](Self::local_focal_point), which is the same value reported in local
210    ///    coordinates.
211    pub focal_point: Offset,
212
213    /// The focal point of the pointers in contact with the screen.
214    ///
215    /// Reported in local coordinates. Defaults to [`focal_point`](Self::focal_point) if not set in the
216    /// constructor.
217    ///
218    /// See also:
219    ///
220    ///  * [`focal_point`](Self::focal_point), which is the same value reported in global
221    ///    coordinates.
222    pub local_focal_point: Offset,
223
224    /// The scale implied by the average distance between the pointers in contact
225    /// with the screen.
226    ///
227    /// This value must be greater than or equal to zero.
228    ///
229    /// See also:
230    ///
231    ///  * [`horizontal_scale`](Self::horizontal_scale), which is the scale along the horizontal axis.
232    ///  * [`vertical_scale`](Self::vertical_scale), which is the scale along the vertical axis.
233    pub scale: f64,
234
235    /// The scale implied by the average distance along the horizontal axis
236    /// between the pointers in contact with the screen.
237    ///
238    /// This value must be greater than or equal to zero.
239    ///
240    /// See also:
241    ///
242    ///  * [`scale`](Self::scale), which is the general scale implied by the pointers.
243    ///  * [`vertical_scale`](Self::vertical_scale), which is the scale along the vertical axis.
244    pub horizontal_scale: f64,
245
246    /// The scale implied by the average distance along the vertical axis
247    /// between the pointers in contact with the screen.
248    ///
249    /// This value must be greater than or equal to zero.
250    ///
251    /// See also:
252    ///
253    ///  * [`scale`](Self::scale), which is the general scale implied by the pointers.
254    ///  * [`horizontal_scale`](Self::horizontal_scale), which is the scale along the horizontal axis.
255    pub vertical_scale: f64,
256
257    /// The angle implied by the first two pointers to enter in contact with
258    /// the screen.
259    ///
260    /// Expressed in radians.
261    pub rotation: f64,
262
263    /// The number of pointers being tracked by the gesture recognizer.
264    ///
265    /// Typically this is the number of fingers being used to pan the widget using the gesture
266    /// recognizer. Due to platform limitations, trackpad gestures count as two fingers
267    /// even if more than two fingers are used.
268    pub pointer_count: usize,
269
270    /// Recorded timestamp of the source pointer event that triggered the scale
271    /// event.
272    ///
273    /// Could be `None` if triggered from proxied events such as accessibility.
274    pub source_time_stamp: Option<Duration>,
275}
276
277impl ScaleUpdateDetails {
278    /// Creates details for [`GestureScaleUpdateCallback`].
279    ///
280    /// The `scale`, `horizontal_scale`, and `vertical_scale` arguments must be
281    /// greater than or equal to zero.
282    #[allow(clippy::too_many_arguments)]
283    pub fn new(
284        focal_point: Offset,
285        local_focal_point: Option<Offset>,
286        scale: f64,
287        horizontal_scale: f64,
288        vertical_scale: f64,
289        rotation: f64,
290        pointer_count: usize,
291        focal_point_delta: Offset,
292        source_time_stamp: Option<Duration>,
293    ) -> ScaleUpdateDetails {
294        debug_assert!(scale >= 0.0);
295        debug_assert!(horizontal_scale >= 0.0);
296        debug_assert!(vertical_scale >= 0.0);
297        ScaleUpdateDetails {
298            focal_point_delta,
299            focal_point,
300            local_focal_point: local_focal_point.unwrap_or(focal_point),
301            scale,
302            horizontal_scale,
303            vertical_scale,
304            rotation,
305            pointer_count,
306            source_time_stamp,
307        }
308    }
309}
310
311impl Default for ScaleUpdateDetails {
312    fn default() -> ScaleUpdateDetails {
313        ScaleUpdateDetails::new(
314            Offset::ZERO,
315            None,
316            1.0,
317            1.0,
318            1.0,
319            0.0,
320            0,
321            Offset::ZERO,
322            None,
323        )
324    }
325}
326
327impl Debug for ScaleUpdateDetails {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        f.debug_struct("ScaleUpdateDetails")
330            .field("focalPointDelta", &self.focal_point_delta)
331            .field("focalPoint", &self.focal_point)
332            .field("localFocalPoint", &self.local_focal_point)
333            .field("scale", &self.scale)
334            .field("horizontalScale", &self.horizontal_scale)
335            .field("verticalScale", &self.vertical_scale)
336            .field("rotation", &self.rotation)
337            .field("pointerCount", &self.pointer_count)
338            .field("sourceTimeStamp", &self.source_time_stamp)
339            .finish()
340    }
341}
342
343/// Details for [`GestureScaleEndCallback`].
344#[derive(Clone)]
345pub struct ScaleEndDetails {
346    /// The velocity of the last pointer to be lifted off of the screen.
347    pub velocity: Velocity,
348
349    /// The final velocity of the scale factor reported by the gesture.
350    pub scale_velocity: f64,
351
352    /// The number of pointers being tracked by the gesture recognizer.
353    ///
354    /// Typically this is the number of fingers being used to pan the widget using the gesture
355    /// recognizer.
356    pub pointer_count: usize,
357}
358
359impl ScaleEndDetails {
360    /// Creates details for [`GestureScaleEndCallback`].
361    pub fn new(velocity: Velocity, scale_velocity: f64, pointer_count: usize) -> ScaleEndDetails {
362        ScaleEndDetails {
363            velocity,
364            scale_velocity,
365            pointer_count,
366        }
367    }
368}
369
370impl Default for ScaleEndDetails {
371    fn default() -> ScaleEndDetails {
372        ScaleEndDetails::new(Velocity::ZERO, 0.0, 0)
373    }
374}
375
376impl Debug for ScaleEndDetails {
377    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378        f.debug_struct("ScaleEndDetails")
379            .field("velocity", &self.velocity)
380            .field("scaleVelocity", &self.scale_velocity)
381            .field("pointerCount", &self.pointer_count)
382            .finish()
383    }
384}
385
386/// Signature for when the pointers in contact with the screen have established
387/// a focal point and initial scale of 1.0.
388pub type GestureScaleStartCallback = ValueChanged<ScaleStartDetails>;
389
390/// Signature for when the pointers in contact with the screen have indicated a
391/// new focal point and/or scale.
392pub type GestureScaleUpdateCallback = ValueChanged<ScaleUpdateDetails>;
393
394/// Signature for when the pointers are no longer in contact with the screen.
395pub type GestureScaleEndCallback = ValueChanged<ScaleEndDetails>;
396
397fn is_fling_gesture(velocity: Velocity) -> bool {
398    let speed_squared = velocity.pixels_per_second.distance_squared();
399    speed_squared > K_MIN_FLING_VELOCITY * K_MIN_FLING_VELOCITY
400}
401
402/// Defines a line between two pointers on screen.
403///
404/// [`LineBetweenPointers`] is an abstraction of a line between two pointers in
405/// contact with the screen. Used to track the rotation of a scale gesture.
406#[derive(Clone, Copy, Debug)]
407struct LineBetweenPointers {
408    // The location and the id of the pointer that marks the start of the line.
409    pointer_start_location: Offset,
410    pointer_start_id: i64,
411
412    // The location and the id of the pointer that marks the end of the line.
413    pointer_end_location: Offset,
414    pointer_end_id: i64,
415}
416
417impl LineBetweenPointers {
418    /// Creates a [`LineBetweenPointers`]. `pointer_start_id` and `pointer_end_id`
419    /// should be different.
420    fn new(
421        pointer_start_location: Offset,
422        pointer_start_id: i64,
423        pointer_end_location: Offset,
424        pointer_end_id: i64,
425    ) -> LineBetweenPointers {
426        debug_assert!(pointer_start_id != pointer_end_id);
427        LineBetweenPointers {
428            pointer_start_location,
429            pointer_start_id,
430            pointer_end_location,
431            pointer_end_id,
432        }
433    }
434}
435
436/// Recognizes a scale gesture.
437///
438/// [`ScaleGestureRecognizer`] tracks the pointers in contact with the screen and
439/// calculates their focal point, indicated scale, and rotation. When a focal
440/// point is established, the recognizer calls [`set_on_start`](Self::set_on_start). As the focal point,
441/// scale, and rotation change, the recognizer calls [`set_on_update`](Self::set_on_update). When the
442/// pointers are no longer in contact with the screen, the recognizer calls
443/// [`set_on_end`](Self::set_on_end).
444pub struct ScaleGestureRecognizer {
445    recognizer: GestureRecognizerData,
446    one_sequence: OneSequenceData,
447    drag_start_behavior: DragStartBehavior,
448    on_start: Option<GestureScaleStartCallback>,
449    on_update: Option<GestureScaleUpdateCallback>,
450    on_end: Option<GestureScaleEndCallback>,
451    state: ScaleState,
452    last_transform: Option<Matrix4>,
453    trackpad_scroll_causes_scale: bool,
454    trackpad_scroll_to_scale_factor: Offset,
455    initial_focal_point: Offset,
456    current_focal_point: Option<Offset>,
457    initial_span: f64,
458    current_span: f64,
459    initial_horizontal_span: f64,
460    current_horizontal_span: f64,
461    initial_vertical_span: f64,
462    current_vertical_span: f64,
463    local_focal_point: Offset,
464    initial_line: Option<LineBetweenPointers>,
465    current_line: Option<LineBetweenPointers>,
466    pointer_locations: IndexMap<i64, Offset>,
467    /// A queue to sort pointers in order of entrance.
468    pointer_queue: Vec<i64>,
469    velocity_trackers: HashMap<i64, VelocityTracker>,
470    scale_velocity_tracker: Option<VelocityTracker>,
471    delta: Offset,
472    pointer_pan_zooms: IndexMap<i64, PointerPanZoomData>,
473    initial_pan_zoom_scale_factor: f64,
474    initial_pan_zoom_rotation_factor: f64,
475    initial_event_timestamp: Option<Duration>,
476}
477
478impl ScaleGestureRecognizer {
479    /// Create a gesture recognizer for interactions intended for scaling content.
480    ///
481    /// Dart's defaults: `dragStartBehavior` [`DragStartBehavior::Down`],
482    /// `trackpadScrollCausesScale` false, `trackpadScrollToScaleFactor`
483    /// [`K_DEFAULT_TRACKPAD_SCROLL_TO_SCALE_FACTOR`].
484    pub fn new(app: &mut App) -> Ref<ScaleGestureRecognizer> {
485        app.create(ScaleGestureRecognizer {
486            recognizer: GestureRecognizerData::new(),
487            one_sequence: OneSequenceData::new(),
488            drag_start_behavior: DragStartBehavior::Down,
489            on_start: None,
490            on_update: None,
491            on_end: None,
492            state: ScaleState::Ready,
493            last_transform: None,
494            trackpad_scroll_causes_scale: false,
495            trackpad_scroll_to_scale_factor: K_DEFAULT_TRACKPAD_SCROLL_TO_SCALE_FACTOR,
496            initial_focal_point: Offset::ZERO,
497            current_focal_point: None,
498            initial_span: 0.0,
499            current_span: 0.0,
500            initial_horizontal_span: 0.0,
501            current_horizontal_span: 0.0,
502            initial_vertical_span: 0.0,
503            current_vertical_span: 0.0,
504            local_focal_point: Offset::ZERO,
505            initial_line: None,
506            current_line: None,
507            pointer_locations: IndexMap::new(),
508            pointer_queue: Vec::new(),
509            velocity_trackers: HashMap::new(),
510            scale_velocity_tracker: None,
511            delta: Offset::ZERO,
512            pointer_pan_zooms: IndexMap::new(),
513            initial_pan_zoom_scale_factor: 1.0,
514            initial_pan_zoom_rotation_factor: 0.0,
515            initial_event_timestamp: None,
516        })
517    }
518
519    /// The kind of devices that are allowed to be recognized.
520    ///
521    /// If none, events from all device kinds will be tracked and recognized.
522    pub fn supported_devices(
523        self: Ref<Self>,
524        app: &mut App,
525        devices: impl IntoIterator<Item = PointerDeviceKind>,
526    ) -> Ref<ScaleGestureRecognizer> {
527        app.get_mut(&self).recognizer.supported_devices = Some(devices.into_iter().collect());
528        self
529    }
530
531    /// Sets the kind of devices that are allowed to be recognized; `None` tracks
532    /// and recognizes events from all device kinds.
533    pub fn set_supported_devices(
534        self: Handle<Self>,
535        app: &mut App,
536        devices: Option<HashSet<PointerDeviceKind>>,
537    ) {
538        app.get_mut(self).recognizer.supported_devices = devices;
539    }
540
541    /// Called when interaction starts. Limits buttons this recognizer accepts.
542    pub fn allowed_buttons_filter(
543        self: Handle<Self>,
544        app: &mut App,
545        filter: impl Fn(i64) -> bool + 'static,
546    ) -> Handle<ScaleGestureRecognizer> {
547        app.get_mut(self).recognizer.allowed_buttons_filter = Rc::new(filter);
548        self
549    }
550
551    /// Optional device specific configuration that takes precedence over
552    /// framework defaults.
553    pub fn gesture_settings(self: Handle<Self>, app: &App) -> Option<DeviceGestureSettings> {
554        app.get(self).recognizer.gesture_settings
555    }
556
557    /// Sets [`gesture_settings`](Self::gesture_settings).
558    pub fn set_gesture_settings(
559        self: Handle<Self>,
560        app: &mut App,
561        settings: Option<DeviceGestureSettings>,
562    ) {
563        app.get_mut(self).recognizer.gesture_settings = settings;
564    }
565
566    /// The team that this recognizer belongs to, if any.
567    pub fn team(self: Handle<Self>, app: &App) -> Option<Handle<GestureArenaTeam>> {
568        app.get(self).one_sequence.team.handle()
569    }
570
571    /// The [`team`](Self::team) can only be set once.
572    pub fn set_team(self: Handle<Self>, app: &mut App, value: Ref<GestureArenaTeam>) {
573        debug_assert!(app.get(self).one_sequence.entries.is_empty());
574        debug_assert!(app.get(self).one_sequence.tracked_pointers.is_empty());
575        debug_assert!(app.get(self).one_sequence.team.is_none());
576        app.get_mut(self).one_sequence.team = Some(value);
577    }
578
579    /// Registers a new pointer that might be relevant to this gesture detector.
580    pub fn add_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
581        GestureRecognizer::add_pointer(self, app, event);
582    }
583
584    /// Registers a new pointer pan/zoom that might be relevant to this gesture
585    /// detector.
586    pub fn add_pointer_pan_zoom(
587        self: Handle<Self>,
588        app: &mut App,
589        event: PointerPanZoomStartEvent,
590    ) {
591        GestureRecognizer::add_pointer_pan_zoom(self, app, event);
592    }
593
594    /// Releases any resources used by the object.
595    pub fn dispose(self: Handle<Self>, app: &mut App) {
596        <Self as RecognizerLeaf>::dispose(self, app);
597    }
598
599    /// Determines what point is used as the starting point in all calculations
600    /// involving this gesture.
601    ///
602    /// When set to [`DragStartBehavior::Down`], the scale is calculated starting
603    /// from the position where the pointer first contacted the screen.
604    ///
605    /// When set to [`DragStartBehavior::Start`], the scale is calculated starting
606    /// from the position where the scale gesture began. The scale gesture may
607    /// begin after the time that the pointer first contacted the screen if there
608    /// are multiple listeners competing for the gesture. In that case, the
609    /// gesture arena waits to determine whether or not the gesture is a scale
610    /// gesture before giving the gesture to this GestureRecognizer. This happens
611    /// in the case of nested GestureDetectors, for example.
612    ///
613    /// Defaults to [`DragStartBehavior::Down`].
614    pub fn drag_start_behavior(self: Handle<Self>, app: &App) -> DragStartBehavior {
615        app.get(self).drag_start_behavior
616    }
617
618    /// Sets [`drag_start_behavior`](Self::drag_start_behavior).
619    pub fn set_drag_start_behavior(self: Handle<Self>, app: &mut App, value: DragStartBehavior) {
620        app.get_mut(self).drag_start_behavior = value;
621    }
622
623    /// The pointers in contact with the screen have established a focal point and
624    /// initial scale of 1.0.
625    ///
626    /// This won't be called until the gesture arena has determined that this
627    /// GestureRecognizer has won the gesture.
628    pub fn set_on_start(
629        self: Handle<Self>,
630        app: &mut App,
631        callback: Option<GestureScaleStartCallback>,
632    ) {
633        app.get_mut(self).on_start = callback;
634    }
635
636    /// The pointers in contact with the screen have indicated a new focal point
637    /// and/or scale.
638    pub fn set_on_update(
639        self: Handle<Self>,
640        app: &mut App,
641        callback: Option<GestureScaleUpdateCallback>,
642    ) {
643        app.get_mut(self).on_update = callback;
644    }
645
646    /// The pointers are no longer in contact with the screen.
647    pub fn set_on_end(
648        self: Handle<Self>,
649        app: &mut App,
650        callback: Option<GestureScaleEndCallback>,
651    ) {
652        app.get_mut(self).on_end = callback;
653    }
654
655    /// Whether scrolling up/down on a trackpad should cause scaling instead of
656    /// panning.
657    ///
658    /// Defaults to false.
659    pub fn trackpad_scroll_causes_scale(self: Handle<Self>, app: &App) -> bool {
660        app.get(self).trackpad_scroll_causes_scale
661    }
662
663    /// Sets [`trackpad_scroll_causes_scale`](Self::trackpad_scroll_causes_scale).
664    pub fn set_trackpad_scroll_causes_scale(self: Handle<Self>, app: &mut App, value: bool) {
665        app.get_mut(self).trackpad_scroll_causes_scale = value;
666    }
667
668    /// A factor to control the direction and magnitude of scale when converting
669    /// trackpad scrolling.
670    ///
671    /// Incoming trackpad pan offsets will be divided by this factor to get scale
672    /// values. Increasing this offset will reduce the amount of scaling caused by
673    /// a fixed amount of trackpad scrolling.
674    ///
675    /// Defaults to [`K_DEFAULT_TRACKPAD_SCROLL_TO_SCALE_FACTOR`].
676    pub fn trackpad_scroll_to_scale_factor(self: Handle<Self>, app: &App) -> Offset {
677        app.get(self).trackpad_scroll_to_scale_factor
678    }
679
680    /// Sets [`trackpad_scroll_to_scale_factor`](Self::trackpad_scroll_to_scale_factor).
681    pub fn set_trackpad_scroll_to_scale_factor(self: Handle<Self>, app: &mut App, value: Offset) {
682        app.get_mut(self).trackpad_scroll_to_scale_factor = value;
683    }
684
685    /// The number of pointers being tracked by the gesture recognizer.
686    ///
687    /// Typically this is the number of fingers being used to pan the widget using the gesture
688    /// recognizer.
689    pub fn pointer_count(self: Handle<Self>, app: &App) -> usize {
690        let this = app.get(self);
691        // PointerPanZoom protocol doesn't contain the exact number of pointers
692        // used on the trackpad, as it isn't exposed by all platforms. However, it
693        // will always be at least two.
694        (2 * this.pointer_pan_zooms.len()) + this.pointer_queue.len()
695    }
696}
697
698impl ScaleGestureRecognizer {
699    fn pointer_scale_factor(&self) -> f64 {
700        if self.initial_span > 0.0 {
701            self.current_span / self.initial_span
702        } else {
703            1.0
704        }
705    }
706
707    fn pointer_horizontal_scale_factor(&self) -> f64 {
708        if self.initial_horizontal_span > 0.0 {
709            self.current_horizontal_span / self.initial_horizontal_span
710        } else {
711            1.0
712        }
713    }
714
715    fn pointer_vertical_scale_factor(&self) -> f64 {
716        if self.initial_vertical_span > 0.0 {
717            self.current_vertical_span / self.initial_vertical_span
718        } else {
719            1.0
720        }
721    }
722
723    fn scale_factor(&self) -> f64 {
724        let mut scale = self.pointer_scale_factor();
725        for p in self.pointer_pan_zooms.values() {
726            scale *= p.scale(self) / self.initial_pan_zoom_scale_factor;
727        }
728        scale
729    }
730
731    fn horizontal_scale_factor(&self) -> f64 {
732        let mut scale = self.pointer_horizontal_scale_factor();
733        for p in self.pointer_pan_zooms.values() {
734            scale *= p.scale(self) / self.initial_pan_zoom_scale_factor;
735        }
736        scale
737    }
738
739    fn vertical_scale_factor(&self) -> f64 {
740        let mut scale = self.pointer_vertical_scale_factor();
741        for p in self.pointer_pan_zooms.values() {
742            scale *= p.scale(self) / self.initial_pan_zoom_scale_factor;
743        }
744        scale
745    }
746
747    fn compute_rotation_factor(&self) -> f64 {
748        let mut factor = 0.0;
749        if let (Some(initial_line), Some(current_line)) = (self.initial_line, self.current_line) {
750            let fx = initial_line.pointer_start_location.dx();
751            let fy = initial_line.pointer_start_location.dy();
752            let sx = initial_line.pointer_end_location.dx();
753            let sy = initial_line.pointer_end_location.dy();
754
755            let nfx = current_line.pointer_start_location.dx();
756            let nfy = current_line.pointer_start_location.dy();
757            let nsx = current_line.pointer_end_location.dx();
758            let nsy = current_line.pointer_end_location.dy();
759
760            let angle1 = (fy - sy).atan2(fx - sx);
761            let angle2 = (nfy - nsy).atan2(nfx - nsx);
762
763            factor = angle2 - angle1;
764        }
765        for p in self.pointer_pan_zooms.values() {
766            factor += p.rotation();
767        }
768        factor -= self.initial_pan_zoom_rotation_factor;
769        factor
770    }
771
772    fn update(&mut self) {
773        let previous_focal_point = self.current_focal_point;
774
775        // Compute the focal point
776        let mut focal_point = Offset::ZERO;
777        for location in self.pointer_locations.values() {
778            focal_point = focal_point + *location;
779        }
780        for p in self.pointer_pan_zooms.values() {
781            focal_point = focal_point + p.focal_point(self);
782        }
783        let current_focal_point = focal_point
784            / (self.pointer_locations.len() + self.pointer_pan_zooms.len()).max(1) as f64;
785        self.current_focal_point = Some(current_focal_point);
786
787        if previous_focal_point.is_none() {
788            self.local_focal_point = transform_position(self.last_transform, current_focal_point);
789            self.delta = Offset::ZERO;
790        } else {
791            let local_previous_focal_point = self.local_focal_point;
792            self.local_focal_point = transform_position(self.last_transform, current_focal_point);
793            self.delta = self.local_focal_point - local_previous_focal_point;
794        }
795
796        let count = self.pointer_locations.len();
797
798        let mut pointer_focal_point = Offset::ZERO;
799        for location in self.pointer_locations.values() {
800            pointer_focal_point = pointer_focal_point + *location;
801        }
802        if count > 0 {
803            pointer_focal_point = pointer_focal_point / count as f64;
804        }
805
806        // Span is the average deviation from focal point. Horizontal and vertical
807        // spans are the average deviations from the focal point's horizontal and
808        // vertical coordinates, respectively.
809        let mut total_deviation = 0.0;
810        let mut total_horizontal_deviation = 0.0;
811        let mut total_vertical_deviation = 0.0;
812        for location in self.pointer_locations.values() {
813            total_deviation += (pointer_focal_point - *location).distance();
814            total_horizontal_deviation += (pointer_focal_point.dx() - location.dx()).abs();
815            total_vertical_deviation += (pointer_focal_point.dy() - location.dy()).abs();
816        }
817        self.current_span = if count > 0 {
818            total_deviation / count as f64
819        } else {
820            0.0
821        };
822        self.current_horizontal_span = if count > 0 {
823            total_horizontal_deviation / count as f64
824        } else {
825            0.0
826        };
827        self.current_vertical_span = if count > 0 {
828            total_vertical_deviation / count as f64
829        } else {
830            0.0
831        };
832    }
833
834    /// Updates [`initial_line`](Self::initial_line) and
835    /// [`current_line`](Self::current_line) accordingly to the situation of the
836    /// registered pointers.
837    fn update_lines(&mut self) {
838        let count = self.pointer_locations.len();
839        debug_assert!(self.pointer_queue.len() >= count);
840
841        // In case of just one pointer registered, reconfigure `initial_line`.
842        if count < 2 {
843            self.initial_line = self.current_line;
844        } else if let Some(initial_line) = self.initial_line
845            && initial_line.pointer_start_id == self.pointer_queue[0]
846            && initial_line.pointer_end_id == self.pointer_queue[1]
847        {
848            // Rotation updated, set the `current_line`.
849            self.current_line = Some(LineBetweenPointers::new(
850                self.pointer_locations[&self.pointer_queue[0]],
851                self.pointer_queue[0],
852                self.pointer_locations[&self.pointer_queue[1]],
853                self.pointer_queue[1],
854            ));
855        } else {
856            // A new rotation process is on the way, set the `initial_line`.
857            self.initial_line = Some(LineBetweenPointers::new(
858                self.pointer_locations[&self.pointer_queue[0]],
859                self.pointer_queue[0],
860                self.pointer_locations[&self.pointer_queue[1]],
861                self.pointer_queue[1],
862            ));
863            self.current_line = self.initial_line;
864        }
865    }
866}
867
868/// The private members of Dart's `ScaleGestureRecognizer` that call back into the app.
869impl ScaleGestureRecognizer {
870    fn reconfigure(self: Handle<Self>, app: &mut App, pointer: i64) -> bool {
871        let this = app.get_mut(self);
872        this.initial_focal_point = this
873            .current_focal_point
874            .expect("update ran before the pointers are reconfigured");
875        this.initial_span = this.current_span;
876        this.initial_line = this.current_line;
877        this.initial_horizontal_span = this.current_horizontal_span;
878        this.initial_vertical_span = this.current_vertical_span;
879        if this.pointer_pan_zooms.is_empty() {
880            this.initial_pan_zoom_scale_factor = 1.0;
881            this.initial_pan_zoom_rotation_factor = 0.0;
882        } else {
883            this.initial_pan_zoom_scale_factor = this.scale_factor() / this.pointer_scale_factor();
884            this.initial_pan_zoom_rotation_factor = this
885                .pointer_pan_zooms
886                .values()
887                .map(PointerPanZoomData::rotation)
888                .reduce(|a, b| a + b)
889                .expect("not empty");
890        }
891        if this.state == ScaleState::Started {
892            if let Some(on_end) = app.get(self).on_end.clone() {
893                let now = app.clock();
894                let this = app.get(self);
895                let mut velocity = this.velocity_trackers[&pointer].get_velocity(now);
896                let scale_velocity = this
897                    .scale_velocity_tracker
898                    .as_ref()
899                    .map_or(-1.0, |tracker| {
900                        tracker.get_velocity(now).pixels_per_second.dx()
901                    });
902                let pointer_count = self.pointer_count(app);
903                if is_fling_gesture(velocity) {
904                    let pixels_per_second = velocity.pixels_per_second;
905                    if pixels_per_second.distance_squared()
906                        > K_MAX_FLING_VELOCITY * K_MAX_FLING_VELOCITY
907                    {
908                        velocity = Velocity {
909                            pixels_per_second: (pixels_per_second / pixels_per_second.distance())
910                                * K_MAX_FLING_VELOCITY,
911                        };
912                    }
913                    GestureRecognizer::invoke_callback(self, app, "onEnd", |app| {
914                        on_end(
915                            app,
916                            ScaleEndDetails::new(velocity, scale_velocity, pointer_count),
917                        );
918                    });
919                } else {
920                    GestureRecognizer::invoke_callback(self, app, "onEnd", |app| {
921                        on_end(
922                            app,
923                            ScaleEndDetails::new(Velocity::ZERO, scale_velocity, pointer_count),
924                        );
925                    });
926                }
927            }
928            let this = app.get_mut(self);
929            this.state = ScaleState::Accepted;
930            // arbitrary PointerDeviceKind
931            this.scale_velocity_tracker =
932                Some(VelocityTracker::with_kind(PointerDeviceKind::Touch));
933            return false;
934        }
935        // arbitrary PointerDeviceKind
936        app.get_mut(self).scale_velocity_tracker =
937            Some(VelocityTracker::with_kind(PointerDeviceKind::Touch));
938        true
939    }
940
941    fn advance_state_machine(
942        self: Handle<Self>,
943        app: &mut App,
944        should_start_if_accepted: bool,
945        event: &PointerEvent,
946    ) {
947        if app.get(self).state == ScaleState::Ready {
948            app.get_mut(self).state = ScaleState::Possible;
949        }
950
951        let state = app.get(self).state;
952        if state == ScaleState::Possible {
953            let this = app.get(self);
954            let span_delta = (this.current_span - this.initial_span).abs();
955            let focal_point_delta = (this
956                .current_focal_point
957                .expect("update ran before the state machine")
958                - this.initial_focal_point)
959                .distance();
960            let scale_factor = this.scale_factor();
961            let pointer_scale_factor = this.pointer_scale_factor();
962            if span_delta > compute_scale_slop(event.kind())
963                || focal_point_delta
964                    > compute_pan_slop(event.kind(), this.recognizer.gesture_settings)
965                || (scale_factor / pointer_scale_factor).max(pointer_scale_factor / scale_factor)
966                    > 1.05
967            {
968                self.resolve(app, GestureDisposition::Accepted);
969            }
970        } else if state >= ScaleState::Accepted {
971            self.resolve(app, GestureDisposition::Accepted);
972        }
973
974        if app.get(self).state == ScaleState::Accepted && should_start_if_accepted {
975            let this = app.get_mut(self);
976            this.initial_event_timestamp = Some(event.time_stamp());
977            this.state = ScaleState::Started;
978            self.dispatch_on_start_callback_if_needed(app);
979        }
980
981        if app.get(self).state == ScaleState::Started {
982            let scale_factor = app.get(self).scale_factor();
983            let now = app.clock();
984            if let Some(tracker) = app.get_mut(self).scale_velocity_tracker.as_mut() {
985                tracker.add_position(now, event.time_stamp(), Offset::new(scale_factor, 0.0));
986            }
987            if let Some(on_update) = app.get(self).on_update.clone() {
988                let this = app.get(self);
989                let details = ScaleUpdateDetails::new(
990                    this.current_focal_point
991                        .expect("update ran before the state machine"),
992                    Some(this.local_focal_point),
993                    this.scale_factor(),
994                    this.horizontal_scale_factor(),
995                    this.vertical_scale_factor(),
996                    this.compute_rotation_factor(),
997                    self.pointer_count(app),
998                    this.delta,
999                    Some(event.time_stamp()),
1000                );
1001                GestureRecognizer::invoke_callback(self, app, "onUpdate", |app| {
1002                    on_update(app, details);
1003                });
1004            }
1005        }
1006    }
1007
1008    fn dispatch_on_start_callback_if_needed(self: Handle<Self>, app: &mut App) {
1009        debug_assert!(app.get(self).state == ScaleState::Started);
1010        if let Some(on_start) = app.get(self).on_start.clone() {
1011            let this = app.get(self);
1012            let first_pointer = this
1013                .pointer_queue
1014                .first()
1015                .or_else(|| this.pointer_pan_zooms.keys().next())
1016                .copied();
1017            let kind = first_pointer
1018                .map(|pointer| GestureRecognizer::kind_for_pointer(self, app, pointer));
1019            let this = app.get(self);
1020            let details = ScaleStartDetails::new(
1021                this.current_focal_point
1022                    .expect("update ran before the gesture started"),
1023                Some(this.local_focal_point),
1024                self.pointer_count(app),
1025                this.initial_event_timestamp,
1026                kind,
1027            );
1028            GestureRecognizer::invoke_callback(self, app, "onStart", |app| {
1029                on_start(app, details);
1030            });
1031        }
1032        app.get_mut(self).initial_event_timestamp = None;
1033    }
1034}
1035
1036impl RecognizerLeafData for ScaleGestureRecognizer {
1037    fn recognizer(&self) -> &GestureRecognizerData {
1038        &self.recognizer
1039    }
1040    fn recognizer_mut(&mut self) -> &mut GestureRecognizerData {
1041        &mut self.recognizer
1042    }
1043}
1044
1045impl OneSequenceLeafData for ScaleGestureRecognizer {
1046    fn one_sequence(&self) -> &OneSequenceData {
1047        &self.one_sequence
1048    }
1049    fn one_sequence_mut(&mut self) -> &mut OneSequenceData {
1050        &mut self.one_sequence
1051    }
1052}
1053
1054impl RecognizerLeaf for ScaleGestureRecognizer {
1055    fn add_allowed_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
1056        OneSequenceGestureRecognizer::add_allowed_pointer(self, app, &event);
1057        let this = app.get_mut(self);
1058        this.velocity_trackers
1059            .insert(event.pointer, VelocityTracker::with_kind(event.kind));
1060        this.initial_event_timestamp = Some(event.time_stamp);
1061        if this.state == ScaleState::Ready {
1062            this.state = ScaleState::Possible;
1063            this.initial_span = 0.0;
1064            this.current_span = 0.0;
1065            this.initial_horizontal_span = 0.0;
1066            this.current_horizontal_span = 0.0;
1067            this.initial_vertical_span = 0.0;
1068            this.current_vertical_span = 0.0;
1069        }
1070    }
1071
1072    fn handle_non_allowed_pointer(self: Handle<Self>, app: &mut App, _event: &PointerDownEvent) {
1073        OneSequenceGestureRecognizer::handle_non_allowed_pointer(self, app);
1074    }
1075
1076    fn is_pointer_pan_zoom_allowed(
1077        self: Handle<Self>,
1078        _app: &App,
1079        _event: &PointerPanZoomStartEvent,
1080    ) -> bool {
1081        true
1082    }
1083
1084    fn add_allowed_pointer_pan_zoom(
1085        self: Handle<Self>,
1086        app: &mut App,
1087        event: PointerPanZoomStartEvent,
1088    ) {
1089        self.start_tracking_pointer(app, event.pointer, event.transform);
1090        let this = app.get_mut(self);
1091        this.velocity_trackers
1092            .insert(event.pointer, VelocityTracker::with_kind(event.kind));
1093        this.initial_event_timestamp = Some(event.time_stamp);
1094        if this.state == ScaleState::Ready {
1095            this.state = ScaleState::Possible;
1096            this.initial_pan_zoom_scale_factor = 1.0;
1097            this.initial_pan_zoom_rotation_factor = 0.0;
1098        }
1099    }
1100
1101    fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
1102        debug_assert!(app.get(self).state != ScaleState::Ready);
1103        let mut did_change_configuration = false;
1104        let mut should_start_if_accepted = false;
1105        let now = app.clock();
1106        let this = app.get_mut(self);
1107        match &event {
1108            PointerEvent::Move(move_event) => {
1109                let tracker = this
1110                    .velocity_trackers
1111                    .get_mut(&move_event.pointer)
1112                    .expect("a tracker for every tracked pointer");
1113                if !move_event.synthesized {
1114                    tracker.add_position(now, move_event.time_stamp, move_event.position);
1115                }
1116                this.pointer_locations
1117                    .insert(move_event.pointer, move_event.position);
1118                should_start_if_accepted = true;
1119                this.last_transform = move_event.transform;
1120            }
1121            PointerEvent::Down(down) => {
1122                this.pointer_locations.insert(down.pointer, down.position);
1123                this.pointer_queue.push(down.pointer);
1124                did_change_configuration = true;
1125                should_start_if_accepted = true;
1126                this.last_transform = down.transform;
1127            }
1128            PointerEvent::Up(_) | PointerEvent::Cancel(_) => {
1129                let pointer = event.pointer();
1130                this.pointer_locations.shift_remove(&pointer);
1131                this.pointer_queue.retain(|&queued| queued != pointer);
1132                did_change_configuration = true;
1133                this.last_transform = event.transform();
1134            }
1135            PointerEvent::PanZoomStart(start) => {
1136                debug_assert!(!this.pointer_pan_zooms.contains_key(&start.pointer));
1137                this.pointer_pan_zooms
1138                    .insert(start.pointer, PointerPanZoomData::from_start_event(start));
1139                did_change_configuration = true;
1140                should_start_if_accepted = true;
1141                this.last_transform = start.transform;
1142            }
1143            PointerEvent::PanZoomUpdate(update) => {
1144                debug_assert!(this.pointer_pan_zooms.contains_key(&update.pointer));
1145                if !update.synthesized && !this.trackpad_scroll_causes_scale {
1146                    this.velocity_trackers
1147                        .get_mut(&update.pointer)
1148                        .expect("a tracker for every tracked pan/zoom")
1149                        .add_position(now, update.time_stamp, update.pan);
1150                }
1151                this.pointer_pan_zooms.insert(
1152                    update.pointer,
1153                    PointerPanZoomData::from_update_event(update),
1154                );
1155                this.last_transform = update.transform;
1156                should_start_if_accepted = true;
1157            }
1158            PointerEvent::PanZoomEnd(end) => {
1159                debug_assert!(this.pointer_pan_zooms.contains_key(&end.pointer));
1160                this.pointer_pan_zooms.shift_remove(&end.pointer);
1161                did_change_configuration = true;
1162            }
1163            _ => {}
1164        }
1165
1166        this.update_lines();
1167        this.update();
1168
1169        if !did_change_configuration || self.reconfigure(app, event.pointer()) {
1170            self.advance_state_machine(app, should_start_if_accepted, &event);
1171        }
1172        OneSequenceGestureRecognizer::stop_tracking_if_pointer_no_longer_down(self, app, &event);
1173    }
1174
1175    fn accept_gesture(self: Handle<Self>, app: &mut App, _pointer: i64) {
1176        if app.get(self).state == ScaleState::Possible {
1177            app.get_mut(self).state = ScaleState::Started;
1178            self.dispatch_on_start_callback_if_needed(app);
1179            let this = app.get_mut(self);
1180            if this.drag_start_behavior == DragStartBehavior::Start {
1181                this.initial_focal_point = this
1182                    .current_focal_point
1183                    .expect("update ran before the gesture is accepted");
1184                this.initial_span = this.current_span;
1185                this.initial_line = this.current_line;
1186                this.initial_horizontal_span = this.current_horizontal_span;
1187                this.initial_vertical_span = this.current_vertical_span;
1188                if this.pointer_pan_zooms.is_empty() {
1189                    this.initial_pan_zoom_scale_factor = 1.0;
1190                    this.initial_pan_zoom_rotation_factor = 0.0;
1191                } else {
1192                    this.initial_pan_zoom_scale_factor =
1193                        this.scale_factor() / this.pointer_scale_factor();
1194                    this.initial_pan_zoom_rotation_factor = this
1195                        .pointer_pan_zooms
1196                        .values()
1197                        .map(PointerPanZoomData::rotation)
1198                        .reduce(|a, b| a + b)
1199                        .expect("not empty");
1200                }
1201            }
1202        }
1203    }
1204
1205    fn reject_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
1206        let this = app.get_mut(self);
1207        this.pointer_pan_zooms.shift_remove(&pointer);
1208        this.pointer_locations.shift_remove(&pointer);
1209        this.pointer_queue.retain(|&queued| queued != pointer);
1210        OneSequenceGestureRecognizer::stop_tracking_pointer(self, app, pointer);
1211    }
1212
1213    fn did_stop_tracking_last_pointer(self: Handle<Self>, app: &mut App, _pointer: i64) {
1214        match app.get(self).state {
1215            ScaleState::Possible => self.resolve(app, GestureDisposition::Rejected),
1216            // We should have not seen a pointer yet
1217            ScaleState::Ready => debug_assert!(false),
1218            ScaleState::Accepted => {}
1219            // We should be in the accepted state when user is done
1220            ScaleState::Started => debug_assert!(false),
1221        }
1222        app.get_mut(self).state = ScaleState::Ready;
1223    }
1224
1225    fn dispose(self: Handle<Self>, app: &mut App) {
1226        app.get_mut(self).velocity_trackers.clear();
1227        OneSequenceGestureRecognizer::dispose(self, app);
1228    }
1229
1230    fn debug_description(self: Handle<Self>) -> &'static str {
1231        "scale"
1232    }
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237    use std::cell::{Cell, RefCell};
1238
1239    use waft_foundation::AppCell;
1240
1241    use super::*;
1242    use crate::binding::GestureBinding;
1243    use crate::drag_details::{DragEndDetails, DragStartDetails};
1244    use crate::events::K_PRIMARY_BUTTON;
1245    use crate::events::{
1246        PointerMoveEvent, PointerPanZoomEndEvent, PointerPanZoomUpdateEvent, PointerUpEvent,
1247    };
1248    use crate::monodrag::{DragGestureRecognizer, HorizontalDragGestureRecognizer};
1249    use crate::tap::TapGestureRecognizer;
1250
1251    /// Flutter's `TestPointer`: keeps the last location so a move carries the
1252    /// delta the recognizer reads, and the last pan so a pan/zoom update carries its
1253    /// pan delta.
1254    struct TestPointer {
1255        pointer: i64,
1256        kind: PointerDeviceKind,
1257        location: Offset,
1258        pan: Offset,
1259    }
1260
1261    impl TestPointer {
1262        fn new(pointer: i64) -> TestPointer {
1263            TestPointer::with_kind(pointer, PointerDeviceKind::Touch)
1264        }
1265
1266        fn with_kind(pointer: i64, kind: PointerDeviceKind) -> TestPointer {
1267            TestPointer {
1268                pointer,
1269                kind,
1270                location: Offset::ZERO,
1271                pan: Offset::ZERO,
1272            }
1273        }
1274
1275        fn down(&mut self, position: Offset) -> PointerDownEvent {
1276            self.location = position;
1277            PointerDownEvent {
1278                pointer: self.pointer,
1279                kind: self.kind,
1280                position,
1281                buttons: K_PRIMARY_BUTTON,
1282                ..PointerDownEvent::default()
1283            }
1284        }
1285
1286        fn move_to(&mut self, position: Offset) -> PointerMoveEvent {
1287            let delta = position - self.location;
1288            self.location = position;
1289            PointerMoveEvent {
1290                pointer: self.pointer,
1291                kind: self.kind,
1292                position,
1293                delta,
1294                down: true,
1295                buttons: K_PRIMARY_BUTTON,
1296                ..PointerMoveEvent::default()
1297            }
1298        }
1299
1300        fn up(&mut self) -> PointerUpEvent {
1301            PointerUpEvent {
1302                pointer: self.pointer,
1303                kind: self.kind,
1304                position: self.location,
1305                ..PointerUpEvent::default()
1306            }
1307        }
1308
1309        fn pan_zoom_start(&mut self, position: Offset) -> PointerPanZoomStartEvent {
1310            self.location = position;
1311            self.pan = Offset::ZERO;
1312            PointerPanZoomStartEvent {
1313                pointer: self.pointer,
1314                kind: self.kind,
1315                position,
1316                ..PointerPanZoomStartEvent::default()
1317            }
1318        }
1319
1320        fn pan_zoom_update(
1321            &mut self,
1322            position: Offset,
1323            pan: Offset,
1324            scale: f64,
1325            time_stamp: Duration,
1326        ) -> PointerPanZoomUpdateEvent {
1327            let pan_delta = pan - self.pan;
1328            self.location = position;
1329            self.pan = pan;
1330            PointerPanZoomUpdateEvent {
1331                pointer: self.pointer,
1332                kind: self.kind,
1333                position,
1334                pan,
1335                pan_delta,
1336                scale,
1337                time_stamp,
1338                ..PointerPanZoomUpdateEvent::default()
1339            }
1340        }
1341
1342        fn pan_zoom_end(&mut self, time_stamp: Duration) -> PointerPanZoomEndEvent {
1343            PointerPanZoomEndEvent {
1344                pointer: self.pointer,
1345                kind: self.kind,
1346                position: self.location,
1347                time_stamp,
1348                ..PointerPanZoomEndEvent::default()
1349            }
1350        }
1351    }
1352
1353    fn close_arena(app: &mut App, pointer: i64) {
1354        GestureBinding::instance(app)
1355            .gesture_arena(app)
1356            .close(app, pointer);
1357    }
1358
1359    fn route(app: &mut App, event: PointerEvent) {
1360        GestureBinding::instance(app)
1361            .pointer_router(app)
1362            .route(app, event);
1363        app.drain_microtasks();
1364    }
1365
1366    /// What the callbacks of Flutter's scale tests record, each cleared by the test once
1367    /// checked.
1368    #[derive(Default)]
1369    struct Recorded {
1370        did_start_scale: Cell<bool>,
1371        updated_focal_point: Cell<Option<Offset>>,
1372        updated_pointer_count: Cell<Option<usize>>,
1373        updated_scale: Cell<Option<f64>>,
1374        updated_horizontal_scale: Cell<Option<f64>>,
1375        updated_vertical_scale: Cell<Option<f64>>,
1376        updated_delta: Cell<Option<Offset>>,
1377        did_end_scale: Cell<bool>,
1378        scale_end_velocity: Cell<Option<f64>>,
1379    }
1380
1381    fn record(app: &mut App, scale: Handle<ScaleGestureRecognizer>) -> Rc<Recorded> {
1382        let recorded = Rc::new(Recorded::default());
1383        let sink = Rc::clone(&recorded);
1384        scale.set_on_start(
1385            app,
1386            Some(Rc::new(move |_app, details: ScaleStartDetails| {
1387                sink.did_start_scale.set(true);
1388                sink.updated_focal_point.set(Some(details.focal_point));
1389                sink.updated_pointer_count.set(Some(details.pointer_count));
1390            })),
1391        );
1392        let sink = Rc::clone(&recorded);
1393        scale.set_on_update(
1394            app,
1395            Some(Rc::new(move |_app, details: ScaleUpdateDetails| {
1396                sink.updated_scale.set(Some(details.scale));
1397                sink.updated_horizontal_scale
1398                    .set(Some(details.horizontal_scale));
1399                sink.updated_vertical_scale
1400                    .set(Some(details.vertical_scale));
1401                sink.updated_focal_point.set(Some(details.focal_point));
1402                sink.updated_delta.set(Some(details.focal_point_delta));
1403                sink.updated_pointer_count.set(Some(details.pointer_count));
1404            })),
1405        );
1406        let sink = Rc::clone(&recorded);
1407        scale.set_on_end(
1408            app,
1409            Some(Rc::new(move |_app, details: ScaleEndDetails| {
1410                sink.did_end_scale.set(true);
1411                sink.scale_end_velocity.set(Some(details.scale_velocity));
1412            })),
1413        );
1414        recorded
1415    }
1416
1417    fn assert_offset_near(actual: Option<Offset>, expected: Offset) {
1418        let actual = actual.expect("an offset was reported");
1419        assert!(
1420            (actual.dx() - expected.dx()).abs() < 1e-9
1421                && (actual.dy() - expected.dy()).abs() < 1e-9,
1422            "{actual:?} != {expected:?}"
1423        );
1424    }
1425
1426    #[test]
1427    fn should_recognize_scale_gestures() {
1428        let cell = AppCell::new();
1429        let mut app = cell.borrow_mut();
1430        let scale = ScaleGestureRecognizer::new(&mut app);
1431        let tap = TapGestureRecognizer::new(&mut app);
1432        let r = record(&mut app, scale.handle());
1433        let did_tap = Rc::new(Cell::new(false));
1434        let tapped = Rc::clone(&did_tap);
1435        tap.set_on_tap(
1436            &mut app,
1437            Some(waft_foundation::Listener::new(move |_| tapped.set(true))),
1438        );
1439
1440        let mut pointer1 = TestPointer::new(1);
1441        let down = pointer1.down(Offset::ZERO);
1442        scale.add_pointer(&mut app, down.clone());
1443        tap.add_pointer(&mut app, down.clone());
1444
1445        close_arena(&mut app, 1);
1446        assert!(!r.did_start_scale.get());
1447        assert_eq!(r.updated_scale.get(), None);
1448        assert_eq!(r.updated_focal_point.get(), None);
1449        assert_eq!(r.updated_delta.get(), None);
1450        assert_eq!(r.updated_pointer_count.get(), None);
1451        assert!(!r.did_end_scale.get());
1452        assert!(!did_tap.get());
1453
1454        // One-finger panning
1455        route(&mut app, PointerEvent::Down(down));
1456        assert!(!r.did_start_scale.get());
1457        assert_eq!(r.updated_scale.get(), None);
1458        assert!(!did_tap.get());
1459
1460        route(
1461            &mut app,
1462            PointerEvent::Move(pointer1.move_to(Offset::new(20.0, 30.0))),
1463        );
1464        assert!(r.did_start_scale.replace(false));
1465        assert_offset_near(r.updated_focal_point.take(), Offset::new(20.0, 30.0));
1466        assert_eq!(r.updated_scale.take(), Some(1.0));
1467        assert_offset_near(r.updated_delta.take(), Offset::new(20.0, 30.0));
1468        assert_eq!(r.updated_pointer_count.take(), Some(1));
1469        assert!(!r.did_end_scale.get());
1470        assert!(!did_tap.get());
1471
1472        // Two-finger scaling
1473        let mut pointer2 = TestPointer::new(2);
1474        let down2 = pointer2.down(Offset::new(10.0, 20.0));
1475        scale.add_pointer(&mut app, down2.clone());
1476        tap.add_pointer(&mut app, down2.clone());
1477        close_arena(&mut app, 2);
1478        route(&mut app, PointerEvent::Down(down2));
1479
1480        assert!(r.did_end_scale.replace(false));
1481        assert_eq!(r.updated_scale.get(), None);
1482        assert_eq!(r.updated_focal_point.get(), None);
1483        assert_eq!(r.updated_delta.get(), None);
1484        assert_eq!(r.updated_pointer_count.get(), None);
1485        assert!(!r.did_start_scale.get());
1486
1487        // Zoom in
1488        route(
1489            &mut app,
1490            PointerEvent::Move(pointer2.move_to(Offset::new(0.0, 10.0))),
1491        );
1492        assert!(r.did_start_scale.replace(false));
1493        assert_offset_near(r.updated_focal_point.take(), Offset::new(10.0, 20.0));
1494        assert_eq!(r.updated_scale.take(), Some(2.0));
1495        assert_eq!(r.updated_horizontal_scale.take(), Some(2.0));
1496        assert_eq!(r.updated_vertical_scale.take(), Some(2.0));
1497        assert_offset_near(r.updated_delta.take(), Offset::new(-5.0, -5.0));
1498        assert_eq!(r.updated_pointer_count.take(), Some(2));
1499        assert!(!r.did_end_scale.get());
1500        assert!(!did_tap.get());
1501
1502        // Zoom out
1503        route(
1504            &mut app,
1505            PointerEvent::Move(pointer2.move_to(Offset::new(15.0, 25.0))),
1506        );
1507        assert_offset_near(r.updated_focal_point.get(), Offset::new(17.5, 27.5));
1508        assert_eq!(r.updated_scale.get(), Some(0.5));
1509        assert_eq!(r.updated_horizontal_scale.get(), Some(0.5));
1510        assert_eq!(r.updated_vertical_scale.get(), Some(0.5));
1511        assert_offset_near(r.updated_delta.get(), Offset::new(7.5, 7.5));
1512        assert_eq!(r.updated_pointer_count.get(), Some(2));
1513        assert!(!did_tap.get());
1514
1515        // Horizontal scaling
1516        route(
1517            &mut app,
1518            PointerEvent::Move(pointer2.move_to(Offset::new(0.0, 20.0))),
1519        );
1520        assert_eq!(r.updated_horizontal_scale.get(), Some(2.0));
1521        assert_eq!(r.updated_vertical_scale.get(), Some(1.0));
1522        assert_eq!(r.updated_pointer_count.get(), Some(2));
1523
1524        // Vertical scaling
1525        route(
1526            &mut app,
1527            PointerEvent::Move(pointer2.move_to(Offset::new(10.0, 10.0))),
1528        );
1529        assert_eq!(r.updated_horizontal_scale.get(), Some(1.0));
1530        assert_eq!(r.updated_vertical_scale.get(), Some(2.0));
1531        assert_offset_near(r.updated_delta.get(), Offset::new(5.0, -5.0));
1532        assert_eq!(r.updated_pointer_count.get(), Some(2));
1533        route(
1534            &mut app,
1535            PointerEvent::Move(pointer2.move_to(Offset::new(15.0, 25.0))),
1536        );
1537        r.updated_focal_point.set(None);
1538        r.updated_scale.set(None);
1539        r.updated_delta.set(None);
1540        r.updated_pointer_count.set(None);
1541
1542        // Three-finger scaling
1543        let mut pointer3 = TestPointer::new(3);
1544        let down3 = pointer3.down(Offset::new(25.0, 35.0));
1545        scale.add_pointer(&mut app, down3.clone());
1546        tap.add_pointer(&mut app, down3.clone());
1547        close_arena(&mut app, 3);
1548        route(&mut app, PointerEvent::Down(down3));
1549
1550        assert!(r.did_end_scale.replace(false));
1551        assert_eq!(r.updated_scale.get(), None);
1552        assert_eq!(r.updated_focal_point.get(), None);
1553        assert_eq!(r.updated_delta.get(), None);
1554        assert_eq!(r.updated_pointer_count.get(), None);
1555        assert!(!r.did_start_scale.get());
1556
1557        // Zoom in
1558        route(
1559            &mut app,
1560            PointerEvent::Move(pointer3.move_to(Offset::new(55.0, 65.0))),
1561        );
1562        assert!(r.did_start_scale.replace(false));
1563        assert_offset_near(r.updated_focal_point.take(), Offset::new(30.0, 40.0));
1564        assert_eq!(r.updated_scale.take(), Some(5.0));
1565        assert_offset_near(r.updated_delta.take(), Offset::new(10.0, 10.0));
1566        assert_eq!(r.updated_pointer_count.take(), Some(3));
1567        assert!(!r.did_end_scale.get());
1568        assert!(!did_tap.get());
1569
1570        // Return to original positions but with different fingers
1571        route(
1572            &mut app,
1573            PointerEvent::Move(pointer1.move_to(Offset::new(25.0, 35.0))),
1574        );
1575        route(
1576            &mut app,
1577            PointerEvent::Move(pointer2.move_to(Offset::new(20.0, 30.0))),
1578        );
1579        route(
1580            &mut app,
1581            PointerEvent::Move(pointer3.move_to(Offset::new(15.0, 25.0))),
1582        );
1583        assert!(!r.did_start_scale.get());
1584        assert_offset_near(r.updated_focal_point.take(), Offset::new(20.0, 30.0));
1585        let scale_factor = r.updated_scale.take().expect("a scale");
1586        assert!((scale_factor - 1.0).abs() < 1e-9);
1587        let delta = r.updated_delta.take().expect("a delta");
1588        assert!((delta.dx() + 13.3).abs() < 0.1);
1589        assert!((delta.dy() + 13.3).abs() < 0.1);
1590        assert_eq!(r.updated_pointer_count.take(), Some(3));
1591        assert!(!r.did_end_scale.get());
1592        assert!(!did_tap.get());
1593
1594        route(&mut app, PointerEvent::Up(pointer1.up()));
1595        assert!(!r.did_start_scale.get());
1596        assert_eq!(r.updated_focal_point.get(), None);
1597        assert_eq!(r.updated_scale.get(), None);
1598        assert_eq!(r.updated_delta.get(), None);
1599        assert!(r.did_end_scale.replace(false));
1600        assert!(!did_tap.get());
1601
1602        // Continue scaling with two fingers
1603        route(
1604            &mut app,
1605            PointerEvent::Move(pointer3.move_to(Offset::new(10.0, 20.0))),
1606        );
1607        assert!(r.did_start_scale.replace(false));
1608        assert_offset_near(r.updated_focal_point.take(), Offset::new(15.0, 25.0));
1609        assert_eq!(r.updated_scale.take(), Some(2.0));
1610        assert_offset_near(r.updated_delta.take(), Offset::new(-2.5, -2.5));
1611        assert_eq!(r.updated_pointer_count.take(), Some(2));
1612
1613        // Continue rotating with two fingers
1614        route(
1615            &mut app,
1616            PointerEvent::Move(pointer3.move_to(Offset::new(30.0, 40.0))),
1617        );
1618        assert_offset_near(r.updated_focal_point.take(), Offset::new(25.0, 35.0));
1619        assert_eq!(r.updated_scale.take(), Some(2.0));
1620        assert_offset_near(r.updated_delta.take(), Offset::new(10.0, 10.0));
1621        route(
1622            &mut app,
1623            PointerEvent::Move(pointer3.move_to(Offset::new(10.0, 20.0))),
1624        );
1625        assert_offset_near(r.updated_focal_point.take(), Offset::new(15.0, 25.0));
1626        assert_eq!(r.updated_scale.take(), Some(2.0));
1627        assert_offset_near(r.updated_delta.take(), Offset::new(-10.0, -10.0));
1628        assert_eq!(r.updated_pointer_count.take(), Some(2));
1629
1630        route(&mut app, PointerEvent::Up(pointer2.up()));
1631        assert!(!r.did_start_scale.get());
1632        assert_eq!(r.updated_focal_point.get(), None);
1633        assert_eq!(r.updated_scale.get(), None);
1634        assert_eq!(r.updated_delta.get(), None);
1635        assert!(r.did_end_scale.replace(false));
1636        assert!(!did_tap.get());
1637
1638        // Continue panning with one finger
1639        route(&mut app, PointerEvent::Move(pointer3.move_to(Offset::ZERO)));
1640        assert!(r.did_start_scale.replace(false));
1641        assert_offset_near(r.updated_focal_point.take(), Offset::ZERO);
1642        assert_eq!(r.updated_scale.take(), Some(1.0));
1643        assert_offset_near(r.updated_delta.take(), Offset::new(-10.0, -20.0));
1644        assert_eq!(r.updated_pointer_count.take(), Some(1));
1645
1646        // We are done
1647        route(&mut app, PointerEvent::Up(pointer3.up()));
1648        assert!(!r.did_start_scale.get());
1649        assert_eq!(r.updated_focal_point.get(), None);
1650        assert_eq!(r.updated_scale.get(), None);
1651        assert_eq!(r.updated_delta.get(), None);
1652        assert_eq!(r.updated_pointer_count.get(), None);
1653        assert!(r.did_end_scale.replace(false));
1654        assert!(!did_tap.get());
1655
1656        scale.dispose(&mut app);
1657        tap.dispose(&mut app);
1658    }
1659
1660    #[test]
1661    fn rejects_scale_gestures_from_unallowed_device_kinds() {
1662        let cell = AppCell::new();
1663        let mut app = cell.borrow_mut();
1664        let scale = ScaleGestureRecognizer::new(&mut app)
1665            .supported_devices(&mut app, [PointerDeviceKind::Touch]);
1666        let r = record(&mut app, scale.handle());
1667
1668        let mut mouse_pointer = TestPointer::with_kind(1, PointerDeviceKind::Mouse);
1669        let down = mouse_pointer.down(Offset::ZERO);
1670        scale.add_pointer(&mut app, down.clone());
1671        close_arena(&mut app, 1);
1672
1673        // One-finger panning
1674        route(&mut app, PointerEvent::Down(down));
1675        assert!(!r.did_start_scale.get());
1676        assert_eq!(r.updated_scale.get(), None);
1677
1678        // Using a mouse, the scale gesture shouldn't even start.
1679        route(
1680            &mut app,
1681            PointerEvent::Move(mouse_pointer.move_to(Offset::new(20.0, 30.0))),
1682        );
1683        assert!(!r.did_start_scale.get());
1684        assert_eq!(r.updated_scale.get(), None);
1685
1686        scale.dispose(&mut app);
1687    }
1688
1689    #[test]
1690    fn scale_gesture_competes_with_drag() {
1691        let cell = AppCell::new();
1692        let mut app = cell.borrow_mut();
1693        let scale = ScaleGestureRecognizer::new(&mut app);
1694        let drag = HorizontalDragGestureRecognizer::new(&mut app);
1695
1696        let log = Rc::new(RefCell::new(Vec::<&'static str>::new()));
1697        let sink = Rc::clone(&log);
1698        scale.set_on_start(
1699            &mut app,
1700            Some(Rc::new(move |_app, _details| {
1701                sink.borrow_mut().push("scale-start")
1702            })),
1703        );
1704        let sink = Rc::clone(&log);
1705        scale.set_on_update(
1706            &mut app,
1707            Some(Rc::new(move |_app, _details| {
1708                sink.borrow_mut().push("scale-update")
1709            })),
1710        );
1711        let sink = Rc::clone(&log);
1712        scale.set_on_end(
1713            &mut app,
1714            Some(Rc::new(move |_app, _details| {
1715                sink.borrow_mut().push("scale-end")
1716            })),
1717        );
1718        let sink = Rc::clone(&log);
1719        drag.set_on_start(
1720            &mut app,
1721            Some(Rc::new(move |_app, _details: DragStartDetails| {
1722                sink.borrow_mut().push("drag-start")
1723            })),
1724        );
1725        let sink = Rc::clone(&log);
1726        drag.set_on_end(
1727            &mut app,
1728            Some(Rc::new(move |_app, _details: DragEndDetails| {
1729                sink.borrow_mut().push("drag-end")
1730            })),
1731        );
1732
1733        let mut pointer1 = TestPointer::new(1);
1734        let down = pointer1.down(Offset::new(10.0, 10.0));
1735        scale.add_pointer(&mut app, down.clone());
1736        drag.add_pointer(&mut app, down.clone());
1737
1738        close_arena(&mut app, 1);
1739        assert!(log.borrow().is_empty());
1740
1741        // Vertical moves are scales.
1742        route(&mut app, PointerEvent::Down(down));
1743        assert!(log.borrow().is_empty());
1744
1745        // Scale will win if focal point delta exceeds 18.0*2.
1746        route(
1747            &mut app,
1748            PointerEvent::Move(pointer1.move_to(Offset::new(10.0, 50.0))),
1749        );
1750        assert_eq!(log.take(), ["scale-start", "scale-update"]);
1751
1752        let mut pointer2 = TestPointer::new(2);
1753        let down2 = pointer2.down(Offset::new(10.0, 20.0));
1754        scale.add_pointer(&mut app, down2.clone());
1755        drag.add_pointer(&mut app, down2.clone());
1756
1757        close_arena(&mut app, 2);
1758        assert!(log.borrow().is_empty());
1759
1760        // Second pointer joins scale even though it moves horizontally.
1761        route(&mut app, PointerEvent::Down(down2));
1762        assert_eq!(log.take(), ["scale-end"]);
1763
1764        route(
1765            &mut app,
1766            PointerEvent::Move(pointer2.move_to(Offset::new(30.0, 20.0))),
1767        );
1768        assert_eq!(log.take(), ["scale-start", "scale-update"]);
1769
1770        route(&mut app, PointerEvent::Up(pointer1.up()));
1771        assert_eq!(log.take(), ["scale-end"]);
1772
1773        route(&mut app, PointerEvent::Up(pointer2.up()));
1774        assert!(log.borrow().is_empty());
1775
1776        // Horizontal moves are either drags or scales, depending on which wins first.
1777        // In this case, we move fast, so that the scale wins. If we moved slowly,
1778        // the horizontal drag would win, since it was added first.
1779        let mut pointer3 = TestPointer::new(3);
1780        let down3 = pointer3.down(Offset::new(30.0, 30.0));
1781        scale.add_pointer(&mut app, down3.clone());
1782        drag.add_pointer(&mut app, down3.clone());
1783        close_arena(&mut app, 3);
1784        route(&mut app, PointerEvent::Down(down3));
1785
1786        assert!(log.borrow().is_empty());
1787
1788        route(
1789            &mut app,
1790            PointerEvent::Move(pointer3.move_to(Offset::new(100.0, 30.0))),
1791        );
1792        assert_eq!(log.take(), ["scale-start", "scale-update"]);
1793
1794        route(&mut app, PointerEvent::Up(pointer3.up()));
1795        assert_eq!(log.take(), ["scale-end"]);
1796
1797        scale.dispose(&mut app);
1798        DragGestureRecognizer::dispose(drag.handle(), &mut app);
1799    }
1800
1801    #[test]
1802    fn should_recognize_scale_gestures_from_pointer_pan_zoom_events() {
1803        let cell = AppCell::new();
1804        let mut app = cell.borrow_mut();
1805        let scale = ScaleGestureRecognizer::new(&mut app);
1806        let drag = HorizontalDragGestureRecognizer::new(&mut app);
1807        let r = record(&mut app, scale.handle());
1808
1809        let mut pointer1 = TestPointer::with_kind(2, PointerDeviceKind::Trackpad);
1810        let start = pointer1.pan_zoom_start(Offset::ZERO);
1811        scale.add_pointer_pan_zoom(&mut app, start.clone());
1812        drag.add_pointer_pan_zoom(&mut app, start.clone());
1813
1814        close_arena(&mut app, 2);
1815        assert!(!r.did_start_scale.get());
1816        assert_eq!(r.updated_scale.get(), None);
1817        assert_eq!(r.updated_focal_point.get(), None);
1818        assert_eq!(r.updated_delta.get(), None);
1819        assert_eq!(r.updated_pointer_count.get(), None);
1820        assert!(!r.did_end_scale.get());
1821
1822        // Panning.
1823        route(&mut app, PointerEvent::PanZoomStart(start));
1824        assert!(!r.did_start_scale.get());
1825        assert_eq!(r.updated_scale.get(), None);
1826        assert_eq!(r.updated_focal_point.get(), None);
1827        assert!(!r.did_end_scale.get());
1828
1829        route(
1830            &mut app,
1831            PointerEvent::PanZoomUpdate(pointer1.pan_zoom_update(
1832                Offset::ZERO,
1833                Offset::new(20.0, 30.0),
1834                1.0,
1835                Duration::ZERO,
1836            )),
1837        );
1838        assert!(r.did_start_scale.replace(false));
1839        assert_offset_near(r.updated_focal_point.take(), Offset::new(20.0, 30.0));
1840        assert_eq!(r.updated_scale.take(), Some(1.0));
1841        assert_offset_near(r.updated_delta.take(), Offset::new(20.0, 30.0));
1842        assert_eq!(r.updated_pointer_count.take(), Some(2));
1843        assert!(!r.did_end_scale.get());
1844
1845        // Zoom in.
1846        route(
1847            &mut app,
1848            PointerEvent::PanZoomUpdate(pointer1.pan_zoom_update(
1849                Offset::ZERO,
1850                Offset::new(20.0, 30.0),
1851                2.0,
1852                Duration::ZERO,
1853            )),
1854        );
1855        assert_offset_near(r.updated_focal_point.take(), Offset::new(20.0, 30.0));
1856        assert_eq!(r.updated_scale.take(), Some(2.0));
1857        assert_eq!(r.updated_horizontal_scale.take(), Some(2.0));
1858        assert_eq!(r.updated_vertical_scale.take(), Some(2.0));
1859        assert_offset_near(r.updated_delta.take(), Offset::ZERO);
1860        assert_eq!(r.updated_pointer_count.take(), Some(2));
1861        assert!(!r.did_end_scale.get());
1862
1863        // Zoom out.
1864        route(
1865            &mut app,
1866            PointerEvent::PanZoomUpdate(pointer1.pan_zoom_update(
1867                Offset::ZERO,
1868                Offset::new(20.0, 30.0),
1869                1.0,
1870                Duration::ZERO,
1871            )),
1872        );
1873        assert_offset_near(r.updated_focal_point.take(), Offset::new(20.0, 30.0));
1874        assert_eq!(r.updated_scale.take(), Some(1.0));
1875        assert_eq!(r.updated_horizontal_scale.take(), Some(1.0));
1876        assert_eq!(r.updated_vertical_scale.take(), Some(1.0));
1877        assert_offset_near(r.updated_delta.take(), Offset::ZERO);
1878        assert_eq!(r.updated_pointer_count.take(), Some(2));
1879        assert!(!r.did_end_scale.get());
1880
1881        // We are done.
1882        route(
1883            &mut app,
1884            PointerEvent::PanZoomEnd(pointer1.pan_zoom_end(Duration::ZERO)),
1885        );
1886        assert!(!r.did_start_scale.get());
1887        assert_eq!(r.updated_focal_point.get(), None);
1888        assert_eq!(r.updated_scale.get(), None);
1889        assert_eq!(r.updated_delta.get(), None);
1890        assert_eq!(r.updated_pointer_count.get(), None);
1891        assert!(r.did_end_scale.replace(false));
1892
1893        scale.dispose(&mut app);
1894        DragGestureRecognizer::dispose(drag.handle(), &mut app);
1895    }
1896
1897    #[test]
1898    fn scale_ending_velocity() {
1899        let cell = AppCell::new();
1900        let mut app = cell.borrow_mut();
1901        let scale = ScaleGestureRecognizer::new(&mut app);
1902        scale.set_drag_start_behavior(&mut app, DragStartBehavior::Start);
1903        scale.set_trackpad_scroll_causes_scale(&mut app, true);
1904        let r = record(&mut app, scale.handle());
1905        // Flutter's test listens for the start and the end only.
1906        scale.set_on_update(&mut app, None);
1907
1908        let mut pointer1 = TestPointer::with_kind(2, PointerDeviceKind::Trackpad);
1909        let start = pointer1.pan_zoom_start(Offset::ZERO);
1910        scale.add_pointer_pan_zoom(&mut app, start.clone());
1911
1912        close_arena(&mut app, 2);
1913        assert!(!r.did_start_scale.get());
1914        assert_eq!(r.updated_focal_point.get(), None);
1915        assert!(!r.did_end_scale.get());
1916
1917        route(&mut app, PointerEvent::PanZoomStart(start));
1918        assert!(r.did_start_scale.replace(false));
1919        assert_offset_near(r.updated_focal_point.take(), Offset::ZERO);
1920        assert!(!r.did_end_scale.get());
1921
1922        // Zoom in by scrolling up.
1923        for i in 0..100_u64 {
1924            route(
1925                &mut app,
1926                PointerEvent::PanZoomUpdate(pointer1.pan_zoom_update(
1927                    Offset::ZERO,
1928                    Offset::new(0.0, i as f64 * -10.0),
1929                    1.0,
1930                    Duration::from_millis(i * 25),
1931                )),
1932            );
1933        }
1934
1935        // End.
1936        route(
1937            &mut app,
1938            PointerEvent::PanZoomEnd(pointer1.pan_zoom_end(Duration::from_millis(2500))),
1939        );
1940        assert!(!r.did_start_scale.get());
1941        assert_eq!(r.updated_focal_point.get(), None);
1942        assert!(r.did_end_scale.replace(false));
1943        let velocity = r.scale_end_velocity.get().expect("an end velocity");
1944        assert!(
1945            (velocity - 281.414_540_980_277_65).abs() < 1e-6,
1946            "{velocity}"
1947        );
1948
1949        scale.dispose(&mut app);
1950    }
1951}