Skip to main content

waft_widgets/widgets/
gesture_detector.rs

1//! Flutter counterpart: `widgets/gesture_detector.dart`.
2//!
3//! The recognizer factories, [`RawGestureDetector`] with its state, and [`GestureDetector`]
4//! over the recognizers ported so far (tap, double tap, long press, vertical and horizontal
5//! drag, pan, scale). The semantics half
6//! (`excludeFromSemantics`, `semantics`, `SemanticsGestureDelegate`, `_GestureSemantics`) is
7//! accessibility and waits.
8
9use std::any::{TypeId, type_name};
10use std::collections::HashSet;
11use std::fmt::{self, Debug};
12use std::marker::PhantomData;
13use std::rc::Rc;
14
15use waft_embedder::{Offset, PointerDeviceKind};
16use waft_foundation::{
17    App, DiagnosticLevel, DiagnosticPropertiesBuilder, EnumProperty, Handle, IterableProperty, Ref,
18};
19use waft_gestures::{
20    AnyGestureRecognizer, DeviceGestureSettings, DoubleTapGestureRecognizer, DragGestureRecognizer,
21    DragStartBehavior, GestureDoubleTapCallback, GestureDragCancelCallback,
22    GestureDragDownCallback, GestureDragEndCallback, GestureDragStartCallback,
23    GestureDragUpdateCallback, GestureLongPressCallback, GestureLongPressCancelCallback,
24    GestureLongPressDownCallback, GestureLongPressEndCallback, GestureLongPressMoveUpdateCallback,
25    GestureLongPressStartCallback, GestureLongPressUpCallback, GestureRecognizerLeaf,
26    GestureScaleEndCallback, GestureScaleStartCallback, GestureScaleUpdateCallback,
27    GestureTapCallback, GestureTapCancelCallback, GestureTapDownCallback, GestureTapMoveCallback,
28    GestureTapUpCallback, HorizontalDragGestureRecognizer,
29    K_DEFAULT_TRACKPAD_SCROLL_TO_SCALE_FACTOR, LongPressGestureRecognizer, MultitouchDragStrategy,
30    PanGestureRecognizer, PointerDownEvent, PointerPanZoomStartEvent, RecognizerRef,
31    ScaleGestureRecognizer, TapGestureRecognizer, VerticalDragGestureRecognizer,
32};
33use waft_rendering::HitTestBehavior;
34
35use crate::framework::{
36    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, StatelessWidget, WidgetRef,
37};
38use crate::widgets::basic::Listener;
39use crate::widgets::media_query::MediaQuery;
40use crate::widgets::scroll_configuration::ScrollConfiguration;
41
42/// Factory for creating gesture recognizers.
43///
44/// `T` is the type of gesture recognizer this class manages.
45///
46/// Used by [`RawGestureDetector::gestures`].
47pub trait GestureRecognizerFactory<T: GestureRecognizerLeaf>: 'static {
48    /// Must return an instance of T.
49    fn constructor(&self, app: &mut App) -> Ref<T>;
50
51    /// Must configure the given instance (which will have been created by
52    /// [`constructor`](Self::constructor)).
53    ///
54    /// This normally means setting the callbacks.
55    fn initializer(&self, app: &mut App, instance: Handle<T>);
56
57    /// This factory as Dart's raw `GestureRecognizerFactory`: erased over `T`, the value of
58    /// [`RawGestureDetector::gestures`].
59    fn into_factory(self) -> GestureRecognizerFactoryRef
60    where
61        Self: Sized,
62    {
63        Rc::new(TypedGestureRecognizerFactory {
64            factory: self,
65            recognizer: PhantomData,
66        })
67    }
68}
69
70/// Signature for closures that implement [`GestureRecognizerFactory::constructor`].
71pub type GestureRecognizerFactoryConstructor<T> = Rc<dyn Fn(&mut App) -> Ref<T>>;
72
73/// Signature for closures that implement [`GestureRecognizerFactory::initializer`].
74pub type GestureRecognizerFactoryInitializer<T> = Rc<dyn Fn(&mut App, Handle<T>)>;
75
76/// Factory for creating gesture recognizers that delegates to callbacks.
77///
78/// Used by [`RawGestureDetector::gestures`].
79pub struct GestureRecognizerFactoryWithHandlers<T> {
80    constructor: GestureRecognizerFactoryConstructor<T>,
81    initializer: GestureRecognizerFactoryInitializer<T>,
82}
83
84impl<T: GestureRecognizerLeaf> GestureRecognizerFactoryWithHandlers<T> {
85    /// Creates a gesture recognizer factory with the given callbacks.
86    pub fn new(
87        constructor: impl Fn(&mut App) -> Ref<T> + 'static,
88        initializer: impl Fn(&mut App, Handle<T>) + 'static,
89    ) -> GestureRecognizerFactoryWithHandlers<T> {
90        GestureRecognizerFactoryWithHandlers {
91            constructor: Rc::new(constructor),
92            initializer: Rc::new(initializer),
93        }
94    }
95}
96
97impl<T: GestureRecognizerLeaf> GestureRecognizerFactory<T>
98    for GestureRecognizerFactoryWithHandlers<T>
99{
100    fn constructor(&self, app: &mut App) -> Ref<T> {
101        (self.constructor)(app)
102    }
103
104    fn initializer(&self, app: &mut App, instance: Handle<T>) {
105        (self.initializer)(app, instance)
106    }
107}
108
109/// A [`GestureRecognizerFactory`] erased over its recognizer type: Dart's raw
110/// `GestureRecognizerFactory`, the value of [`RawGestureDetector::gestures`]. Get one with
111/// [`GestureRecognizerFactory::into_factory`].
112pub trait AnyGestureRecognizerFactory: Debug {
113    /// Dart's `_debugAssertTypeMatches`: whether `type_id` is the recognizer type this
114    /// factory manages.
115    fn debug_assert_type_matches(&self, type_id: TypeId) -> bool;
116
117    /// See [`GestureRecognizerFactory::constructor`].
118    fn constructor(&self, app: &mut App) -> RecognizerRef;
119
120    /// See [`GestureRecognizerFactory::initializer`].
121    fn initializer(&self, app: &mut App, instance: AnyGestureRecognizer);
122}
123
124/// A shared [`AnyGestureRecognizerFactory`].
125pub type GestureRecognizerFactoryRef = Rc<dyn AnyGestureRecognizerFactory>;
126
127/// Dart's `Map<Type, GestureRecognizerFactory>`: the factories in insertion order, each
128/// under the `TypeId` of the recognizer it creates
129/// (`TypeId::of::<TapGestureRecognizer>()`).
130pub type GestureRecognizerFactories = Vec<(TypeId, GestureRecognizerFactoryRef)>;
131
132/// The typed factory behind a [`GestureRecognizerFactoryRef`].
133struct TypedGestureRecognizerFactory<T, F> {
134    factory: F,
135    recognizer: PhantomData<fn() -> T>,
136}
137
138impl<T: GestureRecognizerLeaf, F: GestureRecognizerFactory<T>> AnyGestureRecognizerFactory
139    for TypedGestureRecognizerFactory<T, F>
140{
141    fn debug_assert_type_matches(&self, type_id: TypeId) -> bool {
142        debug_assert!(
143            type_id == TypeId::of::<T>(),
144            "GestureRecognizerFactory of type {} was used where type {type_id:?} was specified.",
145            type_name::<T>()
146        );
147        true
148    }
149
150    fn constructor(&self, app: &mut App) -> RecognizerRef {
151        self.factory.constructor(app).into_erased()
152    }
153
154    fn initializer(&self, app: &mut App, instance: AnyGestureRecognizer) {
155        let instance = instance
156            .downcast::<T>(app)
157            .expect("a factory initializes the recognizer type it constructed");
158        self.factory.initializer(app, instance);
159    }
160}
161
162impl<T, F> Debug for TypedGestureRecognizerFactory<T, F> {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        write!(f, "GestureRecognizerFactory<{}>", type_name::<T>())
165    }
166}
167
168/// A widget that detects gestures.
169///
170/// Attempts to recognize gestures that correspond to its non-null callbacks.
171///
172/// If this widget has a child, it defers to that child for its sizing behavior.
173/// If it does not have a child, it grows to fit the parent instead.
174///
175/// By default a GestureDetector with an invisible child ignores touches;
176/// this behavior can be controlled with [`behavior`](Self::behavior).
177///
178/// See <http://flutter.dev/to/gestures> for additional information.
179///
180/// ### Troubleshooting
181///
182/// Why isn't my parent [`GestureDetector::on_tap`] method called?
183///
184/// Given a parent [`GestureDetector`] with an onTap callback, and a child
185/// GestureDetector that also defines an onTap callback, when the inner
186/// GestureDetector is tapped, both GestureDetectors send a `GestureRecognizer`
187/// into the gesture arena. This is because the pointer coordinates are within the
188/// bounds of both GestureDetectors. The child GestureDetector wins in this
189/// scenario because it was the first to enter the arena, resolving as first come,
190/// first served. The child onTap is called, and the parent's is not as the gesture has
191/// been consumed.
192/// For more information on gesture disambiguation see:
193/// [Gesture disambiguation](https://flutter.dev/to/gesture-disambiguation).
194///
195/// Setting [`GestureDetector::behavior`] to [`HitTestBehavior::Opaque`]
196/// or [`HitTestBehavior::Translucent`] has no impact on parent-child relationships:
197/// both GestureDetectors send a GestureRecognizer into the gesture arena, only one wins.
198///
199/// Some callbacks (e.g. onTapDown) can fire before a recognizer wins the arena,
200/// and others (e.g. onTapCancel) fire even when it loses the arena. Therefore,
201/// the parent detector in the example above may call some of its callbacks even
202/// though it loses in the arena.
203///
204/// ## Debugging
205///
206/// To see how large the hit test box of a [`GestureDetector`] is for debugging
207/// purposes, set `debugPaintPointersEnabled` to true.
208///
209/// See also:
210///
211///  * `Listener`, a widget for listening to lower-level raw pointer events.
212///  * `MouseRegion`, a widget that tracks the movement of mice, even when no
213///    button is pressed.
214///  * [`RawGestureDetector`], a widget that is used to detect custom gestures.
215#[derive(Clone)]
216pub struct GestureDetector {
217    pub key: Option<KeyRef>,
218
219    /// The widget below this widget in the tree.
220    pub child: Option<WidgetRef>,
221
222    /// A pointer that might cause a tap with a primary button has contacted the
223    /// screen at a particular location.
224    ///
225    /// This is called after a short timeout, even if the winning gesture has not
226    /// yet been selected. If the tap gesture wins, [`on_tap_up`](Self::on_tap_up) will be
227    /// called, otherwise [`on_tap_cancel`](Self::on_tap_cancel) will be called.
228    ///
229    /// See also:
230    ///
231    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
232    pub on_tap_down: Option<GestureTapDownCallback>,
233
234    /// A pointer that will trigger a tap with a primary button has stopped
235    /// contacting the screen at a particular location.
236    ///
237    /// This triggers immediately before [`on_tap`](Self::on_tap) in the case of the tap
238    /// gesture winning. If the tap gesture did not win,
239    /// [`on_tap_cancel`](Self::on_tap_cancel) is called instead.
240    ///
241    /// See also:
242    ///
243    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
244    pub on_tap_up: Option<GestureTapUpCallback>,
245
246    /// A tap with a primary button has occurred.
247    ///
248    /// This triggers when the tap gesture wins. If the tap gesture did not win,
249    /// [`on_tap_cancel`](Self::on_tap_cancel) is called instead.
250    ///
251    /// See also:
252    ///
253    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
254    ///  * [`on_tap_up`](Self::on_tap_up), which is called at the same time but includes
255    ///    details regarding the pointer position.
256    pub on_tap: Option<GestureTapCallback>,
257
258    /// A pointer that triggered a tap has moved.
259    ///
260    /// This triggers when the pointer moves after the tap gesture has been recognized.
261    ///
262    /// See also:
263    ///
264    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
265    pub on_tap_move: Option<GestureTapMoveCallback>,
266
267    /// The pointer that previously triggered [`on_tap_down`](Self::on_tap_down) will not
268    /// end up causing a tap.
269    ///
270    /// This is called after [`on_tap_down`](Self::on_tap_down), and instead of
271    /// [`on_tap_up`](Self::on_tap_up) and [`on_tap`](Self::on_tap), if the tap gesture did
272    /// not win.
273    ///
274    /// See also:
275    ///
276    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
277    pub on_tap_cancel: Option<GestureTapCancelCallback>,
278
279    /// A tap with a secondary button has occurred.
280    ///
281    /// This triggers when the tap gesture wins. If the tap gesture did not win,
282    /// [`on_secondary_tap_cancel`](Self::on_secondary_tap_cancel) is called instead.
283    ///
284    /// See also:
285    ///
286    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
287    ///  * [`on_secondary_tap_up`](Self::on_secondary_tap_up), which is called at the same
288    ///    time but includes details regarding the pointer position.
289    pub on_secondary_tap: Option<GestureTapCallback>,
290
291    /// A pointer that might cause a tap with a secondary button has contacted the
292    /// screen at a particular location.
293    ///
294    /// This is called after a short timeout, even if the winning gesture has not
295    /// yet been selected. If the tap gesture wins,
296    /// [`on_secondary_tap_up`](Self::on_secondary_tap_up) will be called, otherwise
297    /// [`on_secondary_tap_cancel`](Self::on_secondary_tap_cancel) will be called.
298    ///
299    /// See also:
300    ///
301    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
302    pub on_secondary_tap_down: Option<GestureTapDownCallback>,
303
304    /// A pointer that will trigger a tap with a secondary button has stopped
305    /// contacting the screen at a particular location.
306    ///
307    /// This triggers in the case of the tap gesture winning. If the tap gesture
308    /// did not win, [`on_secondary_tap_cancel`](Self::on_secondary_tap_cancel) is called
309    /// instead.
310    ///
311    /// See also:
312    ///
313    ///  * [`on_secondary_tap`](Self::on_secondary_tap), a handler triggered right after
314    ///    this one that doesn't pass any details about the tap.
315    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
316    pub on_secondary_tap_up: Option<GestureTapUpCallback>,
317
318    /// The pointer that previously triggered
319    /// [`on_secondary_tap_down`](Self::on_secondary_tap_down) will not end up causing a
320    /// tap.
321    ///
322    /// This is called after [`on_secondary_tap_down`](Self::on_secondary_tap_down), and
323    /// instead of [`on_secondary_tap_up`](Self::on_secondary_tap_up), if the tap gesture
324    /// did not win.
325    ///
326    /// See also:
327    ///
328    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
329    pub on_secondary_tap_cancel: Option<GestureTapCancelCallback>,
330
331    /// A pointer that might cause a tap with a tertiary button has contacted the
332    /// screen at a particular location.
333    ///
334    /// This is called after a short timeout, even if the winning gesture has not
335    /// yet been selected. If the tap gesture wins,
336    /// [`on_tertiary_tap_up`](Self::on_tertiary_tap_up) will be called, otherwise
337    /// [`on_tertiary_tap_cancel`](Self::on_tertiary_tap_cancel) will be called.
338    ///
339    /// See also:
340    ///
341    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
342    pub on_tertiary_tap_down: Option<GestureTapDownCallback>,
343
344    /// A pointer that will trigger a tap with a tertiary button has stopped
345    /// contacting the screen at a particular location.
346    ///
347    /// This triggers in the case of the tap gesture winning. If the tap gesture
348    /// did not win, [`on_tertiary_tap_cancel`](Self::on_tertiary_tap_cancel) is called
349    /// instead.
350    ///
351    /// See also:
352    ///
353    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
354    pub on_tertiary_tap_up: Option<GestureTapUpCallback>,
355
356    /// The pointer that previously triggered
357    /// [`on_tertiary_tap_down`](Self::on_tertiary_tap_down) will not end up causing a tap.
358    ///
359    /// This is called after [`on_tertiary_tap_down`](Self::on_tertiary_tap_down), and
360    /// instead of [`on_tertiary_tap_up`](Self::on_tertiary_tap_up), if the tap gesture did
361    /// not win.
362    ///
363    /// See also:
364    ///
365    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
366    pub on_tertiary_tap_cancel: Option<GestureTapCancelCallback>,
367
368    /// A pointer that might cause a double tap has contacted the screen at a
369    /// particular location.
370    ///
371    /// Triggered immediately after the down event of the second tap.
372    ///
373    /// If the user completes the double tap and the gesture wins,
374    /// [`on_double_tap`](Self::on_double_tap) will be called after this callback. Otherwise,
375    /// [`on_double_tap_cancel`](Self::on_double_tap_cancel) will be called after this
376    /// callback.
377    ///
378    /// See also:
379    ///
380    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
381    pub on_double_tap_down: Option<GestureTapDownCallback>,
382
383    /// The user has tapped the screen with a primary button at the same location
384    /// twice in quick succession.
385    ///
386    /// See also:
387    ///
388    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
389    pub on_double_tap: Option<GestureDoubleTapCallback>,
390
391    /// The pointer that previously triggered
392    /// [`on_double_tap_down`](Self::on_double_tap_down) will not end up causing a double
393    /// tap.
394    ///
395    /// See also:
396    ///
397    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
398    pub on_double_tap_cancel: Option<GestureTapCancelCallback>,
399
400    /// The pointer has contacted the screen with a primary button, which might
401    /// be the start of a long-press.
402    ///
403    /// This triggers after the pointer down event.
404    ///
405    /// If the user completes the long-press, and this gesture wins,
406    /// [`on_long_press_start`](Self::on_long_press_start) will be called after this
407    /// callback. Otherwise, [`on_long_press_cancel`](Self::on_long_press_cancel) will be
408    /// called after this callback.
409    ///
410    /// See also:
411    ///
412    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
413    ///  * [`on_secondary_long_press_down`](Self::on_secondary_long_press_down), a similar
414    ///    callback but for a secondary button.
415    ///  * [`on_tertiary_long_press_down`](Self::on_tertiary_long_press_down), a similar
416    ///    callback but for a tertiary button.
417    ///  * [`LongPressGestureRecognizer::set_on_long_press_down`], which exposes this
418    ///    callback at the gesture layer.
419    pub on_long_press_down: Option<GestureLongPressDownCallback>,
420
421    /// A pointer that previously triggered [`on_long_press_down`](Self::on_long_press_down)
422    /// will not end up causing a long-press.
423    ///
424    /// This triggers once the gesture loses if
425    /// [`on_long_press_down`](Self::on_long_press_down) has previously been triggered.
426    ///
427    /// If the user completed the long-press, and the gesture won, then
428    /// [`on_long_press_start`](Self::on_long_press_start) and
429    /// [`on_long_press`](Self::on_long_press) are called instead.
430    ///
431    /// See also:
432    ///
433    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
434    ///  * [`LongPressGestureRecognizer::set_on_long_press_cancel`], which exposes this
435    ///    callback at the gesture layer.
436    pub on_long_press_cancel: Option<GestureLongPressCancelCallback>,
437
438    /// Called when a long press gesture with a primary button has been recognized.
439    ///
440    /// Triggered when a pointer has remained in contact with the screen at the
441    /// same location for a long period of time.
442    ///
443    /// This is equivalent to (and is called immediately after)
444    /// [`on_long_press_start`](Self::on_long_press_start). The only difference between the
445    /// two is that this callback does not contain details of the position at which the
446    /// pointer initially contacted the screen.
447    ///
448    /// See also:
449    ///
450    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
451    ///  * [`LongPressGestureRecognizer::set_on_long_press`], which exposes this
452    ///    callback at the gesture layer.
453    pub on_long_press: Option<GestureLongPressCallback>,
454
455    /// Called when a long press gesture with a primary button has been recognized.
456    ///
457    /// Triggered when a pointer has remained in contact with the screen at the
458    /// same location for a long period of time.
459    ///
460    /// This is equivalent to (and is called immediately before)
461    /// [`on_long_press`](Self::on_long_press). The only difference between the two is that
462    /// this callback contains details of the position at which the pointer initially
463    /// contacted the screen, whereas [`on_long_press`](Self::on_long_press) does not.
464    ///
465    /// See also:
466    ///
467    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
468    ///  * [`LongPressGestureRecognizer::set_on_long_press_start`], which exposes this
469    ///    callback at the gesture layer.
470    pub on_long_press_start: Option<GestureLongPressStartCallback>,
471
472    /// A pointer has been drag-moved after a long-press with a primary button.
473    ///
474    /// See also:
475    ///
476    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
477    ///  * [`LongPressGestureRecognizer::set_on_long_press_move_update`], which exposes this
478    ///    callback at the gesture layer.
479    pub on_long_press_move_update: Option<GestureLongPressMoveUpdateCallback>,
480
481    /// A pointer that has triggered a long-press with a primary button has
482    /// stopped contacting the screen.
483    ///
484    /// This is equivalent to (and is called immediately after)
485    /// [`on_long_press_end`](Self::on_long_press_end). The only difference between the two
486    /// is that this callback does not contain details of the state of the pointer when it
487    /// stopped contacting the screen.
488    ///
489    /// See also:
490    ///
491    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
492    ///  * [`LongPressGestureRecognizer::set_on_long_press_up`], which exposes this
493    ///    callback at the gesture layer.
494    pub on_long_press_up: Option<GestureLongPressUpCallback>,
495
496    /// A pointer that has triggered a long-press with a primary button has
497    /// stopped contacting the screen.
498    ///
499    /// This is equivalent to (and is called immediately before)
500    /// [`on_long_press_up`](Self::on_long_press_up). The only difference between the two is
501    /// that this callback contains details of the state of the pointer when it stopped
502    /// contacting the screen, whereas [`on_long_press_up`](Self::on_long_press_up) does not.
503    ///
504    /// See also:
505    ///
506    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
507    ///  * [`LongPressGestureRecognizer::set_on_long_press_end`], which exposes this
508    ///    callback at the gesture layer.
509    pub on_long_press_end: Option<GestureLongPressEndCallback>,
510
511    /// The pointer has contacted the screen with a secondary button, which might
512    /// be the start of a long-press.
513    ///
514    /// This triggers after the pointer down event.
515    ///
516    /// If the user completes the long-press, and this gesture wins,
517    /// [`on_secondary_long_press_start`](Self::on_secondary_long_press_start) will be called
518    /// after this callback. Otherwise,
519    /// [`on_secondary_long_press_cancel`](Self::on_secondary_long_press_cancel) will be
520    /// called after this callback.
521    ///
522    /// See also:
523    ///
524    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
525    ///  * [`on_long_press_down`](Self::on_long_press_down), a similar callback but for a
526    ///    secondary button.
527    ///  * [`on_tertiary_long_press_down`](Self::on_tertiary_long_press_down), a similar
528    ///    callback but for a tertiary button.
529    ///  * [`LongPressGestureRecognizer::set_on_secondary_long_press_down`], which exposes
530    ///    this callback at the gesture layer.
531    pub on_secondary_long_press_down: Option<GestureLongPressDownCallback>,
532
533    /// A pointer that previously triggered
534    /// [`on_secondary_long_press_down`](Self::on_secondary_long_press_down) will not end up
535    /// causing a long-press.
536    ///
537    /// This triggers once the gesture loses if
538    /// [`on_secondary_long_press_down`](Self::on_secondary_long_press_down) has previously
539    /// been triggered.
540    ///
541    /// If the user completed the long-press, and the gesture won, then
542    /// [`on_secondary_long_press_start`](Self::on_secondary_long_press_start) and
543    /// [`on_secondary_long_press`](Self::on_secondary_long_press) are called instead.
544    ///
545    /// See also:
546    ///
547    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
548    ///  * [`LongPressGestureRecognizer::set_on_secondary_long_press_cancel`], which exposes
549    ///    this callback at the gesture layer.
550    pub on_secondary_long_press_cancel: Option<GestureLongPressCancelCallback>,
551
552    /// Called when a long press gesture with a secondary button has been
553    /// recognized.
554    ///
555    /// Triggered when a pointer has remained in contact with the screen at the
556    /// same location for a long period of time.
557    ///
558    /// This is equivalent to (and is called immediately after)
559    /// [`on_secondary_long_press_start`](Self::on_secondary_long_press_start). The only
560    /// difference between the two is that this callback does not contain details of the
561    /// position at which the pointer initially contacted the screen.
562    ///
563    /// See also:
564    ///
565    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
566    ///  * [`LongPressGestureRecognizer::set_on_secondary_long_press`], which exposes
567    ///    this callback at the gesture layer.
568    pub on_secondary_long_press: Option<GestureLongPressCallback>,
569
570    /// Called when a long press gesture with a secondary button has been
571    /// recognized.
572    ///
573    /// Triggered when a pointer has remained in contact with the screen at the
574    /// same location for a long period of time.
575    ///
576    /// This is equivalent to (and is called immediately before)
577    /// [`on_secondary_long_press`](Self::on_secondary_long_press). The only difference
578    /// between the two is that this callback contains details of the position at which the
579    /// pointer initially contacted the screen, whereas
580    /// [`on_secondary_long_press`](Self::on_secondary_long_press) does not.
581    ///
582    /// See also:
583    ///
584    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
585    ///  * [`LongPressGestureRecognizer::set_on_secondary_long_press_start`], which exposes
586    ///    this callback at the gesture layer.
587    pub on_secondary_long_press_start: Option<GestureLongPressStartCallback>,
588
589    /// A pointer has been drag-moved after a long press with a secondary button.
590    ///
591    /// See also:
592    ///
593    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
594    ///  * [`LongPressGestureRecognizer::set_on_secondary_long_press_move_update`], which
595    ///    exposes this callback at the gesture layer.
596    pub on_secondary_long_press_move_update: Option<GestureLongPressMoveUpdateCallback>,
597
598    /// A pointer that has triggered a long-press with a secondary button has
599    /// stopped contacting the screen.
600    ///
601    /// This is equivalent to (and is called immediately after)
602    /// [`on_secondary_long_press_end`](Self::on_secondary_long_press_end). The only
603    /// difference between the two is that this callback does not contain details of the
604    /// state of the pointer when it stopped contacting the screen.
605    ///
606    /// See also:
607    ///
608    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
609    ///  * [`LongPressGestureRecognizer::set_on_secondary_long_press_up`], which exposes
610    ///    this callback at the gesture layer.
611    pub on_secondary_long_press_up: Option<GestureLongPressUpCallback>,
612
613    /// A pointer that has triggered a long-press with a secondary button has
614    /// stopped contacting the screen.
615    ///
616    /// This is equivalent to (and is called immediately before)
617    /// [`on_secondary_long_press_up`](Self::on_secondary_long_press_up). The only difference
618    /// between the two is that this callback contains details of the state of the pointer
619    /// when it stopped contacting the screen, whereas
620    /// [`on_secondary_long_press_up`](Self::on_secondary_long_press_up) does not.
621    ///
622    /// See also:
623    ///
624    ///  * `K_SECONDARY_BUTTON`, the button this callback responds to.
625    ///  * [`LongPressGestureRecognizer::set_on_secondary_long_press_end`], which exposes
626    ///    this callback at the gesture layer.
627    pub on_secondary_long_press_end: Option<GestureLongPressEndCallback>,
628
629    /// The pointer has contacted the screen with a tertiary button, which might
630    /// be the start of a long-press.
631    ///
632    /// This triggers after the pointer down event.
633    ///
634    /// If the user completes the long-press, and this gesture wins,
635    /// [`on_tertiary_long_press_start`](Self::on_tertiary_long_press_start) will be called
636    /// after this callback. Otherwise,
637    /// [`on_tertiary_long_press_cancel`](Self::on_tertiary_long_press_cancel) will be called
638    /// after this callback.
639    ///
640    /// See also:
641    ///
642    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
643    ///  * [`on_long_press_down`](Self::on_long_press_down), a similar callback but for a
644    ///    primary button.
645    ///  * [`on_secondary_long_press_down`](Self::on_secondary_long_press_down), a similar
646    ///    callback but for a secondary button.
647    ///  * [`LongPressGestureRecognizer::set_on_tertiary_long_press_down`], which exposes
648    ///    this callback at the gesture layer.
649    pub on_tertiary_long_press_down: Option<GestureLongPressDownCallback>,
650
651    /// A pointer that previously triggered
652    /// [`on_tertiary_long_press_down`](Self::on_tertiary_long_press_down) will not end up
653    /// causing a long-press.
654    ///
655    /// This triggers once the gesture loses if
656    /// [`on_tertiary_long_press_down`](Self::on_tertiary_long_press_down) has previously
657    /// been triggered.
658    ///
659    /// If the user completed the long-press, and the gesture won, then
660    /// [`on_tertiary_long_press_start`](Self::on_tertiary_long_press_start) and
661    /// [`on_tertiary_long_press`](Self::on_tertiary_long_press) are called instead.
662    ///
663    /// See also:
664    ///
665    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
666    ///  * [`LongPressGestureRecognizer::set_on_tertiary_long_press_cancel`], which exposes
667    ///    this callback at the gesture layer.
668    pub on_tertiary_long_press_cancel: Option<GestureLongPressCancelCallback>,
669
670    /// Called when a long press gesture with a tertiary button has been
671    /// recognized.
672    ///
673    /// Triggered when a pointer has remained in contact with the screen at the
674    /// same location for a long period of time.
675    ///
676    /// This is equivalent to (and is called immediately after)
677    /// [`on_tertiary_long_press_start`](Self::on_tertiary_long_press_start). The only
678    /// difference between the two is that this callback does not contain details of the
679    /// position at which the pointer initially contacted the screen.
680    ///
681    /// See also:
682    ///
683    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
684    ///  * [`LongPressGestureRecognizer::set_on_tertiary_long_press`], which exposes
685    ///    this callback at the gesture layer.
686    pub on_tertiary_long_press: Option<GestureLongPressCallback>,
687
688    /// Called when a long press gesture with a tertiary button has been
689    /// recognized.
690    ///
691    /// Triggered when a pointer has remained in contact with the screen at the
692    /// same location for a long period of time.
693    ///
694    /// This is equivalent to (and is called immediately before)
695    /// [`on_tertiary_long_press`](Self::on_tertiary_long_press). The only difference between
696    /// the two is that this callback contains details of the position at which the pointer
697    /// initially contacted the screen, whereas
698    /// [`on_tertiary_long_press`](Self::on_tertiary_long_press) does not.
699    ///
700    /// See also:
701    ///
702    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
703    ///  * [`LongPressGestureRecognizer::set_on_tertiary_long_press_start`], which exposes
704    ///    this callback at the gesture layer.
705    pub on_tertiary_long_press_start: Option<GestureLongPressStartCallback>,
706
707    /// A pointer has been drag-moved after a long press with a tertiary button.
708    ///
709    /// See also:
710    ///
711    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
712    ///  * [`LongPressGestureRecognizer::set_on_tertiary_long_press_move_update`], which
713    ///    exposes this callback at the gesture layer.
714    pub on_tertiary_long_press_move_update: Option<GestureLongPressMoveUpdateCallback>,
715
716    /// A pointer that has triggered a long-press with a tertiary button has
717    /// stopped contacting the screen.
718    ///
719    /// This is equivalent to (and is called immediately after)
720    /// [`on_tertiary_long_press_end`](Self::on_tertiary_long_press_end). The only difference
721    /// between the two is that this callback does not contain details of the state of the
722    /// pointer when it stopped contacting the screen.
723    ///
724    /// See also:
725    ///
726    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
727    ///  * [`LongPressGestureRecognizer::set_on_tertiary_long_press_up`], which exposes
728    ///    this callback at the gesture layer.
729    pub on_tertiary_long_press_up: Option<GestureLongPressUpCallback>,
730
731    /// A pointer that has triggered a long-press with a tertiary button has
732    /// stopped contacting the screen.
733    ///
734    /// This is equivalent to (and is called immediately before)
735    /// [`on_tertiary_long_press_up`](Self::on_tertiary_long_press_up). The only difference
736    /// between the two is that this callback contains details of the state of the pointer
737    /// when it stopped contacting the screen, whereas
738    /// [`on_tertiary_long_press_up`](Self::on_tertiary_long_press_up) does not.
739    ///
740    /// See also:
741    ///
742    ///  * `K_TERTIARY_BUTTON`, the button this callback responds to.
743    ///  * [`LongPressGestureRecognizer::set_on_tertiary_long_press_end`], which exposes
744    ///    this callback at the gesture layer.
745    pub on_tertiary_long_press_end: Option<GestureLongPressEndCallback>,
746
747    /// A pointer has contacted the screen with a primary button and might begin
748    /// to move vertically.
749    ///
750    /// See also:
751    ///
752    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
753    pub on_vertical_drag_down: Option<GestureDragDownCallback>,
754
755    /// A pointer has contacted the screen with a primary button and has begun to
756    /// move vertically.
757    ///
758    /// See also:
759    ///
760    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
761    pub on_vertical_drag_start: Option<GestureDragStartCallback>,
762
763    /// A pointer that is in contact with the screen with a primary button and
764    /// moving vertically has moved in the vertical direction.
765    ///
766    /// See also:
767    ///
768    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
769    pub on_vertical_drag_update: Option<GestureDragUpdateCallback>,
770
771    /// A pointer that was previously in contact with the screen with a primary
772    /// button and moving vertically is no longer in contact with the screen and
773    /// was moving at a specific velocity when it stopped contacting the screen.
774    ///
775    /// See also:
776    ///
777    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
778    pub on_vertical_drag_end: Option<GestureDragEndCallback>,
779
780    /// The pointer that previously triggered [`on_vertical_drag_down`](Self::on_vertical_drag_down)
781    /// did not complete.
782    ///
783    /// See also:
784    ///
785    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
786    pub on_vertical_drag_cancel: Option<GestureDragCancelCallback>,
787
788    /// A pointer has contacted the screen with a primary button and might begin
789    /// to move horizontally.
790    pub on_horizontal_drag_down: Option<GestureDragDownCallback>,
791
792    /// A pointer has contacted the screen with a primary button and has begun to
793    /// move horizontally.
794    pub on_horizontal_drag_start: Option<GestureDragStartCallback>,
795
796    /// A pointer that is in contact with the screen with a primary button and
797    /// moving horizontally has moved in the horizontal direction.
798    pub on_horizontal_drag_update: Option<GestureDragUpdateCallback>,
799
800    /// A pointer that was previously in contact with the screen with a primary
801    /// button and moving horizontally is no longer in contact with the screen and
802    /// was moving at a specific velocity when it stopped contacting the screen.
803    pub on_horizontal_drag_end: Option<GestureDragEndCallback>,
804
805    /// The pointer that previously triggered [`on_horizontal_drag_down`](Self::on_horizontal_drag_down)
806    /// did not complete.
807    pub on_horizontal_drag_cancel: Option<GestureDragCancelCallback>,
808
809    /// A pointer has contacted the screen with a primary button and might begin
810    /// to move.
811    ///
812    /// See also:
813    ///
814    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
815    pub on_pan_down: Option<GestureDragDownCallback>,
816
817    /// A pointer has contacted the screen with a primary button and has begun to
818    /// move.
819    ///
820    /// See also:
821    ///
822    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
823    pub on_pan_start: Option<GestureDragStartCallback>,
824
825    /// A pointer that is in contact with the screen with a primary button and
826    /// moving has moved again.
827    ///
828    /// See also:
829    ///
830    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
831    pub on_pan_update: Option<GestureDragUpdateCallback>,
832
833    /// A pointer that was previously in contact with the screen with a primary
834    /// button and moving is no longer in contact with the screen and was moving
835    /// at a specific velocity when it stopped contacting the screen.
836    ///
837    /// See also:
838    ///
839    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
840    pub on_pan_end: Option<GestureDragEndCallback>,
841
842    /// The pointer that previously triggered [`on_pan_down`](Self::on_pan_down) did not complete.
843    ///
844    /// See also:
845    ///
846    ///  * `K_PRIMARY_BUTTON`, the button this callback responds to.
847    pub on_pan_cancel: Option<GestureDragCancelCallback>,
848
849    /// The pointers in contact with the screen have established a focal point and
850    /// initial scale of 1.0.
851    pub on_scale_start: Option<GestureScaleStartCallback>,
852
853    /// The pointers in contact with the screen have indicated a new focal point
854    /// and/or scale.
855    pub on_scale_update: Option<GestureScaleUpdateCallback>,
856
857    /// The pointers are no longer in contact with the screen.
858    pub on_scale_end: Option<GestureScaleEndCallback>,
859
860    /// Determines the way that drag start behavior is handled.
861    ///
862    /// If set to [`DragStartBehavior::Start`], the drag gesture used for
863    /// [`on_horizontal_drag_start`](Self::on_horizontal_drag_start) will begin at the position
864    /// where the drag gesture won the arena. If set to [`DragStartBehavior::Down`] it
865    /// will begin at the position where a down event is first detected.
866    ///
867    /// For more information about the tradeoffs involved in using start vs down
868    /// drag start behavior, see [`DragStartBehavior`].
869    ///
870    /// By default, the drag start behavior is [`DragStartBehavior::Start`].
871    pub drag_start_behavior: DragStartBehavior,
872
873    /// How this gesture detector should behave during hit testing when deciding
874    /// how the hit test propagates to children and whether to consider targets
875    /// behind this one.
876    ///
877    /// This defaults to [`HitTestBehavior::DeferToChild`] if [`child`](Self::child) is not
878    /// `None` and [`HitTestBehavior::Translucent`] if child is `None`.
879    ///
880    /// See [`HitTestBehavior`] for the allowed values and their meanings.
881    pub behavior: Option<HitTestBehavior>,
882
883    /// The kind of devices that are allowed to be recognized.
884    ///
885    /// If set to `None`, events from all device types will be recognized. Defaults to
886    /// `None`.
887    pub supported_devices: Option<HashSet<PointerDeviceKind>>,
888
889    /// Whether scrolling up/down on a trackpad should cause scaling instead of
890    /// panning.
891    ///
892    /// Defaults to false.
893    pub trackpad_scroll_causes_scale: bool,
894
895    /// A factor to control the direction and magnitude of scale when converting
896    /// trackpad scrolling.
897    ///
898    /// Incoming trackpad pan offsets will be divided by this factor to get scale
899    /// values. Increasing this offset will reduce the amount of scaling caused by
900    /// a fixed amount of trackpad scrolling.
901    ///
902    /// Defaults to [`K_DEFAULT_TRACKPAD_SCROLL_TO_SCALE_FACTOR`].
903    pub trackpad_scroll_to_scale_factor: Offset,
904}
905
906impl Default for GestureDetector {
907    fn default() -> GestureDetector {
908        GestureDetector {
909            key: None,
910            child: None,
911            on_tap_down: None,
912            on_tap_up: None,
913            on_tap: None,
914            on_tap_move: None,
915            on_tap_cancel: None,
916            on_secondary_tap: None,
917            on_secondary_tap_down: None,
918            on_secondary_tap_up: None,
919            on_secondary_tap_cancel: None,
920            on_tertiary_tap_down: None,
921            on_tertiary_tap_up: None,
922            on_tertiary_tap_cancel: None,
923            on_double_tap_down: None,
924            on_double_tap: None,
925            on_double_tap_cancel: None,
926            on_long_press_down: None,
927            on_long_press_cancel: None,
928            on_long_press: None,
929            on_long_press_start: None,
930            on_long_press_move_update: None,
931            on_long_press_up: None,
932            on_long_press_end: None,
933            on_secondary_long_press_down: None,
934            on_secondary_long_press_cancel: None,
935            on_secondary_long_press: None,
936            on_secondary_long_press_start: None,
937            on_secondary_long_press_move_update: None,
938            on_secondary_long_press_up: None,
939            on_secondary_long_press_end: None,
940            on_tertiary_long_press_down: None,
941            on_tertiary_long_press_cancel: None,
942            on_tertiary_long_press: None,
943            on_tertiary_long_press_start: None,
944            on_tertiary_long_press_move_update: None,
945            on_tertiary_long_press_up: None,
946            on_tertiary_long_press_end: None,
947            on_vertical_drag_down: None,
948            on_vertical_drag_start: None,
949            on_vertical_drag_update: None,
950            on_vertical_drag_end: None,
951            on_vertical_drag_cancel: None,
952            on_horizontal_drag_down: None,
953            on_horizontal_drag_start: None,
954            on_horizontal_drag_update: None,
955            on_horizontal_drag_end: None,
956            on_horizontal_drag_cancel: None,
957            on_pan_down: None,
958            on_pan_start: None,
959            on_pan_update: None,
960            on_pan_end: None,
961            on_pan_cancel: None,
962            on_scale_start: None,
963            on_scale_update: None,
964            on_scale_end: None,
965            drag_start_behavior: DragStartBehavior::Start,
966            behavior: None,
967            supported_devices: None,
968            trackpad_scroll_causes_scale: false,
969            trackpad_scroll_to_scale_factor: K_DEFAULT_TRACKPAD_SCROLL_TO_SCALE_FACTOR,
970        }
971    }
972}
973
974impl GestureDetector {
975    /// Creates a widget that detects gestures; Dart's named arguments are the setters.
976    pub fn new() -> GestureDetector {
977        GestureDetector::default()
978    }
979
980    /// Dart `GestureDetector(key:)`.
981    pub fn key(mut self, key: KeyRef) -> GestureDetector {
982        self.key = Some(key);
983        self
984    }
985
986    /// Dart `GestureDetector(child:)`.
987    #[cfg_attr(debug_assertions, track_caller)]
988    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> GestureDetector {
989        self.child = Some(child.into_widget());
990        self
991    }
992
993    /// Dart `GestureDetector(on_tap_down:)`.
994    pub fn on_tap_down(mut self, on_tap_down: GestureTapDownCallback) -> GestureDetector {
995        self.on_tap_down = Some(on_tap_down);
996        self
997    }
998
999    /// Dart `GestureDetector(on_tap_up:)`.
1000    pub fn on_tap_up(mut self, on_tap_up: GestureTapUpCallback) -> GestureDetector {
1001        self.on_tap_up = Some(on_tap_up);
1002        self
1003    }
1004
1005    /// Dart `GestureDetector(on_tap:)`.
1006    pub fn on_tap(mut self, on_tap: GestureTapCallback) -> GestureDetector {
1007        self.on_tap = Some(on_tap);
1008        self
1009    }
1010
1011    /// Dart `GestureDetector(on_tap_move:)`.
1012    pub fn on_tap_move(mut self, on_tap_move: GestureTapMoveCallback) -> GestureDetector {
1013        self.on_tap_move = Some(on_tap_move);
1014        self
1015    }
1016
1017    /// Dart `GestureDetector(on_tap_cancel:)`.
1018    pub fn on_tap_cancel(mut self, on_tap_cancel: GestureTapCancelCallback) -> GestureDetector {
1019        self.on_tap_cancel = Some(on_tap_cancel);
1020        self
1021    }
1022
1023    /// Dart `GestureDetector(on_secondary_tap:)`.
1024    pub fn on_secondary_tap(mut self, on_secondary_tap: GestureTapCallback) -> GestureDetector {
1025        self.on_secondary_tap = Some(on_secondary_tap);
1026        self
1027    }
1028
1029    /// Dart `GestureDetector(on_secondary_tap_down:)`.
1030    pub fn on_secondary_tap_down(
1031        mut self,
1032        on_secondary_tap_down: GestureTapDownCallback,
1033    ) -> GestureDetector {
1034        self.on_secondary_tap_down = Some(on_secondary_tap_down);
1035        self
1036    }
1037
1038    /// Dart `GestureDetector(on_secondary_tap_up:)`.
1039    pub fn on_secondary_tap_up(
1040        mut self,
1041        on_secondary_tap_up: GestureTapUpCallback,
1042    ) -> GestureDetector {
1043        self.on_secondary_tap_up = Some(on_secondary_tap_up);
1044        self
1045    }
1046
1047    /// Dart `GestureDetector(on_secondary_tap_cancel:)`.
1048    pub fn on_secondary_tap_cancel(
1049        mut self,
1050        on_secondary_tap_cancel: GestureTapCancelCallback,
1051    ) -> GestureDetector {
1052        self.on_secondary_tap_cancel = Some(on_secondary_tap_cancel);
1053        self
1054    }
1055
1056    /// Dart `GestureDetector(on_tertiary_tap_down:)`.
1057    pub fn on_tertiary_tap_down(
1058        mut self,
1059        on_tertiary_tap_down: GestureTapDownCallback,
1060    ) -> GestureDetector {
1061        self.on_tertiary_tap_down = Some(on_tertiary_tap_down);
1062        self
1063    }
1064
1065    /// Dart `GestureDetector(on_tertiary_tap_up:)`.
1066    pub fn on_tertiary_tap_up(
1067        mut self,
1068        on_tertiary_tap_up: GestureTapUpCallback,
1069    ) -> GestureDetector {
1070        self.on_tertiary_tap_up = Some(on_tertiary_tap_up);
1071        self
1072    }
1073
1074    /// Dart `GestureDetector(on_tertiary_tap_cancel:)`.
1075    pub fn on_tertiary_tap_cancel(
1076        mut self,
1077        on_tertiary_tap_cancel: GestureTapCancelCallback,
1078    ) -> GestureDetector {
1079        self.on_tertiary_tap_cancel = Some(on_tertiary_tap_cancel);
1080        self
1081    }
1082
1083    /// Dart `GestureDetector(on_double_tap_down:)`.
1084    pub fn on_double_tap_down(
1085        mut self,
1086        on_double_tap_down: GestureTapDownCallback,
1087    ) -> GestureDetector {
1088        self.on_double_tap_down = Some(on_double_tap_down);
1089        self
1090    }
1091
1092    /// Dart `GestureDetector(on_double_tap:)`.
1093    pub fn on_double_tap(mut self, on_double_tap: GestureDoubleTapCallback) -> GestureDetector {
1094        self.on_double_tap = Some(on_double_tap);
1095        self
1096    }
1097
1098    /// Dart `GestureDetector(on_double_tap_cancel:)`.
1099    pub fn on_double_tap_cancel(
1100        mut self,
1101        on_double_tap_cancel: GestureTapCancelCallback,
1102    ) -> GestureDetector {
1103        self.on_double_tap_cancel = Some(on_double_tap_cancel);
1104        self
1105    }
1106
1107    /// Dart `GestureDetector(on_long_press_down:)`.
1108    pub fn on_long_press_down(
1109        mut self,
1110        on_long_press_down: GestureLongPressDownCallback,
1111    ) -> GestureDetector {
1112        self.on_long_press_down = Some(on_long_press_down);
1113        self
1114    }
1115
1116    /// Dart `GestureDetector(on_long_press_cancel:)`.
1117    pub fn on_long_press_cancel(
1118        mut self,
1119        on_long_press_cancel: GestureLongPressCancelCallback,
1120    ) -> GestureDetector {
1121        self.on_long_press_cancel = Some(on_long_press_cancel);
1122        self
1123    }
1124
1125    /// Dart `GestureDetector(on_long_press:)`.
1126    pub fn on_long_press(mut self, on_long_press: GestureLongPressCallback) -> GestureDetector {
1127        self.on_long_press = Some(on_long_press);
1128        self
1129    }
1130
1131    /// Dart `GestureDetector(on_long_press_start:)`.
1132    pub fn on_long_press_start(
1133        mut self,
1134        on_long_press_start: GestureLongPressStartCallback,
1135    ) -> GestureDetector {
1136        self.on_long_press_start = Some(on_long_press_start);
1137        self
1138    }
1139
1140    /// Dart `GestureDetector(on_long_press_move_update:)`.
1141    pub fn on_long_press_move_update(
1142        mut self,
1143        on_long_press_move_update: GestureLongPressMoveUpdateCallback,
1144    ) -> GestureDetector {
1145        self.on_long_press_move_update = Some(on_long_press_move_update);
1146        self
1147    }
1148
1149    /// Dart `GestureDetector(on_long_press_up:)`.
1150    pub fn on_long_press_up(
1151        mut self,
1152        on_long_press_up: GestureLongPressUpCallback,
1153    ) -> GestureDetector {
1154        self.on_long_press_up = Some(on_long_press_up);
1155        self
1156    }
1157
1158    /// Dart `GestureDetector(on_long_press_end:)`.
1159    pub fn on_long_press_end(
1160        mut self,
1161        on_long_press_end: GestureLongPressEndCallback,
1162    ) -> GestureDetector {
1163        self.on_long_press_end = Some(on_long_press_end);
1164        self
1165    }
1166
1167    /// Dart `GestureDetector(on_secondary_long_press_down:)`.
1168    pub fn on_secondary_long_press_down(
1169        mut self,
1170        on_secondary_long_press_down: GestureLongPressDownCallback,
1171    ) -> GestureDetector {
1172        self.on_secondary_long_press_down = Some(on_secondary_long_press_down);
1173        self
1174    }
1175
1176    /// Dart `GestureDetector(on_secondary_long_press_cancel:)`.
1177    pub fn on_secondary_long_press_cancel(
1178        mut self,
1179        on_secondary_long_press_cancel: GestureLongPressCancelCallback,
1180    ) -> GestureDetector {
1181        self.on_secondary_long_press_cancel = Some(on_secondary_long_press_cancel);
1182        self
1183    }
1184
1185    /// Dart `GestureDetector(on_secondary_long_press:)`.
1186    pub fn on_secondary_long_press(
1187        mut self,
1188        on_secondary_long_press: GestureLongPressCallback,
1189    ) -> GestureDetector {
1190        self.on_secondary_long_press = Some(on_secondary_long_press);
1191        self
1192    }
1193
1194    /// Dart `GestureDetector(on_secondary_long_press_start:)`.
1195    pub fn on_secondary_long_press_start(
1196        mut self,
1197        on_secondary_long_press_start: GestureLongPressStartCallback,
1198    ) -> GestureDetector {
1199        self.on_secondary_long_press_start = Some(on_secondary_long_press_start);
1200        self
1201    }
1202
1203    /// Dart `GestureDetector(on_secondary_long_press_move_update:)`.
1204    pub fn on_secondary_long_press_move_update(
1205        mut self,
1206        on_secondary_long_press_move_update: GestureLongPressMoveUpdateCallback,
1207    ) -> GestureDetector {
1208        self.on_secondary_long_press_move_update = Some(on_secondary_long_press_move_update);
1209        self
1210    }
1211
1212    /// Dart `GestureDetector(on_secondary_long_press_up:)`.
1213    pub fn on_secondary_long_press_up(
1214        mut self,
1215        on_secondary_long_press_up: GestureLongPressUpCallback,
1216    ) -> GestureDetector {
1217        self.on_secondary_long_press_up = Some(on_secondary_long_press_up);
1218        self
1219    }
1220
1221    /// Dart `GestureDetector(on_secondary_long_press_end:)`.
1222    pub fn on_secondary_long_press_end(
1223        mut self,
1224        on_secondary_long_press_end: GestureLongPressEndCallback,
1225    ) -> GestureDetector {
1226        self.on_secondary_long_press_end = Some(on_secondary_long_press_end);
1227        self
1228    }
1229
1230    /// Dart `GestureDetector(on_tertiary_long_press_down:)`.
1231    pub fn on_tertiary_long_press_down(
1232        mut self,
1233        on_tertiary_long_press_down: GestureLongPressDownCallback,
1234    ) -> GestureDetector {
1235        self.on_tertiary_long_press_down = Some(on_tertiary_long_press_down);
1236        self
1237    }
1238
1239    /// Dart `GestureDetector(on_tertiary_long_press_cancel:)`.
1240    pub fn on_tertiary_long_press_cancel(
1241        mut self,
1242        on_tertiary_long_press_cancel: GestureLongPressCancelCallback,
1243    ) -> GestureDetector {
1244        self.on_tertiary_long_press_cancel = Some(on_tertiary_long_press_cancel);
1245        self
1246    }
1247
1248    /// Dart `GestureDetector(on_tertiary_long_press:)`.
1249    pub fn on_tertiary_long_press(
1250        mut self,
1251        on_tertiary_long_press: GestureLongPressCallback,
1252    ) -> GestureDetector {
1253        self.on_tertiary_long_press = Some(on_tertiary_long_press);
1254        self
1255    }
1256
1257    /// Dart `GestureDetector(on_tertiary_long_press_start:)`.
1258    pub fn on_tertiary_long_press_start(
1259        mut self,
1260        on_tertiary_long_press_start: GestureLongPressStartCallback,
1261    ) -> GestureDetector {
1262        self.on_tertiary_long_press_start = Some(on_tertiary_long_press_start);
1263        self
1264    }
1265
1266    /// Dart `GestureDetector(on_tertiary_long_press_move_update:)`.
1267    pub fn on_tertiary_long_press_move_update(
1268        mut self,
1269        on_tertiary_long_press_move_update: GestureLongPressMoveUpdateCallback,
1270    ) -> GestureDetector {
1271        self.on_tertiary_long_press_move_update = Some(on_tertiary_long_press_move_update);
1272        self
1273    }
1274
1275    /// Dart `GestureDetector(on_tertiary_long_press_up:)`.
1276    pub fn on_tertiary_long_press_up(
1277        mut self,
1278        on_tertiary_long_press_up: GestureLongPressUpCallback,
1279    ) -> GestureDetector {
1280        self.on_tertiary_long_press_up = Some(on_tertiary_long_press_up);
1281        self
1282    }
1283
1284    /// Dart `GestureDetector(on_tertiary_long_press_end:)`.
1285    pub fn on_tertiary_long_press_end(
1286        mut self,
1287        on_tertiary_long_press_end: GestureLongPressEndCallback,
1288    ) -> GestureDetector {
1289        self.on_tertiary_long_press_end = Some(on_tertiary_long_press_end);
1290        self
1291    }
1292
1293    /// Dart `GestureDetector(on_vertical_drag_down:)`.
1294    pub fn on_vertical_drag_down(
1295        mut self,
1296        on_vertical_drag_down: GestureDragDownCallback,
1297    ) -> GestureDetector {
1298        self.on_vertical_drag_down = Some(on_vertical_drag_down);
1299        self
1300    }
1301
1302    /// Dart `GestureDetector(on_vertical_drag_start:)`.
1303    pub fn on_vertical_drag_start(
1304        mut self,
1305        on_vertical_drag_start: GestureDragStartCallback,
1306    ) -> GestureDetector {
1307        self.on_vertical_drag_start = Some(on_vertical_drag_start);
1308        self.debug_assert_gestures_are_consistent();
1309        self
1310    }
1311
1312    /// Dart `GestureDetector(on_vertical_drag_update:)`.
1313    pub fn on_vertical_drag_update(
1314        mut self,
1315        on_vertical_drag_update: GestureDragUpdateCallback,
1316    ) -> GestureDetector {
1317        self.on_vertical_drag_update = Some(on_vertical_drag_update);
1318        self.debug_assert_gestures_are_consistent();
1319        self
1320    }
1321
1322    /// Dart `GestureDetector(on_vertical_drag_end:)`.
1323    pub fn on_vertical_drag_end(
1324        mut self,
1325        on_vertical_drag_end: GestureDragEndCallback,
1326    ) -> GestureDetector {
1327        self.on_vertical_drag_end = Some(on_vertical_drag_end);
1328        self.debug_assert_gestures_are_consistent();
1329        self
1330    }
1331
1332    /// Dart `GestureDetector(on_vertical_drag_cancel:)`.
1333    pub fn on_vertical_drag_cancel(
1334        mut self,
1335        on_vertical_drag_cancel: GestureDragCancelCallback,
1336    ) -> GestureDetector {
1337        self.on_vertical_drag_cancel = Some(on_vertical_drag_cancel);
1338        self
1339    }
1340
1341    /// Dart `GestureDetector(on_horizontal_drag_down:)`.
1342    pub fn on_horizontal_drag_down(
1343        mut self,
1344        on_horizontal_drag_down: GestureDragDownCallback,
1345    ) -> GestureDetector {
1346        self.on_horizontal_drag_down = Some(on_horizontal_drag_down);
1347        self
1348    }
1349
1350    /// Dart `GestureDetector(on_horizontal_drag_start:)`.
1351    pub fn on_horizontal_drag_start(
1352        mut self,
1353        on_horizontal_drag_start: GestureDragStartCallback,
1354    ) -> GestureDetector {
1355        self.on_horizontal_drag_start = Some(on_horizontal_drag_start);
1356        self.debug_assert_gestures_are_consistent();
1357        self
1358    }
1359
1360    /// Dart `GestureDetector(on_horizontal_drag_update:)`.
1361    pub fn on_horizontal_drag_update(
1362        mut self,
1363        on_horizontal_drag_update: GestureDragUpdateCallback,
1364    ) -> GestureDetector {
1365        self.on_horizontal_drag_update = Some(on_horizontal_drag_update);
1366        self.debug_assert_gestures_are_consistent();
1367        self
1368    }
1369
1370    /// Dart `GestureDetector(on_horizontal_drag_end:)`.
1371    pub fn on_horizontal_drag_end(
1372        mut self,
1373        on_horizontal_drag_end: GestureDragEndCallback,
1374    ) -> GestureDetector {
1375        self.on_horizontal_drag_end = Some(on_horizontal_drag_end);
1376        self.debug_assert_gestures_are_consistent();
1377        self
1378    }
1379
1380    /// Dart `GestureDetector(on_horizontal_drag_cancel:)`.
1381    pub fn on_horizontal_drag_cancel(
1382        mut self,
1383        on_horizontal_drag_cancel: GestureDragCancelCallback,
1384    ) -> GestureDetector {
1385        self.on_horizontal_drag_cancel = Some(on_horizontal_drag_cancel);
1386        self
1387    }
1388
1389    /// Dart `GestureDetector(on_pan_down:)`.
1390    pub fn on_pan_down(mut self, on_pan_down: GestureDragDownCallback) -> GestureDetector {
1391        self.on_pan_down = Some(on_pan_down);
1392        self
1393    }
1394
1395    /// Dart `GestureDetector(on_pan_start:)`.
1396    pub fn on_pan_start(mut self, on_pan_start: GestureDragStartCallback) -> GestureDetector {
1397        self.on_pan_start = Some(on_pan_start);
1398        self.debug_assert_gestures_are_consistent();
1399        self
1400    }
1401
1402    /// Dart `GestureDetector(on_pan_update:)`.
1403    pub fn on_pan_update(mut self, on_pan_update: GestureDragUpdateCallback) -> GestureDetector {
1404        self.on_pan_update = Some(on_pan_update);
1405        self.debug_assert_gestures_are_consistent();
1406        self
1407    }
1408
1409    /// Dart `GestureDetector(on_pan_end:)`.
1410    pub fn on_pan_end(mut self, on_pan_end: GestureDragEndCallback) -> GestureDetector {
1411        self.on_pan_end = Some(on_pan_end);
1412        self.debug_assert_gestures_are_consistent();
1413        self
1414    }
1415
1416    /// Dart `GestureDetector(on_pan_cancel:)`.
1417    pub fn on_pan_cancel(mut self, on_pan_cancel: GestureDragCancelCallback) -> GestureDetector {
1418        self.on_pan_cancel = Some(on_pan_cancel);
1419        self
1420    }
1421
1422    /// Dart `GestureDetector(on_scale_start:)`.
1423    pub fn on_scale_start(mut self, on_scale_start: GestureScaleStartCallback) -> GestureDetector {
1424        self.on_scale_start = Some(on_scale_start);
1425        self.debug_assert_gestures_are_consistent();
1426        self
1427    }
1428
1429    /// Dart `GestureDetector(on_scale_update:)`.
1430    pub fn on_scale_update(
1431        mut self,
1432        on_scale_update: GestureScaleUpdateCallback,
1433    ) -> GestureDetector {
1434        self.on_scale_update = Some(on_scale_update);
1435        self.debug_assert_gestures_are_consistent();
1436        self
1437    }
1438
1439    /// Dart `GestureDetector(on_scale_end:)`.
1440    pub fn on_scale_end(mut self, on_scale_end: GestureScaleEndCallback) -> GestureDetector {
1441        self.on_scale_end = Some(on_scale_end);
1442        self.debug_assert_gestures_are_consistent();
1443        self
1444    }
1445
1446    /// Dart `GestureDetector(drag_start_behavior:)`.
1447    pub fn drag_start_behavior(
1448        mut self,
1449        drag_start_behavior: DragStartBehavior,
1450    ) -> GestureDetector {
1451        self.drag_start_behavior = drag_start_behavior;
1452        self
1453    }
1454
1455    /// Dart `GestureDetector(behavior:)`.
1456    pub fn behavior(mut self, behavior: HitTestBehavior) -> GestureDetector {
1457        self.behavior = Some(behavior);
1458        self
1459    }
1460
1461    /// Dart `GestureDetector(supported_devices:)`.
1462    pub fn supported_devices(
1463        mut self,
1464        supported_devices: HashSet<PointerDeviceKind>,
1465    ) -> GestureDetector {
1466        self.supported_devices = Some(supported_devices);
1467        self
1468    }
1469
1470    /// Dart `GestureDetector(trackpad_scroll_causes_scale:)`.
1471    pub fn trackpad_scroll_causes_scale(
1472        mut self,
1473        trackpad_scroll_causes_scale: bool,
1474    ) -> GestureDetector {
1475        self.trackpad_scroll_causes_scale = trackpad_scroll_causes_scale;
1476        self
1477    }
1478
1479    /// Dart `GestureDetector(trackpad_scroll_to_scale_factor:)`.
1480    pub fn trackpad_scroll_to_scale_factor(
1481        mut self,
1482        trackpad_scroll_to_scale_factor: Offset,
1483    ) -> GestureDetector {
1484        self.trackpad_scroll_to_scale_factor = trackpad_scroll_to_scale_factor;
1485        self
1486    }
1487
1488    /// Dart's constructor assert: a pan or scale recognizer is redundant with a scale one,
1489    /// and ignored beside both drag axes.
1490    fn debug_assert_gestures_are_consistent(&self) {
1491        if !cfg!(debug_assertions) {
1492            return;
1493        }
1494        let have_vertical_drag = self.on_vertical_drag_start.is_some()
1495            || self.on_vertical_drag_update.is_some()
1496            || self.on_vertical_drag_end.is_some();
1497        let have_horizontal_drag = self.on_horizontal_drag_start.is_some()
1498            || self.on_horizontal_drag_update.is_some()
1499            || self.on_horizontal_drag_end.is_some();
1500        let have_pan = self.on_pan_start.is_some()
1501            || self.on_pan_update.is_some()
1502            || self.on_pan_end.is_some();
1503        let have_scale = self.on_scale_start.is_some()
1504            || self.on_scale_update.is_some()
1505            || self.on_scale_end.is_some();
1506        if have_pan || have_scale {
1507            assert!(
1508                !(have_pan && have_scale),
1509                "Incorrect GestureDetector arguments.\nHaving both a pan gesture recognizer and a \
1510                 scale gesture recognizer is redundant; scale is a superset of pan.\nJust use the \
1511                 scale gesture recognizer."
1512            );
1513            let recognizer = if have_pan { "pan" } else { "scale" };
1514            assert!(
1515                !(have_vertical_drag && have_horizontal_drag),
1516                "Incorrect GestureDetector arguments.\nSimultaneously having a vertical drag \
1517                 gesture recognizer, a horizontal drag gesture recognizer, and a {recognizer} \
1518                 gesture recognizer will result in the {recognizer} gesture recognizer being \
1519                 ignored, since the other two will catch all drags."
1520            );
1521        }
1522    }
1523
1524    fn has_tap_callback(&self) -> bool {
1525        self.on_tap_down.is_some()
1526            || self.on_tap_up.is_some()
1527            || self.on_tap.is_some()
1528            || self.on_tap_cancel.is_some()
1529            || self.on_secondary_tap.is_some()
1530            || self.on_secondary_tap_down.is_some()
1531            || self.on_secondary_tap_up.is_some()
1532            || self.on_secondary_tap_cancel.is_some()
1533            || self.on_tertiary_tap_down.is_some()
1534            || self.on_tertiary_tap_up.is_some()
1535            || self.on_tertiary_tap_cancel.is_some()
1536    }
1537
1538    fn has_double_tap_callback(&self) -> bool {
1539        self.on_double_tap.is_some()
1540            || self.on_double_tap_down.is_some()
1541            || self.on_double_tap_cancel.is_some()
1542    }
1543
1544    fn has_long_press_callback(&self) -> bool {
1545        self.on_long_press_down.is_some()
1546            || self.on_long_press_cancel.is_some()
1547            || self.on_long_press.is_some()
1548            || self.on_long_press_start.is_some()
1549            || self.on_long_press_move_update.is_some()
1550            || self.on_long_press_up.is_some()
1551            || self.on_long_press_end.is_some()
1552            || self.on_secondary_long_press_down.is_some()
1553            || self.on_secondary_long_press_cancel.is_some()
1554            || self.on_secondary_long_press.is_some()
1555            || self.on_secondary_long_press_start.is_some()
1556            || self.on_secondary_long_press_move_update.is_some()
1557            || self.on_secondary_long_press_up.is_some()
1558            || self.on_secondary_long_press_end.is_some()
1559            || self.on_tertiary_long_press_down.is_some()
1560            || self.on_tertiary_long_press_cancel.is_some()
1561            || self.on_tertiary_long_press.is_some()
1562            || self.on_tertiary_long_press_start.is_some()
1563            || self.on_tertiary_long_press_move_update.is_some()
1564            || self.on_tertiary_long_press_up.is_some()
1565            || self.on_tertiary_long_press_end.is_some()
1566    }
1567
1568    fn has_vertical_drag_callback(&self) -> bool {
1569        self.on_vertical_drag_down.is_some()
1570            || self.on_vertical_drag_start.is_some()
1571            || self.on_vertical_drag_update.is_some()
1572            || self.on_vertical_drag_end.is_some()
1573            || self.on_vertical_drag_cancel.is_some()
1574    }
1575
1576    fn has_horizontal_drag_callback(&self) -> bool {
1577        self.on_horizontal_drag_down.is_some()
1578            || self.on_horizontal_drag_start.is_some()
1579            || self.on_horizontal_drag_update.is_some()
1580            || self.on_horizontal_drag_end.is_some()
1581            || self.on_horizontal_drag_cancel.is_some()
1582    }
1583
1584    fn has_pan_callback(&self) -> bool {
1585        self.on_pan_down.is_some()
1586            || self.on_pan_start.is_some()
1587            || self.on_pan_update.is_some()
1588            || self.on_pan_end.is_some()
1589            || self.on_pan_cancel.is_some()
1590    }
1591
1592    fn has_scale_callback(&self) -> bool {
1593        self.on_scale_start.is_some()
1594            || self.on_scale_update.is_some()
1595            || self.on_scale_end.is_some()
1596    }
1597
1598    /// The `TapGestureRecognizer` factory of Dart's `build`; the closures capture the
1599    /// widget as Dart's capture `this`.
1600    fn tap_factory(
1601        &self,
1602        gesture_settings: Option<DeviceGestureSettings>,
1603    ) -> GestureRecognizerFactoryRef {
1604        let this = self.clone();
1605        let constructed = self.clone();
1606        GestureRecognizerFactoryWithHandlers::<TapGestureRecognizer>::new(
1607            move |app| {
1608                let instance = TapGestureRecognizer::new(app);
1609                instance.set_supported_devices(app, constructed.supported_devices.clone());
1610                instance
1611            },
1612            move |app, instance| {
1613                instance.set_on_tap_down(app, this.on_tap_down.clone());
1614                instance.set_on_tap_up(app, this.on_tap_up.clone());
1615                instance.set_on_tap(app, this.on_tap.clone());
1616                instance.set_on_tap_cancel(app, this.on_tap_cancel.clone());
1617                instance.set_on_secondary_tap(app, this.on_secondary_tap.clone());
1618                instance.set_on_secondary_tap_down(app, this.on_secondary_tap_down.clone());
1619                instance.set_on_secondary_tap_up(app, this.on_secondary_tap_up.clone());
1620                instance.set_on_secondary_tap_cancel(app, this.on_secondary_tap_cancel.clone());
1621                instance.set_on_tertiary_tap_down(app, this.on_tertiary_tap_down.clone());
1622                instance.set_on_tertiary_tap_up(app, this.on_tertiary_tap_up.clone());
1623                instance.set_on_tertiary_tap_cancel(app, this.on_tertiary_tap_cancel.clone());
1624                instance.set_gesture_settings(app, gesture_settings);
1625                instance.set_supported_devices(app, this.supported_devices.clone());
1626            },
1627        )
1628        .into_factory()
1629    }
1630
1631    /// The `DoubleTapGestureRecognizer` factory of Dart's `build`.
1632    fn double_tap_factory(
1633        &self,
1634        gesture_settings: Option<DeviceGestureSettings>,
1635    ) -> GestureRecognizerFactoryRef {
1636        let this = self.clone();
1637        let constructed = self.clone();
1638        GestureRecognizerFactoryWithHandlers::<DoubleTapGestureRecognizer>::new(
1639            move |app| {
1640                let instance = DoubleTapGestureRecognizer::new(app);
1641                instance.set_supported_devices(app, constructed.supported_devices.clone());
1642                instance
1643            },
1644            move |app, instance| {
1645                instance.set_on_double_tap_down(app, this.on_double_tap_down.clone());
1646                instance.set_on_double_tap(app, this.on_double_tap.clone());
1647                instance.set_on_double_tap_cancel(app, this.on_double_tap_cancel.clone());
1648                instance.set_gesture_settings(app, gesture_settings);
1649                instance.set_supported_devices(app, this.supported_devices.clone());
1650            },
1651        )
1652        .into_factory()
1653    }
1654
1655    /// The `LongPressGestureRecognizer` factory of Dart's `build`.
1656    fn long_press_factory(
1657        &self,
1658        gesture_settings: Option<DeviceGestureSettings>,
1659    ) -> GestureRecognizerFactoryRef {
1660        let this = self.clone();
1661        let constructed = self.clone();
1662        GestureRecognizerFactoryWithHandlers::<LongPressGestureRecognizer>::new(
1663            move |app| {
1664                let instance = LongPressGestureRecognizer::new(app);
1665                instance.set_supported_devices(app, constructed.supported_devices.clone());
1666                instance
1667            },
1668            move |app, instance| {
1669                instance.set_on_long_press_down(app, this.on_long_press_down.clone());
1670                instance.set_on_long_press_cancel(app, this.on_long_press_cancel.clone());
1671                instance.set_on_long_press(app, this.on_long_press.clone());
1672                instance.set_on_long_press_start(app, this.on_long_press_start.clone());
1673                instance.set_on_long_press_move_update(app, this.on_long_press_move_update.clone());
1674                instance.set_on_long_press_up(app, this.on_long_press_up.clone());
1675                instance.set_on_long_press_end(app, this.on_long_press_end.clone());
1676                instance.set_on_secondary_long_press_down(
1677                    app,
1678                    this.on_secondary_long_press_down.clone(),
1679                );
1680                instance.set_on_secondary_long_press_cancel(
1681                    app,
1682                    this.on_secondary_long_press_cancel.clone(),
1683                );
1684                instance.set_on_secondary_long_press(app, this.on_secondary_long_press.clone());
1685                instance.set_on_secondary_long_press_start(
1686                    app,
1687                    this.on_secondary_long_press_start.clone(),
1688                );
1689                instance.set_on_secondary_long_press_move_update(
1690                    app,
1691                    this.on_secondary_long_press_move_update.clone(),
1692                );
1693                instance
1694                    .set_on_secondary_long_press_up(app, this.on_secondary_long_press_up.clone());
1695                instance
1696                    .set_on_secondary_long_press_end(app, this.on_secondary_long_press_end.clone());
1697                instance
1698                    .set_on_tertiary_long_press_down(app, this.on_tertiary_long_press_down.clone());
1699                instance.set_on_tertiary_long_press_cancel(
1700                    app,
1701                    this.on_tertiary_long_press_cancel.clone(),
1702                );
1703                instance.set_on_tertiary_long_press(app, this.on_tertiary_long_press.clone());
1704                instance.set_on_tertiary_long_press_start(
1705                    app,
1706                    this.on_tertiary_long_press_start.clone(),
1707                );
1708                instance.set_on_tertiary_long_press_move_update(
1709                    app,
1710                    this.on_tertiary_long_press_move_update.clone(),
1711                );
1712                instance.set_on_tertiary_long_press_up(app, this.on_tertiary_long_press_up.clone());
1713                instance
1714                    .set_on_tertiary_long_press_end(app, this.on_tertiary_long_press_end.clone());
1715                instance.set_gesture_settings(app, gesture_settings);
1716                instance.set_supported_devices(app, this.supported_devices.clone());
1717            },
1718        )
1719        .into_factory()
1720    }
1721
1722    /// The `VerticalDragGestureRecognizer` factory of Dart's `build`.
1723    fn vertical_drag_factory(
1724        &self,
1725        gesture_settings: Option<DeviceGestureSettings>,
1726        multitouch_drag_strategy: MultitouchDragStrategy,
1727    ) -> GestureRecognizerFactoryRef {
1728        let this = self.clone();
1729        let constructed = self.clone();
1730        GestureRecognizerFactoryWithHandlers::<VerticalDragGestureRecognizer>::new(
1731            move |app| {
1732                let instance = VerticalDragGestureRecognizer::new(app);
1733                instance.set_supported_devices(app, constructed.supported_devices.clone());
1734                instance
1735            },
1736            move |app, instance| {
1737                instance.set_on_down(app, this.on_vertical_drag_down.clone());
1738                instance.set_on_start(app, this.on_vertical_drag_start.clone());
1739                instance.set_on_update(app, this.on_vertical_drag_update.clone());
1740                instance.set_on_end(app, this.on_vertical_drag_end.clone());
1741                instance.set_on_cancel(app, this.on_vertical_drag_cancel.clone());
1742                instance.set_drag_start_behavior(app, this.drag_start_behavior);
1743                instance.set_multitouch_drag_strategy(app, multitouch_drag_strategy);
1744                instance.set_gesture_settings(app, gesture_settings);
1745                instance.set_supported_devices(app, this.supported_devices.clone());
1746            },
1747        )
1748        .into_factory()
1749    }
1750
1751    /// The `HorizontalDragGestureRecognizer` factory of Dart's `build`.
1752    fn horizontal_drag_factory(
1753        &self,
1754        gesture_settings: Option<DeviceGestureSettings>,
1755        multitouch_drag_strategy: MultitouchDragStrategy,
1756    ) -> GestureRecognizerFactoryRef {
1757        let this = self.clone();
1758        let constructed = self.clone();
1759        GestureRecognizerFactoryWithHandlers::<HorizontalDragGestureRecognizer>::new(
1760            move |app| {
1761                let instance = HorizontalDragGestureRecognizer::new(app);
1762                instance.set_supported_devices(app, constructed.supported_devices.clone());
1763                instance
1764            },
1765            move |app, instance| {
1766                instance.set_on_down(app, this.on_horizontal_drag_down.clone());
1767                instance.set_on_start(app, this.on_horizontal_drag_start.clone());
1768                instance.set_on_update(app, this.on_horizontal_drag_update.clone());
1769                instance.set_on_end(app, this.on_horizontal_drag_end.clone());
1770                instance.set_on_cancel(app, this.on_horizontal_drag_cancel.clone());
1771                instance.set_drag_start_behavior(app, this.drag_start_behavior);
1772                instance.set_multitouch_drag_strategy(app, multitouch_drag_strategy);
1773                instance.set_gesture_settings(app, gesture_settings);
1774                instance.set_supported_devices(app, this.supported_devices.clone());
1775            },
1776        )
1777        .into_factory()
1778    }
1779
1780    /// The `PanGestureRecognizer` factory of Dart's `build`.
1781    fn pan_factory(
1782        &self,
1783        gesture_settings: Option<DeviceGestureSettings>,
1784        multitouch_drag_strategy: MultitouchDragStrategy,
1785    ) -> GestureRecognizerFactoryRef {
1786        let this = self.clone();
1787        let constructed = self.clone();
1788        GestureRecognizerFactoryWithHandlers::<PanGestureRecognizer>::new(
1789            move |app| {
1790                let instance = PanGestureRecognizer::new(app);
1791                instance.set_supported_devices(app, constructed.supported_devices.clone());
1792                instance
1793            },
1794            move |app, instance| {
1795                instance.set_on_down(app, this.on_pan_down.clone());
1796                instance.set_on_start(app, this.on_pan_start.clone());
1797                instance.set_on_update(app, this.on_pan_update.clone());
1798                instance.set_on_end(app, this.on_pan_end.clone());
1799                instance.set_on_cancel(app, this.on_pan_cancel.clone());
1800                instance.set_drag_start_behavior(app, this.drag_start_behavior);
1801                instance.set_multitouch_drag_strategy(app, multitouch_drag_strategy);
1802                instance.set_gesture_settings(app, gesture_settings);
1803                instance.set_supported_devices(app, this.supported_devices.clone());
1804            },
1805        )
1806        .into_factory()
1807    }
1808
1809    /// The `ScaleGestureRecognizer` factory of Dart's `build`.
1810    fn scale_factory(
1811        &self,
1812        gesture_settings: Option<DeviceGestureSettings>,
1813    ) -> GestureRecognizerFactoryRef {
1814        let this = self.clone();
1815        let constructed = self.clone();
1816        GestureRecognizerFactoryWithHandlers::<ScaleGestureRecognizer>::new(
1817            move |app| {
1818                let instance = ScaleGestureRecognizer::new(app);
1819                instance.set_supported_devices(app, constructed.supported_devices.clone());
1820                instance
1821            },
1822            move |app, instance| {
1823                instance.set_on_start(app, this.on_scale_start.clone());
1824                instance.set_on_update(app, this.on_scale_update.clone());
1825                instance.set_on_end(app, this.on_scale_end.clone());
1826                instance.set_drag_start_behavior(app, this.drag_start_behavior);
1827                instance.set_gesture_settings(app, gesture_settings);
1828                instance.set_trackpad_scroll_causes_scale(app, this.trackpad_scroll_causes_scale);
1829                instance
1830                    .set_trackpad_scroll_to_scale_factor(app, this.trackpad_scroll_to_scale_factor);
1831                instance.set_supported_devices(app, this.supported_devices.clone());
1832            },
1833        )
1834        .into_factory()
1835    }
1836}
1837
1838impl StatelessWidget for GestureDetector {
1839    fn key(&self) -> Option<&KeyRef> {
1840        self.key.as_ref()
1841    }
1842
1843    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1844        properties.add(EnumProperty::new("startBehavior", self.drag_start_behavior));
1845    }
1846
1847    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1848        let mut gestures: GestureRecognizerFactories = Vec::new();
1849        let gesture_settings = MediaQuery::maybe_gesture_settings_of(app, context);
1850        let configuration = ScrollConfiguration::of(app, context);
1851        let multitouch_drag_strategy = configuration.get_multitouch_drag_strategy(app, context);
1852
1853        if self.has_tap_callback() {
1854            gestures.push((
1855                TypeId::of::<TapGestureRecognizer>(),
1856                self.tap_factory(gesture_settings),
1857            ));
1858        }
1859
1860        if self.has_double_tap_callback() {
1861            gestures.push((
1862                TypeId::of::<DoubleTapGestureRecognizer>(),
1863                self.double_tap_factory(gesture_settings),
1864            ));
1865        }
1866
1867        if self.has_long_press_callback() {
1868            gestures.push((
1869                TypeId::of::<LongPressGestureRecognizer>(),
1870                self.long_press_factory(gesture_settings),
1871            ));
1872        }
1873
1874        if self.has_vertical_drag_callback() {
1875            gestures.push((
1876                TypeId::of::<VerticalDragGestureRecognizer>(),
1877                self.vertical_drag_factory(gesture_settings, multitouch_drag_strategy),
1878            ));
1879        }
1880
1881        if self.has_horizontal_drag_callback() {
1882            gestures.push((
1883                TypeId::of::<HorizontalDragGestureRecognizer>(),
1884                self.horizontal_drag_factory(gesture_settings, multitouch_drag_strategy),
1885            ));
1886        }
1887
1888        if self.has_pan_callback() {
1889            gestures.push((
1890                TypeId::of::<PanGestureRecognizer>(),
1891                self.pan_factory(gesture_settings, multitouch_drag_strategy),
1892            ));
1893        }
1894
1895        if self.has_scale_callback() {
1896            gestures.push((
1897                TypeId::of::<ScaleGestureRecognizer>(),
1898                self.scale_factory(gesture_settings),
1899            ));
1900        }
1901
1902        let mut detector = RawGestureDetector::new().gestures(gestures);
1903        if let Some(child) = &self.child {
1904            detector = detector.child(child.clone());
1905        }
1906        if let Some(behavior) = self.behavior {
1907            detector = detector.behavior(behavior);
1908        }
1909        detector.into_widget()
1910    }
1911}
1912
1913impl Debug for GestureDetector {
1914    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1915        f.debug_struct("GestureDetector")
1916            .field("key", &self.key)
1917            .field("behavior", &self.behavior)
1918            .field("supportedDevices", &self.supported_devices)
1919            .field("child", &self.child)
1920            .finish()
1921    }
1922}
1923
1924/// A widget that detects gestures described by the given gesture
1925/// factories.
1926///
1927/// For common gestures, use a [`GestureDetector`].
1928/// [`RawGestureDetector`] is useful primarily when developing your
1929/// own gesture recognizers.
1930///
1931/// Configuring the gesture recognizers requires a carefully constructed map, as
1932/// described in [`gestures`](Self::gestures).
1933///
1934/// See also:
1935///
1936///  * [`GestureDetector`], a less flexible but much simpler widget that does the same thing.
1937///  * `Listener`, a widget that reports raw pointer events.
1938///  * `GestureRecognizer`, the class that you extend to create a custom gesture recognizer.
1939#[derive(Debug, Default)]
1940pub struct RawGestureDetector {
1941    pub key: Option<KeyRef>,
1942
1943    /// The widget below this widget in the tree.
1944    pub child: Option<WidgetRef>,
1945
1946    /// The gestures that this widget will attempt to recognize.
1947    ///
1948    /// This should be a map from `GestureRecognizer` subclasses to
1949    /// [`GestureRecognizerFactory`] subclasses specialized with the same type.
1950    ///
1951    /// This value can be late-bound at layout time using
1952    /// [`RawGestureDetectorState::replace_gesture_recognizers`].
1953    pub gestures: GestureRecognizerFactories,
1954
1955    /// How this gesture detector should behave during hit testing.
1956    ///
1957    /// This defaults to [`HitTestBehavior::DeferToChild`] if [`child`](Self::child) is not
1958    /// `None` and [`HitTestBehavior::Translucent`] if child is `None`.
1959    pub behavior: Option<HitTestBehavior>,
1960}
1961
1962impl RawGestureDetector {
1963    /// Creates a widget that detects gestures; Dart's named arguments are the setters.
1964    pub fn new() -> RawGestureDetector {
1965        RawGestureDetector::default()
1966    }
1967
1968    /// Dart `RawGestureDetector(key:)`.
1969    pub fn key(mut self, key: KeyRef) -> RawGestureDetector {
1970        self.key = Some(key);
1971        self
1972    }
1973
1974    /// Dart `RawGestureDetector(gestures:)`.
1975    pub fn gestures(mut self, gestures: GestureRecognizerFactories) -> RawGestureDetector {
1976        self.gestures = gestures;
1977        self
1978    }
1979
1980    /// Dart `RawGestureDetector(behavior:)`.
1981    pub fn behavior(mut self, behavior: HitTestBehavior) -> RawGestureDetector {
1982        self.behavior = Some(behavior);
1983        self
1984    }
1985
1986    /// Dart `RawGestureDetector(child:)`.
1987    #[cfg_attr(debug_assertions, track_caller)]
1988    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RawGestureDetector {
1989        self.child = Some(child.into_widget());
1990        self
1991    }
1992}
1993
1994impl StatefulWidget for RawGestureDetector {
1995    type State = RawGestureDetectorState;
1996
1997    fn key(&self) -> Option<&KeyRef> {
1998        self.key.as_ref()
1999    }
2000
2001    fn create_state(&self) -> RawGestureDetectorState {
2002        RawGestureDetectorState {
2003            state: StateData::new(),
2004            recognizers: Some(Vec::new()),
2005        }
2006    }
2007}
2008
2009/// Dart's `Map<Type, GestureRecognizer>`: the recognizers the state keeps, in the order of the
2010/// factories that made them.
2011type Recognizers = Vec<(TypeId, RecognizerRef)>;
2012
2013/// Dart's `map[type]`.
2014fn recognizer_of_type(
2015    recognizers: &[(TypeId, RecognizerRef)],
2016    type_id: TypeId,
2017) -> Option<RecognizerRef> {
2018    recognizers
2019        .iter()
2020        .find(|(candidate, _)| *candidate == type_id)
2021        .map(|(_, recognizer)| recognizer.clone())
2022}
2023
2024/// Dart's `map.containsKey(type)`.
2025fn contains_type(recognizers: &[(TypeId, RecognizerRef)], type_id: TypeId) -> bool {
2026    recognizer_of_type(recognizers, type_id).is_some()
2027}
2028
2029/// State for a [`RawGestureDetector`].
2030pub struct RawGestureDetectorState {
2031    state: StateData<RawGestureDetector>,
2032    /// `None` after [`dispose`](State::dispose), as Dart nulls `_recognizers`.
2033    recognizers: Option<Recognizers>,
2034}
2035
2036impl RawGestureDetectorState {
2037    /// This method can be called after the build phase, during the
2038    /// layout of the nearest descendant `RenderObjectWidget` of the
2039    /// gesture detector, to update the list of active gesture
2040    /// recognizers.
2041    ///
2042    /// The typical use case is `Scrollable`s, which put their viewport
2043    /// in their gesture detector, and then need to know the dimensions
2044    /// of the viewport and the viewport's child to determine whether
2045    /// the gesture detector should be enabled.
2046    ///
2047    /// The argument should follow the same conventions as
2048    /// [`RawGestureDetector::gestures`]. It acts like a temporary replacement for
2049    /// that value until the next build.
2050    pub fn replace_gesture_recognizers(
2051        self: Handle<Self>,
2052        app: &mut App,
2053        gestures: GestureRecognizerFactories,
2054    ) {
2055        debug_assert!(
2056            self.context(app)
2057                .find_render_object(app)
2058                .expect("a mounted RawGestureDetector has a render object")
2059                .owner(app)
2060                .expect("the render object is attached")
2061                .debug_doing_layout(app),
2062            "Unexpected call to replaceGestureRecognizers() method of RawGestureDetectorState. \
2063             The replaceGestureRecognizers() method can only be called during the layout phase. \
2064             To set the gesture recognizers at other times, trigger a new build using setState() \
2065             and provide the new gesture recognizers as constructor arguments to the \
2066             corresponding RawGestureDetector or GestureDetector object."
2067        );
2068        self.sync_all(app, &gestures);
2069    }
2070
2071    fn sync_all(self: Handle<Self>, app: &mut App, gestures: &GestureRecognizerFactories) {
2072        debug_assert!(app.get(self).recognizers.is_some());
2073        let old_recognizers = app
2074            .get_mut(self)
2075            .recognizers
2076            .replace(Vec::new())
2077            .expect("_syncAll after dispose");
2078        for (type_id, factory) in gestures {
2079            debug_assert!(factory.debug_assert_type_matches(*type_id));
2080            debug_assert!(!contains_type(self.recognizers(app), *type_id));
2081            let recognizer = match recognizer_of_type(&old_recognizers, *type_id) {
2082                Some(existing) => existing,
2083                None => factory.constructor(app),
2084            };
2085            self.recognizers_mut(app)
2086                .push((*type_id, recognizer.clone()));
2087            debug_assert!(
2088                recognizer.type_id() == *type_id,
2089                "GestureRecognizerFactory of type {type_id:?} created a GestureRecognizer of \
2090                 type {:?}. The GestureRecognizerFactory must be specialized with the type of \
2091                 the class that it returns from its constructor method.",
2092                recognizer.type_id()
2093            );
2094            factory.initializer(app, recognizer.handle());
2095        }
2096        for (type_id, old_recognizer) in &old_recognizers {
2097            if !contains_type(self.recognizers(app), *type_id) {
2098                old_recognizer.dispose(app);
2099            }
2100        }
2101    }
2102
2103    fn handle_pointer_down(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
2104        debug_assert!(app.get(self).recognizers.is_some());
2105        for recognizer in self.recognizer_handles(app) {
2106            recognizer.add_pointer(app, &event);
2107        }
2108    }
2109
2110    fn handle_pointer_pan_zoom_start(
2111        self: Handle<Self>,
2112        app: &mut App,
2113        event: PointerPanZoomStartEvent,
2114    ) {
2115        debug_assert!(app.get(self).recognizers.is_some());
2116        for recognizer in self.recognizer_handles(app) {
2117            recognizer.add_pointer_pan_zoom(app, &event);
2118        }
2119    }
2120
2121    fn default_behavior(self: Handle<Self>, app: &App) -> HitTestBehavior {
2122        if self.widget(app).child.is_none() {
2123            HitTestBehavior::Translucent
2124        } else {
2125            HitTestBehavior::DeferToChild
2126        }
2127    }
2128
2129    /// Dart's `_recognizers!`.
2130    fn recognizers(self: Handle<Self>, app: &App) -> &[(TypeId, RecognizerRef)] {
2131        app.get(self)
2132            .recognizers
2133            .as_deref()
2134            .expect("_recognizers is null: the state is disposed")
2135    }
2136
2137    /// See [`recognizers`](Self::recognizers).
2138    fn recognizers_mut(self: Handle<Self>, app: &mut App) -> &mut Recognizers {
2139        app.get_mut(self)
2140            .recognizers
2141            .as_mut()
2142            .expect("_recognizers is null: the state is disposed")
2143    }
2144
2145    /// Dart's `_recognizers!.values`, copied out so the loop can hand `app` to each.
2146    fn recognizer_handles(self: Handle<Self>, app: &App) -> Vec<AnyGestureRecognizer> {
2147        self.recognizers(app)
2148            .iter()
2149            .map(|(_, recognizer)| recognizer.handle())
2150            .collect()
2151    }
2152}
2153
2154impl State for RawGestureDetectorState {
2155    type Widget = RawGestureDetector;
2156    crate::state_accessors!();
2157
2158    fn debug_fill_properties(
2159        self: Handle<Self>,
2160        app: &App,
2161        properties: &mut DiagnosticPropertiesBuilder,
2162    ) {
2163        if let Some(recognizers) = app.get(self).recognizers.as_ref() {
2164            let gestures: Vec<String> = recognizers
2165                .iter()
2166                .map(|(_, recognizer)| recognizer.debug_description().to_string())
2167                .collect();
2168            properties
2169                .add(IterableProperty::<String>::new("gestures", gestures).if_empty("<none>"));
2170            properties.add(
2171                IterableProperty::<String>::new(
2172                    "recognizers",
2173                    recognizers
2174                        .iter()
2175                        .map(|(_, recognizer)| format!("{recognizer:?}"))
2176                        .collect::<Vec<String>>(),
2177                )
2178                .with_level(DiagnosticLevel::Fine),
2179            );
2180        } else {
2181            properties.add(waft_foundation::MessageProperty::new("", "DISPOSED"));
2182        }
2183        properties.add(
2184            EnumProperty::<HitTestBehavior>::new("behavior", self.widget(app).behavior)
2185                .default_value(None),
2186        );
2187    }
2188
2189    fn init_state(self: Handle<Self>, app: &mut App) {
2190        let gestures = self.widget(app).gestures.clone();
2191        self.sync_all(app, &gestures);
2192    }
2193
2194    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RawGestureDetector) {
2195        let gestures = self.widget(app).gestures.clone();
2196        self.sync_all(app, &gestures);
2197    }
2198
2199    fn dispose(self: Handle<Self>, app: &mut App) {
2200        let recognizers = app
2201            .get_mut(self)
2202            .recognizers
2203            .take()
2204            .expect("dispose after dispose");
2205        for (_, recognizer) in recognizers {
2206            recognizer.dispose(app);
2207        }
2208    }
2209
2210    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2211        let widget = self.widget(app);
2212        let behavior = widget
2213            .behavior
2214            .unwrap_or_else(|| self.default_behavior(app));
2215        let child = widget.child.clone();
2216        let mut listener = Listener::new()
2217            .on_pointer_down(Rc::new(move |app: &mut App, event: PointerDownEvent| {
2218                self.handle_pointer_down(app, event);
2219            }))
2220            .on_pointer_pan_zoom_start(Rc::new(
2221                move |app: &mut App, event: PointerPanZoomStartEvent| {
2222                    self.handle_pointer_pan_zoom_start(app, event);
2223                },
2224            ))
2225            .behavior(behavior);
2226        if let Some(child) = child {
2227            listener = listener.child(child);
2228        }
2229        listener.into_widget()
2230    }
2231}
2232
2233impl Debug for RawGestureDetectorState {
2234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2235        let Some(recognizers) = &self.recognizers else {
2236            return f.write_str("RawGestureDetectorState(DISPOSED)");
2237        };
2238        let gestures: Vec<&'static str> = recognizers
2239            .iter()
2240            .map(|(_, recognizer)| recognizer.debug_description())
2241            .collect();
2242        f.debug_struct("RawGestureDetectorState")
2243            .field("gestures", &gestures)
2244            .field("recognizers", recognizers)
2245            .finish()
2246    }
2247}
2248
2249#[cfg(test)]
2250mod tests {
2251    use std::cell::{Cell, RefCell};
2252    use std::rc::Rc;
2253    use std::time::Duration;
2254
2255    use waft_embedder::{Matrix4, Offset, SceneBuilder, Size, TextDirection, ViewId};
2256    use waft_foundation::{App, AppCell, Handle, HandleId, Listener};
2257    use waft_gestures::{
2258        DragEndDetails, DragStartDetails, DragUpdateDetails, GestureBinding,
2259        GestureBindingOverridesObject, HitTestResult, K_LONG_PRESS_TIMEOUT, K_PRIMARY_BUTTON,
2260        PointerDownEvent, PointerEvent, PointerMoveEvent, PointerUpEvent, ScaleEndDetails,
2261        ScaleUpdateDetails, TapDownDetails, TapUpDetails,
2262    };
2263    use waft_rendering::{
2264        AnyRenderObject, BoxConstraints, RenderBox, RenderBoxData, RenderConstrainedBox,
2265        RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildMixin,
2266        RenderPointerListener, RenderView,
2267    };
2268
2269    use super::*;
2270    use crate::framework::{AnyElement, Element, LeafRenderObjectWidget, RenderObjectWidget};
2271    use crate::test_harness::Harness;
2272    use crate::widgets::basic::{
2273        CompositedTransformFollower, CompositedTransformTarget, SizedBox, Stack,
2274    };
2275
2276    // ---- the test tree ----
2277
2278    /// Plays `RendererBinding`'s part: hit-tests the harness's render root before the
2279    /// gesture binding adds itself to the path.
2280    struct RootHitTester {
2281        root: RenderHandle<RenderView>,
2282    }
2283
2284    impl GestureBindingOverridesObject for RootHitTester {
2285        fn hit_test_in_view(
2286            self: Handle<Self>,
2287            app: &mut App,
2288            result: &mut HitTestResult,
2289            position: Offset,
2290            _view_id: ViewId,
2291        ) {
2292            let root = app.get(self).root;
2293            root.hit_test(app, result, position);
2294        }
2295
2296        fn will_dispatch_event(
2297            self: Handle<Self>,
2298            _app: &mut App,
2299            _event: &PointerEvent,
2300            _hit_test_result: Option<&HitTestResult>,
2301        ) {
2302        }
2303    }
2304
2305    /// Mounts and pumps `child`, and points the gesture binding's hit test at the tree.
2306    fn mount(app: &mut App, child: WidgetRef) -> Harness {
2307        let harness = Harness::mount(app, child);
2308        harness.pump(app);
2309        let hit_tester = app.create(RootHitTester {
2310            root: harness.render_root(app),
2311        });
2312        GestureBinding::instance(app).set_overrides(app, Rc::new(hit_tester));
2313        harness
2314    }
2315
2316    /// The `RawGestureDetectorState` of the first detector under the root, through the
2317    /// `GestureDetector` when there is one.
2318    fn detector_state(harness: &Harness, app: &App) -> Handle<RawGestureDetectorState> {
2319        let mut element = harness.root.as_element().children(app)[0];
2320        loop {
2321            if let Some(state) = element.state_handle::<RawGestureDetectorState>(app) {
2322                return state;
2323            }
2324            element = element.children(app)[0];
2325        }
2326    }
2327
2328    fn press(app: &mut App, pointer: i64, position: Offset, kind: PointerDeviceKind) {
2329        GestureBinding::instance(app).handle_pointer_event(
2330            app,
2331            PointerEvent::Down(PointerDownEvent {
2332                pointer,
2333                position,
2334                kind,
2335                ..PointerDownEvent::default()
2336            }),
2337        );
2338        app.drain_microtasks();
2339    }
2340
2341    fn release(app: &mut App, pointer: i64, position: Offset, kind: PointerDeviceKind) {
2342        GestureBinding::instance(app).handle_pointer_event(
2343            app,
2344            PointerEvent::Up(PointerUpEvent {
2345                pointer,
2346                position,
2347                kind,
2348                ..PointerUpEvent::default()
2349            }),
2350        );
2351        app.drain_microtasks();
2352    }
2353
2354    fn tap_at(app: &mut App, pointer: i64, position: Offset, kind: PointerDeviceKind) {
2355        press(app, pointer, position, kind);
2356        release(app, pointer, position, kind);
2357    }
2358
2359    /// `SizedBox` in miniature: a box that is never hit by itself.
2360    #[derive(Debug)]
2361    struct Sized {
2362        size: Size,
2363    }
2364
2365    impl RenderObjectWidget for Sized {
2366        type RenderObject = RenderConstrainedBox;
2367
2368        fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
2369            RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
2370        }
2371    }
2372
2373    impl LeafRenderObjectWidget for Sized {}
2374
2375    /// A leaf that runs a callback from `perform_layout`, the way a viewport reaches
2376    /// `replace_gesture_recognizers` during layout.
2377    struct LayoutProbe {
2378        on_layout: Rc<dyn Fn(&mut App)>,
2379    }
2380
2381    impl Debug for LayoutProbe {
2382        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2383            f.write_str("LayoutProbe")
2384        }
2385    }
2386
2387    impl RenderObjectWidget for LayoutProbe {
2388        type RenderObject = RenderLayoutProbe;
2389
2390        fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
2391            RenderHandle::new_box(
2392                app,
2393                RenderLayoutProbe {
2394                    render_object: RenderObjectData::new(),
2395                    render_box: RenderBoxData::new(),
2396                    on_layout: Rc::clone(&self.on_layout),
2397                },
2398            )
2399            .as_object()
2400        }
2401    }
2402
2403    impl LeafRenderObjectWidget for LayoutProbe {}
2404
2405    struct RenderLayoutProbe {
2406        render_object: RenderObjectData,
2407        render_box: RenderBoxData,
2408        on_layout: Rc<dyn Fn(&mut App)>,
2409    }
2410
2411    impl RenderObject for RenderLayoutProbe {
2412        waft_rendering::render_object_accessors!();
2413
2414        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2415            let on_layout = Rc::clone(&self.get(app).on_layout);
2416            on_layout(app);
2417            let size = self.constraints(app).biggest();
2418            self.set_size(app, size);
2419        }
2420    }
2421
2422    impl RenderBox for RenderLayoutProbe {
2423        waft_rendering::render_box_accessors!();
2424    }
2425
2426    /// A tap factory that counts its constructions and initializations and records the
2427    /// recognizer it made.
2428    struct CountingTapFactory {
2429        constructions: Rc<Cell<u32>>,
2430        initializations: Rc<Cell<u32>>,
2431        constructed: Rc<Cell<Option<HandleId>>>,
2432        taps: Rc<Cell<u32>>,
2433    }
2434
2435    impl CountingTapFactory {
2436        fn detector(&self) -> WidgetRef {
2437            let constructions = Rc::clone(&self.constructions);
2438            let constructed = Rc::clone(&self.constructed);
2439            let initializations = Rc::clone(&self.initializations);
2440            let taps = Rc::clone(&self.taps);
2441            let factory = GestureRecognizerFactoryWithHandlers::<TapGestureRecognizer>::new(
2442                move |app| {
2443                    constructions.set(constructions.get() + 1);
2444                    let recognizer = TapGestureRecognizer::new(app);
2445                    constructed.set(Some(recognizer.id()));
2446                    recognizer
2447                },
2448                move |app, instance| {
2449                    initializations.set(initializations.get() + 1);
2450                    let taps = Rc::clone(&taps);
2451                    instance.set_on_tap(
2452                        app,
2453                        Some(Listener::new(move |_app| taps.set(taps.get() + 1))),
2454                    );
2455                },
2456            );
2457            RawGestureDetector::new()
2458                .gestures(vec![(
2459                    TypeId::of::<TapGestureRecognizer>(),
2460                    factory.into_factory(),
2461                )])
2462                .into_widget()
2463        }
2464    }
2465
2466    // ---- GestureDetector ----
2467
2468    /// A widget that changes the shape of its subtree on the press, so the `Listener` under it
2469    /// is re-inflated while the pointer is down.
2470    #[derive(Debug)]
2471    struct SwapOnPress {
2472        ups: Rc<Cell<u32>>,
2473    }
2474
2475    struct SwapOnPressState {
2476        state: StateData<SwapOnPress>,
2477        swapped: bool,
2478    }
2479
2480    impl StatefulWidget for SwapOnPress {
2481        type State = SwapOnPressState;
2482        fn create_state(&self) -> SwapOnPressState {
2483            SwapOnPressState {
2484                state: StateData::new(),
2485                swapped: false,
2486            }
2487        }
2488    }
2489
2490    impl State for SwapOnPressState {
2491        type Widget = SwapOnPress;
2492        crate::state_accessors!();
2493        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2494            let ups = Rc::clone(&self.widget(app).ups);
2495            let listener = crate::Listener::new()
2496                .behavior(HitTestBehavior::Opaque)
2497                .on_pointer_down(Rc::new(move |app: &mut App, _event| {
2498                    self.set_state(app, |state| state.swapped = true);
2499                }))
2500                .on_pointer_up(Rc::new(move |_app: &mut App, _event| {
2501                    ups.set(ups.get() + 1);
2502                }))
2503                .child(Sized {
2504                    size: Size::new(100.0, 100.0),
2505                });
2506            if app.get(self).swapped {
2507                SizedBox::new().child(listener).into_widget()
2508            } else {
2509                listener.into_widget()
2510            }
2511        }
2512    }
2513
2514    fn pointer_listener_under(app: &App, root: AnyElement) -> AnyRenderObject {
2515        let mut pending = vec![root];
2516        while let Some(element) = pending.pop() {
2517            if let Some(object) = element.render_object(app)
2518                && object.downcast::<RenderPointerListener>(app).is_some()
2519            {
2520                return object;
2521            }
2522            pending.extend(element.children(app));
2523        }
2524        panic!("no pointer listener under the root");
2525    }
2526
2527    /// Flutter's gesture binding replays the press's hit-test path for the release, and the
2528    /// `RenderPointerListener` it names stays alive in Dart even after a rebuild disposed it. The
2529    /// arena retains it for as long as the path does, so the release still reaches it.
2530    #[test]
2531    fn a_listener_rebuilt_mid_press_still_receives_the_release() {
2532        let cell = AppCell::new();
2533        let mut app = cell.borrow_mut();
2534        let ups = Rc::new(Cell::new(0));
2535        let harness = mount(
2536            &mut app,
2537            SwapOnPress {
2538                ups: Rc::clone(&ups),
2539            }
2540            .into_widget(),
2541        );
2542        let pressed_listener = pointer_listener_under(&app, harness.root.as_element());
2543
2544        press(
2545            &mut app,
2546            1,
2547            Offset::new(20.0, 30.0),
2548            PointerDeviceKind::Touch,
2549        );
2550        harness.pump(&mut app);
2551        let rebuilt_listener = pointer_listener_under(&app, harness.root.as_element());
2552        assert_ne!(
2553            rebuilt_listener, pressed_listener,
2554            "the press swapped the subtree"
2555        );
2556        assert!(
2557            app.is_disposed(pressed_listener.id()),
2558            "disposed by the rebuild"
2559        );
2560        drop(app);
2561        cell.checkpoint();
2562        let mut app = cell.borrow_mut();
2563        assert!(
2564            app.contains(pressed_listener.id()),
2565            "kept by the cached path"
2566        );
2567
2568        release(
2569            &mut app,
2570            1,
2571            Offset::new(20.0, 30.0),
2572            PointerDeviceKind::Touch,
2573        );
2574        assert_eq!(ups.get(), 1, "the release reached the pressed listener");
2575        drop(app);
2576        cell.checkpoint();
2577        let app = cell.borrow();
2578        assert!(
2579            !app.contains(pressed_listener.id()),
2580            "vacated with the path"
2581        );
2582    }
2583
2584    /// `CompositedTransformFollower`: the follower's child paints and hit-tests where the
2585    /// target is, through the transform between them, once a frame has been composited.
2586    #[test]
2587    fn a_follower_lands_on_its_target_and_is_hit_there() {
2588        let cell = AppCell::new();
2589        let mut app = cell.borrow_mut();
2590        let link = waft_rendering::LayerLink::new(&mut app);
2591        let downs = Rc::new(Cell::new(0));
2592        let on_down = Rc::clone(&downs);
2593        let target = crate::widgets::basic::Transform::new(Matrix4::translation(40.0, 30.0)).child(
2594            CompositedTransformTarget::new(link.clone()).child(Sized {
2595                size: Size::new(10.0, 10.0),
2596            }),
2597        );
2598        let follower = CompositedTransformFollower::new(link)
2599            .offset(Offset::new(5.0, 5.0))
2600            .child(
2601                crate::Listener::new()
2602                    .behavior(HitTestBehavior::Opaque)
2603                    .on_pointer_down(Rc::new(move |_app: &mut App, _event| {
2604                        on_down.set(on_down.get() + 1);
2605                    }))
2606                    .child(Sized {
2607                        size: Size::new(20.0, 20.0),
2608                    }),
2609            );
2610        // The stack fills the view, as an `Overlay` does: a follower is only hit where its
2611        // parent considers itself hittable.
2612        let harness = mount(
2613            &mut app,
2614            SizedBox::expand()
2615                .child(
2616                    Stack::new()
2617                        .text_direction(TextDirection::Ltr)
2618                        .children(vec![target.into_widget(), follower.into_widget()]),
2619                )
2620                .into_widget(),
2621        );
2622        // The follower's transform is established when the frame is composited.
2623        let _scene = harness
2624            .render_root(&app)
2625            .as_object()
2626            .debug_layer(&app)
2627            .expect("painted")
2628            .build_scene(&mut app, SceneBuilder::new());
2629
2630        let listener = pointer_listener_under(&app, harness.root.as_element())
2631            .as_box()
2632            .expect("a box");
2633        assert_eq!(
2634            listener.local_to_global(&app, Offset::ZERO, None),
2635            Offset::new(45.0, 35.0),
2636            "the target's 40,30 plus the follower's 5,5 offset"
2637        );
2638
2639        press(
2640            &mut app,
2641            1,
2642            Offset::new(50.0, 40.0),
2643            PointerDeviceKind::Touch,
2644        );
2645        assert_eq!(downs.get(), 1, "hit where the follower painted");
2646        press(&mut app, 2, Offset::new(5.0, 5.0), PointerDeviceKind::Touch);
2647        assert_eq!(
2648            downs.get(),
2649            1,
2650            "not where the follower would have been unlinked"
2651        );
2652    }
2653
2654    #[test]
2655    fn a_gesture_detector_fires_its_tap_callbacks_end_to_end() {
2656        let cell = AppCell::new();
2657        let mut app = cell.borrow_mut();
2658        let log: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2659        let down_log = Rc::clone(&log);
2660        let up_log = Rc::clone(&log);
2661        let tap_log = Rc::clone(&log);
2662        mount(
2663            &mut app,
2664            GestureDetector::new()
2665                .on_tap_down(Rc::new(move |_app, details: TapDownDetails| {
2666                    down_log
2667                        .borrow_mut()
2668                        .push(format!("down {:?}", details.local_position));
2669                }))
2670                .on_tap_up(Rc::new(move |_app, details: TapUpDetails| {
2671                    up_log
2672                        .borrow_mut()
2673                        .push(format!("up {:?}", details.global_position));
2674                }))
2675                .on_tap(Listener::new(move |_app| {
2676                    tap_log.borrow_mut().push("tap".into())
2677                }))
2678                .behavior(HitTestBehavior::Opaque)
2679                .child(Sized {
2680                    size: Size::new(100.0, 100.0),
2681                })
2682                .into_widget(),
2683        );
2684
2685        tap_at(
2686            &mut app,
2687            1,
2688            Offset::new(20.0, 30.0),
2689            PointerDeviceKind::Touch,
2690        );
2691        assert_eq!(
2692            *log.borrow(),
2693            ["down Offset(20.0, 30.0)", "up Offset(20.0, 30.0)", "tap"]
2694        );
2695    }
2696
2697    #[test]
2698    fn a_gesture_detector_fires_its_double_tap_callbacks_end_to_end() {
2699        let cell = AppCell::new();
2700        let mut app = cell.borrow_mut();
2701        let log: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2702        let down_log = Rc::clone(&log);
2703        let tap_log = Rc::clone(&log);
2704        mount(
2705            &mut app,
2706            GestureDetector::new()
2707                .on_double_tap_down(Rc::new(move |_app, details: TapDownDetails| {
2708                    down_log
2709                        .borrow_mut()
2710                        .push(format!("down {:?}", details.local_position));
2711                }))
2712                .on_double_tap(Listener::new(move |_app| {
2713                    tap_log.borrow_mut().push("double tap".into())
2714                }))
2715                .behavior(HitTestBehavior::Opaque)
2716                .child(Sized {
2717                    size: Size::new(100.0, 100.0),
2718                })
2719                .into_widget(),
2720        );
2721
2722        tap_at(
2723            &mut app,
2724            1,
2725            Offset::new(20.0, 30.0),
2726            PointerDeviceKind::Touch,
2727        );
2728        assert!(log.borrow().is_empty(), "the first tap waits for a second");
2729
2730        drop(app);
2731        cell.elapse(Duration::from_millis(100));
2732        let mut app = cell.borrow_mut();
2733
2734        tap_at(
2735            &mut app,
2736            2,
2737            Offset::new(21.0, 29.0),
2738            PointerDeviceKind::Touch,
2739        );
2740        assert_eq!(*log.borrow(), ["down Offset(21.0, 29.0)", "double tap"]);
2741    }
2742
2743    #[test]
2744    fn a_childless_detector_defaults_to_translucent_and_receives_the_tap() {
2745        let cell = AppCell::new();
2746        let mut app = cell.borrow_mut();
2747        let taps = Rc::new(Cell::new(0));
2748        let count = Rc::clone(&taps);
2749        mount(
2750            &mut app,
2751            GestureDetector::new()
2752                .on_tap(Listener::new(move |_app| count.set(count.get() + 1)))
2753                .into_widget(),
2754        );
2755
2756        tap_at(
2757            &mut app,
2758            1,
2759            Offset::new(10.0, 10.0),
2760            PointerDeviceKind::Touch,
2761        );
2762        assert_eq!(taps.get(), 1);
2763    }
2764
2765    #[test]
2766    fn a_detector_with_a_child_defers_to_it_and_misses_when_the_child_is_not_hit() {
2767        let cell = AppCell::new();
2768        let mut app = cell.borrow_mut();
2769        let taps = Rc::new(Cell::new(0));
2770        let count = Rc::clone(&taps);
2771        mount(
2772            &mut app,
2773            GestureDetector::new()
2774                .on_tap(Listener::new(move |_app| count.set(count.get() + 1)))
2775                .child(Sized {
2776                    size: Size::new(100.0, 100.0),
2777                })
2778                .into_widget(),
2779        );
2780
2781        tap_at(
2782            &mut app,
2783            1,
2784            Offset::new(10.0, 10.0),
2785            PointerDeviceKind::Touch,
2786        );
2787        assert_eq!(taps.get(), 0);
2788    }
2789
2790    #[test]
2791    fn a_long_press_is_recognized_after_the_timeout_and_the_tap_is_cancelled() {
2792        let cell = AppCell::new();
2793        let mut app = cell.borrow_mut();
2794        let log: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2795        let tap_log = Rc::clone(&log);
2796        let cancel_log = Rc::clone(&log);
2797        let long_press_log = Rc::clone(&log);
2798        let up_log = Rc::clone(&log);
2799        mount(
2800            &mut app,
2801            GestureDetector::new()
2802                .on_tap(Listener::new(move |_app| tap_log.borrow_mut().push("tap")))
2803                .on_tap_cancel(Listener::new(move |_app| {
2804                    cancel_log.borrow_mut().push("tap_cancel")
2805                }))
2806                .on_long_press(Listener::new(move |_app| {
2807                    long_press_log.borrow_mut().push("long_press")
2808                }))
2809                .on_long_press_up(Listener::new(move |_app| {
2810                    up_log.borrow_mut().push("long_press_up")
2811                }))
2812                .into_widget(),
2813        );
2814
2815        press(
2816            &mut app,
2817            1,
2818            Offset::new(10.0, 10.0),
2819            PointerDeviceKind::Touch,
2820        );
2821        assert!(log.borrow().is_empty());
2822        drop(app);
2823        cell.elapse(K_LONG_PRESS_TIMEOUT);
2824        let mut app = cell.borrow_mut();
2825        assert_eq!(*log.borrow(), ["tap_cancel", "long_press"]);
2826        release(
2827            &mut app,
2828            1,
2829            Offset::new(10.0, 10.0),
2830            PointerDeviceKind::Touch,
2831        );
2832        assert_eq!(*log.borrow(), ["tap_cancel", "long_press", "long_press_up"]);
2833    }
2834
2835    #[test]
2836    fn supported_devices_is_respected() {
2837        let cell = AppCell::new();
2838        let mut app = cell.borrow_mut();
2839        let taps = Rc::new(Cell::new(0));
2840        let count = Rc::clone(&taps);
2841        mount(
2842            &mut app,
2843            GestureDetector::new()
2844                .on_tap(Listener::new(move |_app| count.set(count.get() + 1)))
2845                .supported_devices(HashSet::from([PointerDeviceKind::Mouse]))
2846                .into_widget(),
2847        );
2848
2849        tap_at(
2850            &mut app,
2851            1,
2852            Offset::new(10.0, 10.0),
2853            PointerDeviceKind::Touch,
2854        );
2855        assert_eq!(taps.get(), 0, "a touch is not a supported device");
2856        tap_at(
2857            &mut app,
2858            2,
2859            Offset::new(10.0, 10.0),
2860            PointerDeviceKind::Mouse,
2861        );
2862        assert_eq!(taps.get(), 1);
2863    }
2864
2865    // ---- RawGestureDetector ----
2866
2867    #[test]
2868    fn rebuilding_reuses_the_recognizer_reruns_the_initializer_and_drops_it_when_removed() {
2869        let cell = AppCell::new();
2870        let mut app = cell.borrow_mut();
2871        let factory = CountingTapFactory {
2872            constructions: Rc::new(Cell::new(0)),
2873            initializations: Rc::new(Cell::new(0)),
2874            constructed: Rc::new(Cell::new(None)),
2875            taps: Rc::new(Cell::new(0)),
2876        };
2877        let harness = mount(&mut app, factory.detector());
2878        assert_eq!(factory.constructions.get(), 1);
2879        assert_eq!(factory.initializations.get(), 1);
2880        let recognizer = factory
2881            .constructed
2882            .get()
2883            .expect("constructed at init_state");
2884
2885        harness.set_child(&mut app, factory.detector());
2886        harness.pump(&mut app);
2887        assert_eq!(factory.constructions.get(), 1, "the recognizer is reused");
2888        assert_eq!(
2889            factory.initializations.get(),
2890            2,
2891            "the initializer runs again"
2892        );
2893        tap_at(
2894            &mut app,
2895            1,
2896            Offset::new(10.0, 10.0),
2897            PointerDeviceKind::Touch,
2898        );
2899        assert_eq!(factory.taps.get(), 1);
2900
2901        harness.set_child(&mut app, RawGestureDetector::new().into_widget());
2902        harness.pump(&mut app);
2903        drop(app);
2904        cell.checkpoint();
2905        let mut app = cell.borrow_mut();
2906        assert!(
2907            !app.contains(recognizer),
2908            "a type no longer listed is disposed"
2909        );
2910        tap_at(
2911            &mut app,
2912            2,
2913            Offset::new(10.0, 10.0),
2914            PointerDeviceKind::Touch,
2915        );
2916        assert_eq!(factory.taps.get(), 1);
2917    }
2918
2919    #[test]
2920    fn replace_gesture_recognizers_swaps_the_recognizers_during_layout() {
2921        let cell = AppCell::new();
2922        let mut app = cell.borrow_mut();
2923        let armed = Rc::new(Cell::new(false));
2924        let state_slot: Rc<Cell<Option<Handle<RawGestureDetectorState>>>> =
2925            Rc::new(Cell::new(None));
2926        let long_presses = Rc::new(Cell::new(0));
2927        let on_layout: Rc<dyn Fn(&mut App)> = {
2928            let armed = Rc::clone(&armed);
2929            let state_slot = Rc::clone(&state_slot);
2930            let long_presses = Rc::clone(&long_presses);
2931            Rc::new(move |app: &mut App| {
2932                if !armed.get() {
2933                    return;
2934                }
2935                let count = Rc::clone(&long_presses);
2936                let factory =
2937                    GestureRecognizerFactoryWithHandlers::<LongPressGestureRecognizer>::new(
2938                        LongPressGestureRecognizer::new,
2939                        move |app, instance| {
2940                            let count = Rc::clone(&count);
2941                            instance.set_on_long_press(
2942                                app,
2943                                Some(Listener::new(move |_app| count.set(count.get() + 1))),
2944                            );
2945                        },
2946                    );
2947                let state = state_slot.get().expect("mounted");
2948                state.replace_gesture_recognizers(
2949                    app,
2950                    vec![(
2951                        TypeId::of::<LongPressGestureRecognizer>(),
2952                        factory.into_factory(),
2953                    )],
2954                );
2955            })
2956        };
2957        let factory = CountingTapFactory {
2958            constructions: Rc::new(Cell::new(0)),
2959            initializations: Rc::new(Cell::new(0)),
2960            constructed: Rc::new(Cell::new(None)),
2961            taps: Rc::new(Cell::new(0)),
2962        };
2963        let tap_factory = GestureRecognizerFactoryWithHandlers::<TapGestureRecognizer>::new(
2964            {
2965                let constructed = Rc::clone(&factory.constructed);
2966                move |app| {
2967                    let recognizer = TapGestureRecognizer::new(app);
2968                    constructed.set(Some(recognizer.id()));
2969                    recognizer
2970                }
2971            },
2972            {
2973                let taps = Rc::clone(&factory.taps);
2974                move |app, instance| {
2975                    let taps = Rc::clone(&taps);
2976                    instance.set_on_tap(
2977                        app,
2978                        Some(Listener::new(move |_app| taps.set(taps.get() + 1))),
2979                    );
2980                }
2981            },
2982        );
2983        let harness = mount(
2984            &mut app,
2985            RawGestureDetector::new()
2986                .gestures(vec![(
2987                    TypeId::of::<TapGestureRecognizer>(),
2988                    tap_factory.into_factory(),
2989                )])
2990                .behavior(HitTestBehavior::Opaque)
2991                .child(LayoutProbe { on_layout })
2992                .into_widget(),
2993        );
2994        let state = detector_state(&harness, &app);
2995        state_slot.set(Some(state));
2996        let tap_recognizer = factory
2997            .constructed
2998            .get()
2999            .expect("constructed at init_state");
3000        assert_eq!(state.recognizers(&app).len(), 1);
3001
3002        // Dirty the probe so the next layout pass, inside `flush_layout`, runs the swap.
3003        armed.set(true);
3004        let listener = harness
3005            .render_root(&app)
3006            .child(&app)
3007            .expect("the detector's listener")
3008            .as_object()
3009            .downcast::<RenderPointerListener>(&app)
3010            .expect("a RenderPointerListener");
3011        listener
3012            .child(&app)
3013            .expect("the probe")
3014            .as_object()
3015            .mark_needs_layout(&mut app);
3016        let pipeline = harness
3017            .render_root(&app)
3018            .as_object()
3019            .owner(&app)
3020            .expect("attached");
3021        pipeline.flush_layout(&mut app);
3022        armed.set(false);
3023        drop(app);
3024        cell.checkpoint();
3025        let mut app = cell.borrow_mut();
3026
3027        assert!(
3028            !app.contains(tap_recognizer),
3029            "the tap recognizer was disposed"
3030        );
3031        let recognizers = state.recognizers(&app);
3032        assert_eq!(recognizers.len(), 1);
3033        assert_eq!(recognizers[0].0, TypeId::of::<LongPressGestureRecognizer>());
3034        assert_eq!(recognizers[0].1.debug_description(), "long press");
3035
3036        press(
3037            &mut app,
3038            1,
3039            Offset::new(10.0, 10.0),
3040            PointerDeviceKind::Touch,
3041        );
3042        drop(app);
3043        cell.elapse(K_LONG_PRESS_TIMEOUT);
3044        let mut app = cell.borrow_mut();
3045        release(
3046            &mut app,
3047            1,
3048            Offset::new(10.0, 10.0),
3049            PointerDeviceKind::Touch,
3050        );
3051        assert_eq!(long_presses.get(), 1);
3052        assert_eq!(factory.taps.get(), 0);
3053    }
3054
3055    #[test]
3056    fn unmounting_disposes_the_recognizers() {
3057        let cell = AppCell::new();
3058        let mut app = cell.borrow_mut();
3059        let harness = mount(
3060            &mut app,
3061            GestureDetector::new()
3062                .on_tap(Listener::new(|_app| {}))
3063                .on_long_press(Listener::new(|_app| {}))
3064                .into_widget(),
3065        );
3066        let state = detector_state(&harness, &app);
3067        let recognizers: Vec<HandleId> = state
3068            .recognizer_handles(&app)
3069            .into_iter()
3070            .map(AnyGestureRecognizer::id)
3071            .collect();
3072        assert_eq!(recognizers.len(), 2);
3073        assert_eq!(
3074            format!("{:?}", app.get(state)),
3075            format!(
3076                "RawGestureDetectorState {{ gestures: [\"tap\", \"long press\"], recognizers: {:?} }}",
3077                state.recognizers(&app)
3078            )
3079        );
3080
3081        harness.set_child(
3082            &mut app,
3083            Sized {
3084                size: Size::new(5.0, 5.0),
3085            }
3086            .into_widget(),
3087        );
3088        harness.pump(&mut app);
3089        drop(app);
3090        cell.checkpoint();
3091        let app = cell.borrow();
3092        for recognizer in recognizers {
3093            assert!(!app.contains(recognizer), "dispose freed the recognizer");
3094        }
3095        assert!(!app.contains(state), "the state is freed with its element");
3096    }
3097
3098    // ---- the vertical drag, pan and scale callbacks ----
3099
3100    fn move_pointer(app: &mut App, pointer: i64, from: Offset, to: Offset) {
3101        GestureBinding::instance(app).handle_pointer_event(
3102            app,
3103            PointerEvent::Move(PointerMoveEvent {
3104                pointer,
3105                position: to,
3106                delta: to - from,
3107                kind: PointerDeviceKind::Touch,
3108                down: true,
3109                buttons: K_PRIMARY_BUTTON,
3110                ..PointerMoveEvent::default()
3111            }),
3112        );
3113        app.drain_microtasks();
3114    }
3115
3116    /// Dart's `Container(color: Color(0xFF00FF00))`. That one is hit by itself and this
3117    /// box is not, so the detectors over it take the hit themselves, as `Opaque`.
3118    fn green_box() -> Sized {
3119        Sized {
3120            size: Size::new(800.0, 600.0),
3121        }
3122    }
3123
3124    #[test]
3125    fn uncontested_scrolls_start_immediately() {
3126        let cell = AppCell::new();
3127        let mut app = cell.borrow_mut();
3128        let did_start_drag = Rc::new(Cell::new(false));
3129        let updated_drag_delta = Rc::new(Cell::new(None));
3130        let did_end_drag = Rc::new(Cell::new(false));
3131        let (started, updated, ended) = (
3132            Rc::clone(&did_start_drag),
3133            Rc::clone(&updated_drag_delta),
3134            Rc::clone(&did_end_drag),
3135        );
3136        mount(
3137            &mut app,
3138            GestureDetector::new()
3139                .on_vertical_drag_start(Rc::new(move |_app, _details: DragStartDetails| {
3140                    started.set(true)
3141                }))
3142                .on_vertical_drag_update(Rc::new(move |_app, details: DragUpdateDetails| {
3143                    updated.set(details.primary_delta)
3144                }))
3145                .on_vertical_drag_end(Rc::new(move |_app, _details: DragEndDetails| {
3146                    ended.set(true)
3147                }))
3148                .behavior(HitTestBehavior::Opaque)
3149                .child(green_box())
3150                .into_widget(),
3151        );
3152        assert!(!did_start_drag.get());
3153        assert_eq!(updated_drag_delta.get(), None);
3154        assert!(!did_end_drag.get());
3155
3156        let first_location = Offset::new(10.0, 10.0);
3157        press(&mut app, 7, first_location, PointerDeviceKind::Touch);
3158        assert!(did_start_drag.replace(false));
3159        assert_eq!(updated_drag_delta.get(), None);
3160        assert!(!did_end_drag.get());
3161
3162        let second_location = Offset::new(10.0, 9.0);
3163        move_pointer(&mut app, 7, first_location, second_location);
3164        assert!(!did_start_drag.get());
3165        assert_eq!(updated_drag_delta.take(), Some(-1.0));
3166        assert!(!did_end_drag.get());
3167
3168        release(&mut app, 7, second_location, PointerDeviceKind::Touch);
3169        assert!(!did_start_drag.get());
3170        assert_eq!(updated_drag_delta.get(), None);
3171        assert!(did_end_drag.replace(false));
3172    }
3173
3174    #[test]
3175    fn match_two_scroll_gestures_in_succession() {
3176        let cell = AppCell::new();
3177        let mut app = cell.borrow_mut();
3178        let gesture_count = Rc::new(Cell::new(0));
3179        let drag_distance = Rc::new(Cell::new(0.0));
3180
3181        let down_location = Offset::new(10.0, 10.0);
3182        // must be far enough to be more than kTouchSlop
3183        let up_location = Offset::new(10.0, 50.0);
3184
3185        let (distance, count) = (Rc::clone(&drag_distance), Rc::clone(&gesture_count));
3186        mount(
3187            &mut app,
3188            GestureDetector::new()
3189                .drag_start_behavior(DragStartBehavior::Down)
3190                .on_vertical_drag_update(Rc::new(move |_app, details: DragUpdateDetails| {
3191                    distance.set(distance.get() + details.primary_delta.unwrap_or(0.0));
3192                }))
3193                .on_vertical_drag_end(Rc::new(move |_app, _details: DragEndDetails| {
3194                    count.set(count.get() + 1);
3195                }))
3196                .on_horizontal_drag_update(Rc::new(|_app, _details: DragUpdateDetails| {
3197                    panic!("gesture should not match");
3198                }))
3199                .on_horizontal_drag_end(Rc::new(|_app, _details: DragEndDetails| {
3200                    panic!("gesture should not match");
3201                }))
3202                .behavior(HitTestBehavior::Opaque)
3203                .child(green_box())
3204                .into_widget(),
3205        );
3206
3207        for _ in 0..2 {
3208            press(&mut app, 7, down_location, PointerDeviceKind::Touch);
3209            move_pointer(&mut app, 7, down_location, up_location);
3210            release(&mut app, 7, up_location, PointerDeviceKind::Touch);
3211        }
3212
3213        assert_eq!(gesture_count.get(), 2);
3214        // delta between down and up, twice
3215        assert_eq!(drag_distance.get(), 40.0 * 2.0);
3216    }
3217
3218    #[test]
3219    fn pan_does_not_crash() {
3220        let cell = AppCell::new();
3221        let mut app = cell.borrow_mut();
3222        let did_start_pan = Rc::new(Cell::new(false));
3223        let pan_delta: Rc<Cell<Option<Offset>>> = Rc::new(Cell::new(None));
3224        let did_end_pan = Rc::new(Cell::new(false));
3225        let (started, delta, ended) = (
3226            Rc::clone(&did_start_pan),
3227            Rc::clone(&pan_delta),
3228            Rc::clone(&did_end_pan),
3229        );
3230        mount(
3231            &mut app,
3232            GestureDetector::new()
3233                .on_pan_start(Rc::new(move |_app, _details: DragStartDetails| {
3234                    started.set(true)
3235                }))
3236                .on_pan_update(Rc::new(move |_app, details: DragUpdateDetails| {
3237                    delta.set(Some(delta.get().unwrap_or(Offset::ZERO) + details.delta));
3238                }))
3239                .on_pan_end(Rc::new(move |_app, _details: DragEndDetails| {
3240                    ended.set(true)
3241                }))
3242                .behavior(HitTestBehavior::Opaque)
3243                .child(green_box())
3244                .into_widget(),
3245        );
3246
3247        assert!(!did_start_pan.get());
3248        assert_eq!(pan_delta.get(), None);
3249        assert!(!did_end_pan.get());
3250
3251        // `WidgetTester.dragFrom(Offset(10, 10), Offset(20, 30))`: through the top edge of
3252        // the drag slop box, then the rest of the way.
3253        let start = Offset::new(10.0, 10.0);
3254        let through_slop = start + Offset::new(20.0 / 1.5, 20.0);
3255        let end = start + Offset::new(20.0, 30.0);
3256        press(&mut app, 1, start, PointerDeviceKind::Touch);
3257        move_pointer(&mut app, 1, start, through_slop);
3258        move_pointer(&mut app, 1, through_slop, end);
3259        release(&mut app, 1, end, PointerDeviceKind::Touch);
3260
3261        assert!(did_start_pan.get());
3262        let pan_delta = pan_delta.get().expect("the pan updated");
3263        assert!((pan_delta.dx() - 20.0).abs() < 1e-9);
3264        assert!((pan_delta.dy() - 30.0).abs() < 1e-9);
3265        assert!(did_end_pan.get());
3266    }
3267
3268    #[test]
3269    #[should_panic(
3270        expected = "Having both a pan gesture recognizer and a scale gesture recognizer is \
3271                    redundant; scale is a superset of pan."
3272    )]
3273    fn constructor_redundant_pan_and_scale() {
3274        let _ = GestureDetector::new()
3275            .on_scale_start(Rc::new(|_app, _details| {}))
3276            .on_pan_start(Rc::new(|_app, _details| {}));
3277    }
3278
3279    #[test]
3280    #[should_panic(
3281        expected = "Simultaneously having a vertical drag gesture recognizer, a horizontal drag \
3282                    gesture recognizer, and a pan gesture recognizer will result in the pan \
3283                    gesture recognizer being ignored, since the other two will catch all drags."
3284    )]
3285    fn constructor_duplicate_drag_recognizer() {
3286        let _ = GestureDetector::new()
3287            .on_vertical_drag_start(Rc::new(|_app, _details| {}))
3288            .on_horizontal_drag_start(Rc::new(|_app, _details| {}))
3289            .on_pan_start(Rc::new(|_app, _details| {}));
3290    }
3291
3292    #[test]
3293    fn a_gesture_detector_reports_a_pinch_end_to_end() {
3294        let cell = AppCell::new();
3295        let mut app = cell.borrow_mut();
3296        let scales = Rc::new(RefCell::new(Vec::new()));
3297        let ended = Rc::new(Cell::new(false));
3298        let (sink, end_flag) = (Rc::clone(&scales), Rc::clone(&ended));
3299        mount(
3300            &mut app,
3301            GestureDetector::new()
3302                .on_scale_update(Rc::new(move |_app, details: ScaleUpdateDetails| {
3303                    sink.borrow_mut().push(details.scale);
3304                }))
3305                .on_scale_end(Rc::new(move |_app, _details: ScaleEndDetails| {
3306                    end_flag.set(true)
3307                }))
3308                .behavior(HitTestBehavior::Opaque)
3309                .child(green_box())
3310                .into_widget(),
3311        );
3312
3313        let first = Offset::new(100.0, 100.0);
3314        let second = Offset::new(200.0, 100.0);
3315        press(&mut app, 1, first, PointerDeviceKind::Touch);
3316        press(&mut app, 2, second, PointerDeviceKind::Touch);
3317        let pinched = Offset::new(250.0, 100.0);
3318        move_pointer(&mut app, 2, second, pinched);
3319        let spread = Offset::new(50.0, 100.0);
3320        move_pointer(&mut app, 1, first, spread);
3321        release(&mut app, 1, spread, PointerDeviceKind::Touch);
3322        release(&mut app, 2, pinched, PointerDeviceKind::Touch);
3323
3324        let reported = scales.borrow();
3325        let last = *reported.last().expect("the pinch updated");
3326        assert!((last - 2.0).abs() < 1e-9, "{reported:?}");
3327        assert!(ended.get());
3328    }
3329}
3330
3331#[cfg(test)]
3332mod diagnostics_tests {
3333    use waft_foundation::AppCell;
3334
3335    use super::*;
3336    use crate::framework::GlobalKey;
3337    use crate::test_harness::Harness;
3338    use crate::testing::describe_properties;
3339
3340    /// `gesture_detector_test.dart`, "RawGestureDetectorState's debugFillProperties" when
3341    /// default: no gestures, and the default behavior is not shown.
3342    #[test]
3343    fn a_raw_gesture_detector_describes_its_gestures() {
3344        let cell = AppCell::new();
3345        let key = GlobalKey::new();
3346        let state = {
3347            let mut app = cell.borrow_mut();
3348            let harness = Harness::mount(
3349                &mut app,
3350                RawGestureDetector::new()
3351                    .key(key.clone().into())
3352                    .into_widget(),
3353            );
3354            harness.pump(&mut app);
3355            key.current_state::<RawGestureDetectorState>(&app)
3356                .expect("the detector is mounted")
3357        };
3358        let app = cell.borrow();
3359        assert_eq!(
3360            describe_properties(|properties| state.debug_fill_properties(&app, properties)),
3361            ["gestures: <none>"]
3362        );
3363    }
3364}