Skip to main content

waft_gestures/
events.rs

1//! Flutter counterpart: `gestures/events.dart`.
2
3use std::time::Duration;
4
5use waft_embedder::{Matrix4, Offset, PointerDeviceKind, ViewId};
6use waft_foundation::ValueChanged;
7
8use crate::constants::{
9    K_PAN_SLOP, K_PRECISE_POINTER_HIT_SLOP, K_PRECISE_POINTER_PAN_SLOP,
10    K_PRECISE_POINTER_SCALE_SLOP, K_SCALE_SLOP, K_TOUCH_SLOP,
11};
12use crate::gesture_settings::DeviceGestureSettings;
13
14/// The bit of [`PointerEvent`] `buttons` that corresponds to a cross-device
15/// behavior of "primary operation".
16pub const K_PRIMARY_BUTTON: i64 = 0x01;
17
18/// The bit of [`PointerEvent`] `buttons` that corresponds to a cross-device
19/// behavior of "secondary operation".
20pub const K_SECONDARY_BUTTON: i64 = 0x02;
21
22/// The bit of [`PointerEvent`] `buttons` that corresponds to the primary mouse
23/// button.
24pub const K_PRIMARY_MOUSE_BUTTON: i64 = K_PRIMARY_BUTTON;
25
26/// The bit of [`PointerEvent`] `buttons` that corresponds to the secondary mouse
27/// button.
28pub const K_SECONDARY_MOUSE_BUTTON: i64 = K_SECONDARY_BUTTON;
29
30/// The bit of [`PointerEvent`] `buttons` that corresponds to when a stylus
31/// contacting the screen.
32pub const K_STYLUS_CONTACT: i64 = K_PRIMARY_BUTTON;
33
34/// The bit of [`PointerEvent`] `buttons` that corresponds to the primary stylus
35/// button.
36pub const K_PRIMARY_STYLUS_BUTTON: i64 = K_SECONDARY_BUTTON;
37
38/// The bit of [`PointerEvent`] `buttons` that corresponds to a cross-device
39/// behavior of "tertiary operation".
40pub const K_TERTIARY_BUTTON: i64 = 0x04;
41
42/// The bit of [`PointerEvent`] `buttons` that corresponds to the middle mouse
43/// button.
44pub const K_MIDDLE_MOUSE_BUTTON: i64 = K_TERTIARY_BUTTON;
45
46/// The bit of [`PointerEvent`] `buttons` that corresponds to the secondary
47/// stylus button.
48pub const K_SECONDARY_STYLUS_BUTTON: i64 = K_TERTIARY_BUTTON;
49
50/// The bit of [`PointerEvent`] `buttons` that corresponds to the back mouse
51/// button.
52pub const K_BACK_MOUSE_BUTTON: i64 = 0x08;
53
54/// The bit of [`PointerEvent`] `buttons` that corresponds to the forward mouse
55/// button.
56pub const K_FORWARD_MOUSE_BUTTON: i64 = 0x10;
57
58/// The bit of [`PointerEvent`] `buttons` that corresponds to the pointer
59/// contacting a touch screen.
60pub const K_TOUCH_CONTACT: i64 = K_PRIMARY_BUTTON;
61
62/// Dart VM `kMaxUnsignedSMI` (`foundation/_bitfield_io.dart`).
63const K_MAX_UNSIGNED_SMI: i64 = 0x3FFF_FFFF_FFFF_FFFF;
64
65/// The bit of [`PointerEvent`] `buttons` that corresponds to the nth mouse
66/// button.
67pub fn nth_mouse_button(number: i64) -> i64 {
68    K_PRIMARY_MOUSE_BUTTON.wrapping_shl((number - 1) as u32) & K_MAX_UNSIGNED_SMI
69}
70
71/// The bit of [`PointerEvent`] `buttons` that corresponds to the nth stylus
72/// button.
73pub fn nth_stylus_button(number: i64) -> i64 {
74    K_PRIMARY_STYLUS_BUTTON.wrapping_shl((number - 1) as u32) & K_MAX_UNSIGNED_SMI
75}
76
77/// Returns the button of `buttons` with the smallest integer.
78///
79/// It returns zero when `buttons` is zero.
80pub fn smallest_button(buttons: i64) -> i64 {
81    buttons.isolate_lowest_one()
82}
83
84/// Returns whether `buttons` contains one and only one button.
85pub fn is_single_button(buttons: i64) -> bool {
86    buttons != 0 && smallest_button(buttons) == buttons
87}
88
89macro_rules! pointer_event_struct {
90    (
91        $(#[$meta:meta])*
92        pub struct $name:ident {
93            $($(#[$extra_meta:meta])* $extra_vis:vis $extra:ident: $extra_ty:ty = $extra_default:expr),* $(,)?
94        }
95        down = $down:expr,
96        pressure = $pressure:expr,
97        distance = $distance:expr,
98        buttons = $buttons:expr,
99        kind = $kind:expr $(,)?
100    ) => {
101        $(#[$meta])*
102        #[derive(Clone, Debug)]
103        pub struct $name {
104            /// The ID of the `FlutterView` which this event originated from.
105            pub view_id: ViewId,
106            /// Unique identifier that ties the [`PointerEvent`] to the embedder
107            /// event that created it.
108            pub embedder_id: i64,
109            /// Time of event dispatch, relative to an arbitrary timeline.
110            pub time_stamp: Duration,
111            /// Unique identifier for the pointer, not reused.
112            pub pointer: i64,
113            /// The kind of input device for which the event was generated.
114            pub kind: PointerDeviceKind,
115            /// Unique identifier for the pointing device, reused across
116            /// interactions.
117            pub device: i64,
118            /// Coordinate of the position of the pointer, in logical pixels in
119            /// the global coordinate space.
120            pub position: Offset,
121            /// Distance in logical pixels that the pointer moved since the last
122            /// [`PointerMoveEvent`] or [`PointerHoverEvent`].
123            pub delta: Offset,
124            /// Bit field using the `*_BUTTON` constants.
125            pub buttons: i64,
126            /// Set if the pointer is currently down.
127            pub down: bool,
128            /// Set if an application from a different security domain is in any
129            /// way obscuring this application's window.
130            pub obscured: bool,
131            /// The pressure of the touch.
132            pub pressure: f64,
133            /// The minimum value that [`pressure`](Self::pressure) can return.
134            pub pressure_min: f64,
135            /// The maximum value that [`pressure`](Self::pressure) can return.
136            pub pressure_max: f64,
137            /// The distance of the detected object from the input surface.
138            pub distance: f64,
139            /// The maximum value that [`distance`](Self::distance) can return.
140            pub distance_max: f64,
141            /// The area of the screen being pressed.
142            pub size: f64,
143            /// The radius of the contact ellipse along the major axis, in
144            /// logical pixels.
145            pub radius_major: f64,
146            /// The radius of the contact ellipse along the minor axis, in
147            /// logical pixels.
148            pub radius_minor: f64,
149            /// The minimum value that could be reported for radius major/minor.
150            pub radius_min: f64,
151            /// The maximum value that could be reported for radius major/minor.
152            pub radius_max: f64,
153            /// The orientation angle of the detected object, in radians.
154            pub orientation: f64,
155            /// The tilt angle of the detected object, in radians.
156            pub tilt: f64,
157            /// Opaque platform-specific data associated with the event.
158            pub platform_data: i64,
159            /// Set if the event was synthesized by Flutter.
160            pub synthesized: bool,
161            /// The transformation used to transform this event from the global
162            /// coordinate space into the coordinate space of the event
163            /// receiver.
164            pub transform: Option<Matrix4>,
165            /// The original un-transformed event before any transforms were
166            /// applied.
167            pub original: Option<Box<$name>>,
168            $($(#[$extra_meta])* $extra_vis $extra: $extra_ty,)*
169        }
170
171        impl Default for $name {
172            fn default() -> $name {
173                $name {
174                    view_id: ViewId(0),
175                    embedder_id: 0,
176                    time_stamp: Duration::ZERO,
177                    pointer: 0,
178                    kind: $kind,
179                    device: 0,
180                    position: Offset::ZERO,
181                    delta: Offset::ZERO,
182                    buttons: $buttons,
183                    down: $down,
184                    obscured: false,
185                    pressure: $pressure,
186                    pressure_min: 1.0,
187                    pressure_max: 1.0,
188                    distance: $distance,
189                    distance_max: 0.0,
190                    size: 0.0,
191                    radius_major: 0.0,
192                    radius_minor: 0.0,
193                    radius_min: 0.0,
194                    radius_max: 0.0,
195                    orientation: 0.0,
196                    tilt: 0.0,
197                    platform_data: 0,
198                    synthesized: false,
199                    transform: None,
200                    original: None,
201                    $($extra: $extra_default,)*
202                }
203            }
204        }
205
206        impl $name {
207            /// The [`position`](Self::position) transformed into the event
208            /// receiver's local coordinate system according to
209            /// [`transform`](Self::transform).
210            pub fn local_position(&self) -> Offset {
211                transform_position(self.transform, self.position)
212            }
213
214            /// The [`delta`](Self::delta) transformed into the event receiver's
215            /// local coordinate system according to [`transform`](Self::transform).
216            pub fn local_delta(&self) -> Offset {
217                transform_delta_via_positions(
218                    self.position,
219                    None,
220                    self.delta,
221                    self.transform,
222                )
223            }
224
225            /// The minimum value that [`distance`](Self::distance) can return.
226            ///
227            /// This value is always 0.0.
228            pub fn distance_min(&self) -> f64 {
229                0.0
230            }
231
232            /// Transforms the event from the global coordinate space into the
233            /// coordinate space of an event receiver.
234            pub fn transformed(&self, transform: Option<Matrix4>) -> $name {
235                if transform.is_none() || self.transform == transform {
236                    return self.clone();
237                }
238                let original = self.original.clone().unwrap_or_else(|| {
239                    let mut orig = self.clone();
240                    orig.transform = None;
241                    orig.original = None;
242                    Box::new(orig)
243                });
244                let mut event = (*original).clone();
245                event.original = Some(original);
246                event.transform = transform;
247                event
248            }
249
250            /// Creates a copy of this event. Chain field replacements, then
251            /// [`transformed`](Self::transformed) if a transform should stick.
252            pub fn copy_with(&self) -> $name {
253                self.clone()
254            }
255        }
256    };
257}
258
259pointer_event_struct! {
260    /// The device has started tracking the pointer.
261    pub struct PointerAddedEvent {}
262    down = false,
263    pressure = 0.0,
264    distance = 0.0,
265    buttons = 0,
266    kind = PointerDeviceKind::Touch,
267}
268
269pointer_event_struct! {
270    /// The device is no longer tracking the pointer.
271    pub struct PointerRemovedEvent {}
272    down = false,
273    pressure = 0.0,
274    distance = 0.0,
275    buttons = 0,
276    kind = PointerDeviceKind::Touch,
277}
278
279pointer_event_struct! {
280    /// The pointer has moved with respect to the device while not in contact
281    /// with the device.
282    pub struct PointerHoverEvent {}
283    down = false,
284    pressure = 0.0,
285    distance = 0.0,
286    buttons = 0,
287    kind = PointerDeviceKind::Touch,
288}
289
290pointer_event_struct! {
291    /// The pointer has moved with respect to the device while not in contact
292    /// with the device, and entered a target object.
293    ///
294    /// Only sent through `MouseTracker` annotation callbacks, never by pointer
295    /// routing or hit testing.
296    pub struct PointerEnterEvent {}
297    down = false,
298    pressure = 0.0,
299    distance = 0.0,
300    buttons = 0,
301    kind = PointerDeviceKind::Touch,
302}
303
304pointer_event_struct! {
305    /// The pointer has moved with respect to the device while not in contact
306    /// with the device, and exited a target object.
307    ///
308    /// Only sent through `MouseTracker` annotation callbacks, never by pointer
309    /// routing or hit testing.
310    pub struct PointerExitEvent {}
311    down = false,
312    pressure = 0.0,
313    distance = 0.0,
314    buttons = 0,
315    kind = PointerDeviceKind::Touch,
316}
317
318pointer_event_struct! {
319    /// The pointer has made contact with the device.
320    pub struct PointerDownEvent {}
321    down = true,
322    pressure = 1.0,
323    distance = 0.0,
324    buttons = K_PRIMARY_BUTTON,
325    kind = PointerDeviceKind::Touch,
326}
327
328pointer_event_struct! {
329    /// The pointer has moved with respect to the device while in contact with
330    /// the device.
331    pub struct PointerMoveEvent {}
332    down = true,
333    pressure = 1.0,
334    distance = 0.0,
335    buttons = K_PRIMARY_BUTTON,
336    kind = PointerDeviceKind::Touch,
337}
338
339pointer_event_struct! {
340    /// The pointer has stopped making contact with the device.
341    pub struct PointerUpEvent {}
342    down = false,
343    pressure = 0.0,
344    distance = 0.0,
345    buttons = 0,
346    kind = PointerDeviceKind::Touch,
347}
348
349pointer_event_struct! {
350    /// The input from the pointer is no longer directed towards this receiver.
351    pub struct PointerCancelEvent {}
352    down = false,
353    pressure = 0.0,
354    distance = 0.0,
355    buttons = 0,
356    kind = PointerDeviceKind::Touch,
357}
358
359pointer_event_struct! {
360    /// The pointer issued a scroll event.
361    pub struct PointerScrollEvent {
362        /// The amount to scroll, in logical pixels.
363        pub scroll_delta: Offset = Offset::ZERO,
364    }
365    down = false,
366    pressure = 1.0,
367    distance = 0.0,
368    buttons = 0,
369    kind = PointerDeviceKind::Touch,
370}
371
372pointer_event_struct! {
373    /// The pointer issued a scroll-inertia cancel event.
374    pub struct PointerScrollInertiaCancelEvent {}
375    down = false,
376    pressure = 1.0,
377    distance = 0.0,
378    buttons = 0,
379    kind = PointerDeviceKind::Touch,
380}
381
382pointer_event_struct! {
383    /// The pointer issued a scale event.
384    pub struct PointerScaleEvent {
385        /// The scale implied by the trackpad event.
386        pub scale: f64 = 1.0,
387    }
388    down = false,
389    pressure = 1.0,
390    distance = 0.0,
391    buttons = 0,
392    kind = PointerDeviceKind::Touch,
393}
394
395pointer_event_struct! {
396    /// A pan/zoom has begun on this pointer.
397    pub struct PointerPanZoomStartEvent {}
398    down = false,
399    pressure = 1.0,
400    distance = 0.0,
401    buttons = 0,
402    kind = PointerDeviceKind::Trackpad,
403}
404
405pointer_event_struct! {
406    /// The active pan/zoom on this pointer has updated.
407    pub struct PointerPanZoomUpdateEvent {
408        /// The current panning magnitude of the pan/zoom in logical pixels.
409        pub pan: Offset = Offset::ZERO,
410        /// The difference in panning since the last pan/zoom update, in logical
411        /// pixels.
412        pub pan_delta: Offset = Offset::ZERO,
413        /// The current scale of the pan/zoom (unitless), with 1.0 as the
414        /// initial scale.
415        pub scale: f64 = 1.0,
416        /// The current angle of the pan/zoom in radians, with 0.0 as the
417        /// initial angle.
418        pub rotation: f64 = 0.0,
419    }
420    down = false,
421    pressure = 1.0,
422    distance = 0.0,
423    buttons = 0,
424    kind = PointerDeviceKind::Trackpad,
425}
426
427pointer_event_struct! {
428    /// The pan/zoom on this pointer has ended.
429    pub struct PointerPanZoomEndEvent {}
430    down = false,
431    pressure = 1.0,
432    distance = 0.0,
433    buttons = 0,
434    kind = PointerDeviceKind::Trackpad,
435}
436
437impl PointerPanZoomUpdateEvent {
438    /// The [`pan`](Self::pan) transformed into the event receiver's local
439    /// coordinate system according to [`transform`](Self::transform).
440    pub fn local_pan(&self) -> Offset {
441        transform_position(self.transform, self.pan)
442    }
443
444    /// The [`pan_delta`](Self::pan_delta) transformed into the event receiver's
445    /// local coordinate system according to [`transform`](Self::transform).
446    pub fn local_pan_delta(&self) -> Offset {
447        transform_delta_via_positions(
448            self.pan,
449            Some(self.local_pan()),
450            self.pan_delta,
451            self.transform,
452        )
453    }
454}
455
456/// Runs `$body` with `$e` bound to whichever event struct the enum holds.
457macro_rules! with_variant {
458    ($event:expr, $e:ident => $body:expr) => {
459        match $event {
460            PointerEvent::Added($e) => $body,
461            PointerEvent::Removed($e) => $body,
462            PointerEvent::Hover($e) => $body,
463            PointerEvent::Enter($e) => $body,
464            PointerEvent::Exit($e) => $body,
465            PointerEvent::Down($e) => $body,
466            PointerEvent::Move($e) => $body,
467            PointerEvent::Up($e) => $body,
468            PointerEvent::Cancel($e) => $body,
469            PointerEvent::Scroll($e) => $body,
470            PointerEvent::ScrollInertiaCancel($e) => $body,
471            PointerEvent::Scale($e) => $body,
472            PointerEvent::PanZoomStart($e) => $body,
473            PointerEvent::PanZoomUpdate($e) => $body,
474            PointerEvent::PanZoomEnd($e) => $body,
475        }
476    };
477}
478
479/// Like [`with_variant!`], re-wrapping the result in the same variant.
480macro_rules! map_variant {
481    ($event:expr, $e:ident => $body:expr) => {
482        match $event {
483            PointerEvent::Added($e) => PointerEvent::Added($body),
484            PointerEvent::Removed($e) => PointerEvent::Removed($body),
485            PointerEvent::Hover($e) => PointerEvent::Hover($body),
486            PointerEvent::Enter($e) => PointerEvent::Enter($body),
487            PointerEvent::Exit($e) => PointerEvent::Exit($body),
488            PointerEvent::Down($e) => PointerEvent::Down($body),
489            PointerEvent::Move($e) => PointerEvent::Move($body),
490            PointerEvent::Up($e) => PointerEvent::Up($body),
491            PointerEvent::Cancel($e) => PointerEvent::Cancel($body),
492            PointerEvent::Scroll($e) => PointerEvent::Scroll($body),
493            PointerEvent::ScrollInertiaCancel($e) => PointerEvent::ScrollInertiaCancel($body),
494            PointerEvent::Scale($e) => PointerEvent::Scale($body),
495            PointerEvent::PanZoomStart($e) => PointerEvent::PanZoomStart($body),
496            PointerEvent::PanZoomUpdate($e) => PointerEvent::PanZoomUpdate($body),
497            PointerEvent::PanZoomEnd($e) => PointerEvent::PanZoomEnd($body),
498        }
499    };
500}
501
502/// Flutter's `PointerEnterEvent.fromMouseEvent` / `PointerExitEvent.fromMouseEvent`: the
503/// fields every event carries, copied into a new event, then transformed like the source.
504macro_rules! from_mouse_event {
505    ($target:ident, $event:expr) => {
506        with_variant!($event, e => $target {
507            view_id: e.view_id,
508            time_stamp: e.time_stamp,
509            pointer: e.pointer,
510            kind: e.kind,
511            device: e.device,
512            position: e.position,
513            delta: e.delta,
514            buttons: e.buttons,
515            obscured: e.obscured,
516            pressure_min: e.pressure_min,
517            pressure_max: e.pressure_max,
518            distance: e.distance,
519            distance_max: e.distance_max,
520            size: e.size,
521            radius_major: e.radius_major,
522            radius_minor: e.radius_minor,
523            radius_min: e.radius_min,
524            radius_max: e.radius_max,
525            orientation: e.orientation,
526            tilt: e.tilt,
527            down: e.down,
528            synthesized: e.synthesized,
529            ..$target::default()
530        })
531        .transformed($event.transform())
532    };
533}
534
535impl PointerEnterEvent {
536    /// Creates an enter event from a [`PointerEvent`].
537    ///
538    /// This is used by the `MouseTracker` to synthesize enter events.
539    pub fn from_mouse_event(event: &PointerEvent) -> PointerEnterEvent {
540        from_mouse_event!(PointerEnterEvent, event)
541    }
542}
543
544impl PointerExitEvent {
545    /// Creates an exit event from a [`PointerEvent`].
546    ///
547    /// This is used by the `MouseTracker` to synthesize exit events.
548    pub fn from_mouse_event(event: &PointerEvent) -> PointerExitEvent {
549        from_mouse_event!(PointerExitEvent, event)
550    }
551}
552
553/// Base class for touch, stylus, or mouse events.
554///
555/// Pairing enum over the public event classes. `_Transformed*` subclasses are
556/// the same variant with [`transform`](PointerAddedEvent::transform) set.
557#[derive(Clone, Debug)]
558pub enum PointerEvent {
559    /// [`PointerAddedEvent`].
560    Added(PointerAddedEvent),
561    /// [`PointerRemovedEvent`].
562    Removed(PointerRemovedEvent),
563    /// [`PointerHoverEvent`].
564    Hover(PointerHoverEvent),
565    /// [`PointerEnterEvent`].
566    Enter(PointerEnterEvent),
567    /// [`PointerExitEvent`].
568    Exit(PointerExitEvent),
569    /// [`PointerDownEvent`].
570    Down(PointerDownEvent),
571    /// [`PointerMoveEvent`].
572    Move(PointerMoveEvent),
573    /// [`PointerUpEvent`].
574    Up(PointerUpEvent),
575    /// [`PointerCancelEvent`].
576    Cancel(PointerCancelEvent),
577    /// [`PointerScrollEvent`].
578    Scroll(PointerScrollEvent),
579    /// [`PointerScrollInertiaCancelEvent`].
580    ScrollInertiaCancel(PointerScrollInertiaCancelEvent),
581    /// [`PointerScaleEvent`].
582    Scale(PointerScaleEvent),
583    /// [`PointerPanZoomStartEvent`].
584    PanZoomStart(PointerPanZoomStartEvent),
585    /// [`PointerPanZoomUpdateEvent`].
586    PanZoomUpdate(PointerPanZoomUpdateEvent),
587    /// [`PointerPanZoomEndEvent`].
588    PanZoomEnd(PointerPanZoomEndEvent),
589}
590
591impl PointerEvent {
592    /// The ID of the `FlutterView` which this event originated from.
593    pub fn view_id(&self) -> ViewId {
594        with_variant!(self, e => e.view_id)
595    }
596
597    /// Unique identifier for the pointing device, reused across interactions.
598    pub fn device(&self) -> i64 {
599        with_variant!(self, e => e.device)
600    }
601
602    /// The transformation used to transform this event from the global
603    /// coordinate space into the coordinate space of the event receiver.
604    pub fn transform(&self) -> Option<Matrix4> {
605        with_variant!(self, e => e.transform)
606    }
607
608    /// Coordinate of the position of the pointer, in logical pixels in the
609    /// global coordinate space.
610    pub fn position(&self) -> Offset {
611        with_variant!(self, e => e.position)
612    }
613
614    /// The [`position`](Self::position) transformed into the event receiver's
615    /// local coordinate system.
616    pub fn local_position(&self) -> Offset {
617        with_variant!(self, e => e.local_position())
618    }
619
620    /// The [`delta`](Self::delta) transformed into the event receiver's local
621    /// coordinate system.
622    pub fn local_delta(&self) -> Offset {
623        with_variant!(self, e => e.local_delta())
624    }
625
626    /// Distance in logical pixels that the pointer moved since the last move
627    /// or hover.
628    pub fn delta(&self) -> Offset {
629        with_variant!(self, e => e.delta)
630    }
631
632    /// Unique identifier for the pointer, not reused.
633    pub fn pointer(&self) -> i64 {
634        with_variant!(self, e => e.pointer)
635    }
636
637    /// The kind of input device for which the event was generated.
638    pub fn kind(&self) -> PointerDeviceKind {
639        with_variant!(self, e => e.kind)
640    }
641
642    /// Bit field using the `*_BUTTON` constants.
643    pub fn buttons(&self) -> i64 {
644        with_variant!(self, e => e.buttons)
645    }
646
647    /// The pressure of the touch.
648    ///
649    /// This value is a number ranging from 0.0, indicating a touch with no
650    /// discernible pressure, to 1.0, indicating a touch with "normal" pressure,
651    /// and possibly beyond, indicating a stronger touch. For devices that do not
652    /// detect pressure (e.g. mice), returns 1.0.
653    pub fn pressure(&self) -> f64 {
654        with_variant!(self, e => e.pressure)
655    }
656
657    /// The minimum value that [`pressure`](Self::pressure) can return for this
658    /// pointer.
659    ///
660    /// For devices that do not detect pressure (e.g. mice), returns 1.0. This
661    /// will always be a number less than or equal to 1.0.
662    pub fn pressure_min(&self) -> f64 {
663        with_variant!(self, e => e.pressure_min)
664    }
665
666    /// The maximum value that [`pressure`](Self::pressure) can return for this
667    /// pointer.
668    ///
669    /// For devices that do not detect pressure (e.g. mice), returns 1.0. This
670    /// will always be a greater than or equal to 1.0.
671    pub fn pressure_max(&self) -> f64 {
672        with_variant!(self, e => e.pressure_max)
673    }
674
675    /// Time of event dispatch, relative to an arbitrary timeline.
676    pub fn time_stamp(&self) -> Duration {
677        with_variant!(self, e => e.time_stamp)
678    }
679
680    /// Set if the event was synthesized.
681    pub fn synthesized(&self) -> bool {
682        with_variant!(self, e => e.synthesized)
683    }
684
685    /// Set if the pointer is currently down.
686    pub fn down(&self) -> bool {
687        with_variant!(self, e => e.down)
688    }
689
690    /// Transforms the event from the global coordinate space into the
691    /// coordinate space of an event receiver.
692    pub fn transformed(&self, transform: Option<Matrix4>) -> PointerEvent {
693        map_variant!(self, e => e.transformed(transform))
694    }
695}
696
697/// Returns the transformation of `position` into the coordinate system
698/// described by `transform`.
699///
700/// The z-value of `position` is assumed to be 0.0. If `transform` is None,
701/// `position` is returned as-is.
702pub fn transform_position(transform: Option<Matrix4>, position: Offset) -> Offset {
703    match transform {
704        None => position,
705        Some(transform) => Offset::from(transform.map_point(position.into())),
706    }
707}
708
709/// Transforms `untransformed_delta` into the coordinate system described by
710/// `transform`.
711pub fn transform_delta_via_positions(
712    untransformed_end_position: Offset,
713    transformed_end_position: Option<Offset>,
714    untransformed_delta: Offset,
715    transform: Option<Matrix4>,
716) -> Offset {
717    if transform.is_none() {
718        return untransformed_delta;
719    }
720    let transformed_end_position = transformed_end_position
721        .unwrap_or_else(|| transform_position(transform, untransformed_end_position));
722    let transformed_start_position =
723        transform_position(transform, untransformed_end_position - untransformed_delta);
724    transformed_end_position - transformed_start_position
725}
726
727/// Removes the "perspective" component from `transform`.
728///
729/// When applying the resulting transform matrix to a point with a
730/// z-coordinate of zero (which is generally assumed for all points
731/// represented by an [`Offset`]), the other coordinates will get transformed as
732/// before, but the new z-coordinate is going to be zero again. This is
733/// achieved by setting the third column and third row of the matrix to
734/// "0, 0, 1, 0".
735pub fn remove_perspective_transform(transform: Matrix4) -> Matrix4 {
736    let vector = [0.0, 0.0, 1.0, 0.0];
737    let mut storage = transform.to_flutter_array();
738    // `setColumn(2, vector)`
739    storage[8..12].copy_from_slice(&vector);
740    // `setRow(2, vector)`
741    for (column, value) in vector.into_iter().enumerate() {
742        storage[column * 4 + 2] = value;
743    }
744    Matrix4::from_flutter_array(&storage)
745}
746
747/// Determine the appropriate hit slop pixels based on the `kind` of pointer.
748pub fn compute_hit_slop(kind: PointerDeviceKind, settings: Option<DeviceGestureSettings>) -> f64 {
749    match kind {
750        PointerDeviceKind::Mouse => K_PRECISE_POINTER_HIT_SLOP,
751        PointerDeviceKind::Stylus
752        | PointerDeviceKind::InvertedStylus
753        | PointerDeviceKind::Unknown
754        | PointerDeviceKind::Touch
755        | PointerDeviceKind::Trackpad => settings
756            .and_then(|settings| settings.touch_slop)
757            .unwrap_or(K_TOUCH_SLOP),
758    }
759}
760
761/// Determine the appropriate pan slop pixels based on the `kind` of pointer.
762pub fn compute_pan_slop(kind: PointerDeviceKind, settings: Option<DeviceGestureSettings>) -> f64 {
763    match kind {
764        PointerDeviceKind::Mouse => K_PRECISE_POINTER_PAN_SLOP,
765        PointerDeviceKind::Stylus
766        | PointerDeviceKind::InvertedStylus
767        | PointerDeviceKind::Unknown
768        | PointerDeviceKind::Touch
769        | PointerDeviceKind::Trackpad => settings
770            .and_then(|settings| settings.pan_slop())
771            .unwrap_or(K_PAN_SLOP),
772    }
773}
774
775/// Determine the appropriate scale slop pixels based on the `kind` of pointer.
776pub fn compute_scale_slop(kind: PointerDeviceKind) -> f64 {
777    match kind {
778        PointerDeviceKind::Mouse => K_PRECISE_POINTER_SCALE_SLOP,
779        PointerDeviceKind::Stylus
780        | PointerDeviceKind::InvertedStylus
781        | PointerDeviceKind::Unknown
782        | PointerDeviceKind::Touch
783        | PointerDeviceKind::Trackpad => K_SCALE_SLOP,
784    }
785}
786
787/// Signature for listening to [`PointerDownEvent`] events.
788pub type PointerDownEventListener = ValueChanged<PointerDownEvent>;
789
790/// Signature for listening to [`PointerMoveEvent`] events.
791pub type PointerMoveEventListener = ValueChanged<PointerMoveEvent>;
792
793/// Signature for listening to [`PointerUpEvent`] events.
794pub type PointerUpEventListener = ValueChanged<PointerUpEvent>;
795
796/// Signature for listening to [`PointerHoverEvent`] events.
797pub type PointerHoverEventListener = ValueChanged<PointerHoverEvent>;
798
799/// Signature for listening to [`PointerEnterEvent`] events.
800pub type PointerEnterEventListener = ValueChanged<PointerEnterEvent>;
801
802/// Signature for listening to [`PointerExitEvent`] events.
803pub type PointerExitEventListener = ValueChanged<PointerExitEvent>;
804
805/// Signature for listening to [`PointerCancelEvent`] events.
806pub type PointerCancelEventListener = ValueChanged<PointerCancelEvent>;
807
808/// Signature for listening to [`PointerPanZoomStartEvent`] events.
809pub type PointerPanZoomStartEventListener = ValueChanged<PointerPanZoomStartEvent>;
810
811/// Signature for listening to [`PointerPanZoomUpdateEvent`] events.
812pub type PointerPanZoomUpdateEventListener = ValueChanged<PointerPanZoomUpdateEvent>;
813
814/// Signature for listening to [`PointerPanZoomEndEvent`] events.
815pub type PointerPanZoomEndEventListener = ValueChanged<PointerPanZoomEndEvent>;
816
817/// Signature for listening to pointer signal events: [`PointerEvent::Scroll`],
818/// [`PointerEvent::ScrollInertiaCancel`], and [`PointerEvent::Scale`].
819pub type PointerSignalEventListener = ValueChanged<PointerEvent>;
820
821#[cfg(test)]
822mod tests {
823    use super::*;
824
825    #[test]
826    fn smallest_button_picks_the_least_significant_set_bit() {
827        assert_eq!(smallest_button(0x01), 0x01);
828        assert_eq!(smallest_button(0x11), 0x01);
829        assert_eq!(smallest_button(0x10), 0x10);
830        assert_eq!(smallest_button(0), 0);
831    }
832
833    #[test]
834    fn is_single_button_rejects_zero_and_multi() {
835        assert!(is_single_button(0x1));
836        assert!(!is_single_button(0x11));
837        assert!(!is_single_button(0));
838    }
839
840    #[test]
841    fn transformed_down_keeps_global_position() {
842        let event = PointerDownEvent {
843            position: Offset::new(10.0, 20.0),
844            ..PointerDownEvent::default()
845        };
846        let transformed = event.transformed(Some(Matrix4::translation(5.0, 7.0)));
847        assert_eq!(transformed.position, Offset::new(10.0, 20.0));
848        assert_eq!(transformed.local_position(), Offset::new(15.0, 27.0));
849        assert!(transformed.original.is_some());
850    }
851
852    /// `events_test.dart`: `paintTransformToPointerEventTransform`.
853    #[test]
854    fn paint_transform_to_pointer_event_transform() {
855        let original = Matrix4::IDENTITY;
856        let changed = remove_perspective_transform(original);
857        assert_eq!(changed, original);
858
859        // `Matrix4.identity()..scale(3.0)`, which scales z as well.
860        let mut storage = Matrix4::IDENTITY.to_flutter_array();
861        storage[0] = 3.0;
862        storage[5] = 3.0;
863        storage[10] = 3.0;
864        let original = Matrix4::from_flutter_array(&storage);
865        let changed = remove_perspective_transform(original);
866        assert_ne!(changed, original);
867        // `..setColumn(2, Vector4(0, 0, 1, 0))..setRow(2, Vector4(0, 0, 1, 0))`
868        storage[8..12].copy_from_slice(&[0.0, 0.0, 1.0, 0.0]);
869        storage[2] = 0.0;
870        storage[6] = 0.0;
871        storage[10] = 1.0;
872        storage[14] = 0.0;
873        assert_eq!(changed, Matrix4::from_flutter_array(&storage));
874    }
875}