-
Notifications
You must be signed in to change notification settings - Fork 30.4k
Expand file tree
/
Copy pathtap_and_drag.dart
More file actions
1486 lines (1323 loc) · 56 KB
/
tap_and_drag.dart
File metadata and controls
1486 lines (1323 loc) · 56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'package:flutter/widgets.dart';
///
/// @docImport 'arena.dart';
library;
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'constants.dart';
import 'events.dart';
import 'gesture_details.dart';
import 'monodrag.dart';
import 'recognizer.dart';
import 'scale.dart';
import 'tap.dart';
// Examples can assume:
// void setState(VoidCallback fn) { }
// late String _last;
double _getGlobalDistance(PointerEvent event, OffsetPair? originPosition) {
assert(originPosition != null);
final Offset offset = event.position - originPosition!.global;
return offset.distance;
}
// The possible states of a [BaseTapAndDragGestureRecognizer].
//
// The recognizer advances from [ready] to [possible] when it starts tracking
// a pointer in [BaseTapAndDragGestureRecognizer.addAllowedPointer]. Where it advances
// from there depends on the sequence of pointer events that is tracked by the
// recognizer, following the initial [PointerDownEvent]:
//
// * If a [PointerUpEvent] has not been tracked, the recognizer stays in the [possible]
// state as long as it continues to track a pointer.
// * If a [PointerMoveEvent] is tracked that has moved a sufficient global distance
// from the initial [PointerDownEvent] and it came before a [PointerUpEvent], then
// this recognizer moves from the [possible] state to [accepted].
// * If a [PointerUpEvent] is tracked before the pointer has moved a sufficient global
// distance to be considered a drag, then this recognizer moves from the [possible]
// state to [ready].
// * If a [PointerCancelEvent] is tracked then this recognizer moves from its current
// state to [ready].
//
// Once the recognizer has stopped tracking any remaining pointers, the recognizer
// returns to the [ready] state.
enum _DragState {
// The recognizer is ready to start recognizing a drag.
ready,
// The sequence of pointer events seen thus far is consistent with a drag but
// it has not been accepted definitively.
possible,
// The sequence of pointer events has been accepted definitively as a drag.
accepted,
}
/// {@macro flutter.gestures.tap.GestureTapDownCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragDownDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onTapDown].
typedef GestureTapDragDownCallback = void Function(TapDragDownDetails details);
/// Details for [GestureTapDragDownCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onTapDown] callback.
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragDownDetails with Diagnosticable implements PositionedGestureDetails {
/// Creates details for a [GestureTapDragDownCallback].
TapDragDownDetails({
required this.globalPosition,
required this.localPosition,
this.kind,
required this.consecutiveTapCount,
});
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.globalPosition}
@override
final Offset globalPosition;
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.localPosition}
@override
final Offset localPosition;
/// The kind of the device that initiated the event.
final PointerDeviceKind? kind;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(EnumProperty<PointerDeviceKind?>('kind', kind));
properties.add(IntProperty('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.tap.GestureTapUpCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragUpDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onTapUp].
typedef GestureTapDragUpCallback = void Function(TapDragUpDetails details);
/// Details for [GestureTapDragUpCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onTapUp] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragUpDetails with Diagnosticable implements PositionedGestureDetails {
/// Creates details for a [GestureTapDragUpCallback].
TapDragUpDetails({
required this.globalPosition,
required this.localPosition,
required this.kind,
required this.consecutiveTapCount,
});
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.globalPosition}
@override
final Offset globalPosition;
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.localPosition}
@override
final Offset localPosition;
/// The kind of the device that initiated the event.
final PointerDeviceKind kind;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(EnumProperty<PointerDeviceKind?>('kind', kind));
properties.add(IntProperty('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.dragdetails.GestureDragStartCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragStartDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onDragStart].
typedef GestureTapDragStartCallback = void Function(TapDragStartDetails details);
/// Details for [GestureTapDragStartCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onDragStart] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragStartDetails with Diagnosticable implements PositionedGestureDetails {
/// Creates details for a [GestureTapDragStartCallback].
TapDragStartDetails({
required this.globalPosition,
required this.localPosition,
this.sourceTimeStamp,
this.kind,
required this.consecutiveTapCount,
});
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.globalPosition}
@override
final Offset globalPosition;
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.localPosition}
@override
final Offset localPosition;
/// Recorded timestamp of the source pointer event that triggered the drag
/// event.
///
/// Could be null if triggered from proxied events such as accessibility.
final Duration? sourceTimeStamp;
/// The kind of the device that initiated the event.
final PointerDeviceKind? kind;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DiagnosticsProperty<Duration?>('sourceTimeStamp', sourceTimeStamp));
properties.add(EnumProperty<PointerDeviceKind?>('kind', kind));
properties.add(IntProperty('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.dragdetails.GestureDragUpdateCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragUpdateDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onDragUpdate].
typedef GestureTapDragUpdateCallback = void Function(TapDragUpdateDetails details);
/// Details for [GestureTapDragUpdateCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onDragUpdate] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragUpdateDetails with Diagnosticable implements PositionedGestureDetails {
/// Creates details for a [GestureTapDragUpdateCallback].
///
/// If [primaryDelta] is non-null, then its value must match one of the
/// coordinates of [delta] and the other coordinate must be zero.
TapDragUpdateDetails({
required this.globalPosition,
required this.localPosition,
this.sourceTimeStamp,
this.delta = Offset.zero,
this.primaryDelta,
this.kind,
required this.offsetFromOrigin,
required this.localOffsetFromOrigin,
required this.consecutiveTapCount,
}) : assert(
primaryDelta == null ||
(primaryDelta == delta.dx && delta.dy == 0.0) ||
(primaryDelta == delta.dy && delta.dx == 0.0),
);
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.globalPosition}
@override
final Offset globalPosition;
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.localPosition}
@override
final Offset localPosition;
/// Recorded timestamp of the source pointer event that triggered the drag
/// event.
///
/// Could be null if triggered from proxied events such as accessibility.
final Duration? sourceTimeStamp;
/// The amount the pointer has moved in the coordinate space of the event
/// receiver since the previous update.
///
/// If the [GestureTapDragUpdateCallback] is for a one-dimensional drag (e.g.,
/// a horizontal or vertical drag), then this offset contains only the delta
/// in that direction (i.e., the coordinate in the other direction is zero).
///
/// Defaults to zero if not specified in the constructor.
final Offset delta;
/// The amount the pointer has moved along the primary axis in the coordinate
/// space of the event receiver since the previous
/// update.
///
/// If the [GestureTapDragUpdateCallback] is for a one-dimensional drag (e.g.,
/// a horizontal or vertical drag), then this value contains the component of
/// [delta] along the primary axis (e.g., horizontal or vertical,
/// respectively). Otherwise, if the [GestureTapDragUpdateCallback] is for a
/// two-dimensional drag (e.g., a pan), then this value is null.
///
/// Defaults to null if not specified in the constructor.
final double? primaryDelta;
/// The kind of the device that initiated the event.
final PointerDeviceKind? kind;
/// A delta offset from the point where the drag initially contacted
/// the screen to the point where the pointer is currently located in global
/// coordinates (the present [globalPosition]) when this callback is triggered.
///
/// When considering a [GestureRecognizer] that tracks the number of consecutive taps,
/// this offset is associated with the most recent [PointerDownEvent] that occurred.
final Offset offsetFromOrigin;
/// A local delta offset from the point where the drag initially contacted
/// the screen to the point where the pointer is currently located in local
/// coordinates (the present [localPosition]) when this callback is triggered.
///
/// When considering a [GestureRecognizer] that tracks the number of consecutive taps,
/// this offset is associated with the most recent [PointerDownEvent] that occurred.
final Offset localOffsetFromOrigin;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DiagnosticsProperty<Duration?>('sourceTimeStamp', sourceTimeStamp));
properties.add(DiagnosticsProperty<Offset>('delta', delta));
properties.add(DoubleProperty('primaryDelta', primaryDelta));
properties.add(EnumProperty<PointerDeviceKind?>('kind', kind));
properties.add(DiagnosticsProperty<Offset>('offsetFromOrigin', offsetFromOrigin));
properties.add(DiagnosticsProperty<Offset>('localOffsetFromOrigin', localOffsetFromOrigin));
properties.add(IntProperty('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.monodrag.GestureDragEndCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragEndDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onDragEnd].
typedef GestureTapDragEndCallback = void Function(TapDragEndDetails endDetails);
/// Details for [GestureTapDragEndCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onDragEnd] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
class TapDragEndDetails with Diagnosticable implements PositionedGestureDetails {
/// Creates details for a [GestureTapDragEndCallback].
TapDragEndDetails({
this.globalPosition = Offset.zero,
Offset? localPosition,
this.velocity = Velocity.zero,
this.primaryVelocity,
required this.consecutiveTapCount,
}) : assert(
primaryVelocity == null ||
primaryVelocity == velocity.pixelsPerSecond.dx ||
primaryVelocity == velocity.pixelsPerSecond.dy,
),
localPosition = localPosition ?? globalPosition;
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.globalPosition}
@override
final Offset globalPosition;
/// {@macro flutter.gestures.gesturedetails.PositionedGestureDetails.localPosition}
@override
final Offset localPosition;
/// The velocity the pointer was moving when it stopped contacting the screen.
///
/// Defaults to zero if not specified in the constructor.
final Velocity velocity;
/// The velocity the pointer was moving along the primary axis when it stopped
/// contacting the screen, in logical pixels per second.
///
/// If the [GestureTapDragEndCallback] is for a one-dimensional drag (e.g., a
/// horizontal or vertical drag), then this value contains the component of
/// [velocity] along the primary axis (e.g., horizontal or vertical,
/// respectively). Otherwise, if the [GestureTapDragEndCallback] is for a
/// two-dimensional drag (e.g., a pan), then this value is null.
///
/// Defaults to null if not specified in the constructor.
final double? primaryVelocity;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DiagnosticsProperty<Velocity>('velocity', velocity));
properties.add(DoubleProperty('primaryVelocity', primaryVelocity));
properties.add(IntProperty('consecutiveTapCount', consecutiveTapCount));
}
}
/// Signature for when the pointer that previously triggered a
/// [GestureTapDragDownCallback] did not complete.
///
/// Used by [BaseTapAndDragGestureRecognizer.onCancel].
typedef GestureCancelCallback = void Function();
// A mixin for [OneSequenceGestureRecognizer] that tracks the number of taps
// that occur in a series of [PointerEvent]s and the most recent set of
// [LogicalKeyboardKey]s pressed on the most recent tap down.
//
// A tap is tracked as part of a series of taps if:
//
// 1. The elapsed time between when a [PointerUpEvent] and the subsequent
// [PointerDownEvent] does not exceed [kDoubleTapTimeout].
// 2. The delta between the position tapped in the global coordinate system
// and the position that was tapped previously must be less than or equal
// to [kDoubleTapSlop].
//
// This mixin's state, i.e. the series of taps being tracked is reset when
// a tap is tracked that does not meet any of the specifications stated above.
mixin _TapStatusTrackerMixin on OneSequenceGestureRecognizer {
// Public state available to [OneSequenceGestureRecognizer].
// The [PointerDownEvent] that was most recently tracked in [addAllowedPointer].
//
// This value will be null if a [PointerDownEvent] has not been tracked yet in
// [addAllowedPointer] or the timer between two taps has elapsed.
//
// This value is only reset when the timer between a [PointerUpEvent] and the
// [PointerDownEvent] times out or when a new [PointerDownEvent] is tracked in
// [addAllowedPointer].
PointerDownEvent? get currentDown => _down;
// The [PointerUpEvent] that was most recently tracked in [handleEvent].
//
// This value will be null if a [PointerUpEvent] has not been tracked yet in
// [handleEvent] or the timer between two taps has elapsed.
//
// This value is only reset when the timer between a [PointerUpEvent] and the
// [PointerDownEvent] times out or when a new [PointerDownEvent] is tracked in
// [addAllowedPointer].
PointerUpEvent? get currentUp => _up;
// The number of consecutive taps that the most recently tracked [PointerDownEvent]
// in [currentDown] represents.
//
// This value defaults to zero, meaning a tap series is not currently being tracked.
//
// When this value is greater than zero it means [addAllowedPointer] has run
// and at least one [PointerDownEvent] belongs to the current series of taps
// being tracked.
//
// [addAllowedPointer] will either increment this value by `1` or set the value to `1`
// depending if the new [PointerDownEvent] is determined to be in the same series as the
// tap that preceded it. If too much time has elapsed between two taps, the recognizer has lost
// in the arena, the gesture has been cancelled, or the recognizer is being disposed then
// this value will be set to `0`, and a new series will begin.
int get consecutiveTapCount => _consecutiveTapCount;
// The upper limit for the [consecutiveTapCount]. When this limit is reached
// all tap related state is reset and a new tap series is tracked.
//
// If this value is null, [consecutiveTapCount] can grow infinitely large.
int? get maxConsecutiveTap;
// Private tap state tracked.
PointerDownEvent? _down;
PointerUpEvent? _up;
int _consecutiveTapCount = 0;
OffsetPair? _originPosition;
int? _previousButtons;
// For timing taps.
Timer? _consecutiveTapTimer;
Offset? _lastTapOffset;
/// {@macro flutter.gestures.selectionrecognizers.TextSelectionGestureDetector.onTapTrackStart}
VoidCallback? onTapTrackStart;
/// {@macro flutter.gestures.selectionrecognizers.TextSelectionGestureDetector.onTapTrackReset}
VoidCallback? onTapTrackReset;
// When tracking a tap, the [consecutiveTapCount] is incremented if the given tap
// falls under the tolerance specifications and reset to 1 if not.
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
if (_consecutiveTapTimer != null && !_consecutiveTapTimer!.isActive) {
_tapTrackerReset();
}
if (maxConsecutiveTap == _consecutiveTapCount) {
_tapTrackerReset();
}
_up = null;
if (_down != null && !_representsSameSeries(event)) {
// The given tap does not match the specifications of the series of taps being tracked,
// reset the tap count and related state.
_consecutiveTapCount = 1;
} else {
_consecutiveTapCount += 1;
}
_consecutiveTapTimerStop();
// `_down` must be assigned in this method instead of [handleEvent],
// because [acceptGesture] might be called before [handleEvent],
// which may rely on `_down` to initiate a callback.
_trackTap(event);
}
@override
void handleEvent(PointerEvent event) {
if (event is PointerMoveEvent) {
final double computedSlop = computeHitSlop(event.kind, gestureSettings);
final bool isSlopPastTolerance = _getGlobalDistance(event, _originPosition) > computedSlop;
if (isSlopPastTolerance) {
_consecutiveTapTimerStop();
_previousButtons = null;
_lastTapOffset = null;
}
} else if (event is PointerUpEvent) {
_up = event;
if (_down != null) {
_consecutiveTapTimerStop();
_consecutiveTapTimerStart();
}
} else if (event is PointerCancelEvent) {
_tapTrackerReset();
}
}
@override
void rejectGesture(int pointer) {
_tapTrackerReset();
}
@override
void dispose() {
_tapTrackerReset();
super.dispose();
}
void _trackTap(PointerDownEvent event) {
_down = event;
_previousButtons = event.buttons;
_lastTapOffset = event.position;
_originPosition = OffsetPair(local: event.localPosition, global: event.position);
onTapTrackStart?.call();
}
bool _hasSameButton(int buttons) {
assert(_previousButtons != null);
if (buttons == _previousButtons!) {
return true;
} else {
return false;
}
}
bool _isWithinConsecutiveTapTolerance(Offset secondTapOffset) {
if (_lastTapOffset == null) {
return false;
}
final Offset difference = secondTapOffset - _lastTapOffset!;
return difference.distance <= kDoubleTapSlop;
}
bool _representsSameSeries(PointerDownEvent event) {
return _consecutiveTapTimer != null &&
_isWithinConsecutiveTapTolerance(event.position) &&
_hasSameButton(event.buttons);
}
void _consecutiveTapTimerStart() {
_consecutiveTapTimer ??= Timer(kDoubleTapTimeout, _consecutiveTapTimerTimeout);
}
void _consecutiveTapTimerStop() {
if (_consecutiveTapTimer != null) {
_consecutiveTapTimer!.cancel();
_consecutiveTapTimer = null;
}
}
void _consecutiveTapTimerTimeout() {
// The consecutive tap timer may time out before a tap down/tap up event is
// fired. In this case we should not reset the tap tracker state immediately.
// Instead we should reset the tap tracker on the next call to [addAllowedPointer],
// if the timer is no longer active.
}
void _tapTrackerReset() {
// The timer has timed out, i.e. the time between a [PointerUpEvent] and the subsequent
// [PointerDownEvent] exceeded the duration of [kDoubleTapTimeout], so the tap belonging
// to the [PointerDownEvent] cannot be considered part of the same tap series as the
// previous [PointerUpEvent].
_consecutiveTapTimerStop();
_previousButtons = null;
_originPosition = null;
_lastTapOffset = null;
_consecutiveTapCount = 0;
_down = null;
_up = null;
onTapTrackReset?.call();
}
}
/// A base class for gesture recognizers that recognize taps and movements.
///
/// Takes on the responsibilities of [TapGestureRecognizer] and
/// [DragGestureRecognizer] in one [GestureRecognizer].
///
/// ### Gesture arena behavior
///
/// [BaseTapAndDragGestureRecognizer] competes on the pointer events of
/// [kPrimaryButton] only when it has at least one non-null `onTap*`
/// or `onDrag*` callback.
///
/// It will declare defeat if it determines that a gesture is not a
/// tap (e.g. if the pointer is dragged too far while it's contacting the
/// screen) or a drag (e.g. if the pointer was not dragged far enough to
/// be considered a drag.
///
/// This recognizer will not immediately declare victory for every tap that it
/// recognizes, but it declares victory for every drag.
///
/// The recognizer will declare victory when all other recognizer's in
/// the arena have lost, if the timer of [kPressTimeout] elapses and a tap
/// series greater than 1 is being tracked, or until the pointer has moved
/// a sufficient global distance from the origin to be considered a drag.
///
/// If this recognizer loses the arena (either by declaring defeat or by
/// another recognizer declaring victory) while the pointer is contacting the
/// screen, it will fire [onCancel] instead of [onTapUp] or [onDragEnd].
///
/// ### When competing with `TapGestureRecognizer` and `DragGestureRecognizer`
///
/// Similar to [TapGestureRecognizer] and [DragGestureRecognizer],
/// [BaseTapAndDragGestureRecognizer] will not aggressively declare victory when
/// it detects a tap, so when it is competing with those gesture recognizers and
/// others it has a chance of losing. Similarly, when `eagerVictoryOnDrag` is set
/// to `false`, this recognizer will not aggressively declare victory when it
/// detects a drag. By default, `eagerVictoryOnDrag` is set to `true`, so this
/// recognizer will aggressively declare victory when it detects a drag.
///
/// When competing against [TapGestureRecognizer], if the pointer does not move past the tap
/// tolerance, then the recognizer that entered the arena first will win. In this case the
/// gesture detected is a tap. If the pointer does travel past the tap tolerance then this
/// recognizer will be declared winner by default. The gesture detected in this case is a drag.
///
/// When competing against [DragGestureRecognizer], if the pointer does not move a sufficient
/// global distance to be considered a drag, the recognizers will tie in the arena. If the
/// pointer does travel enough distance then the recognizer that entered the arena
/// first will win. The gesture detected in this case is a drag.
///
/// {@tool dartpad}
/// This example shows how to use the [TapAndPanGestureRecognizer] along with a
/// [RawGestureDetector] to scale a Widget.
///
/// ** See code in examples/api/lib/gestures/tap_and_drag/tap_and_drag.0.dart **
/// {@end-tool}
///
/// {@tool snippet}
///
/// This example shows how to hook up [TapAndPanGestureRecognizer]s' to nested
/// [RawGestureDetector]s'. It assumes that the code is being used inside a [State]
/// object with a `_last` field that is then displayed as the child of the gesture detector.
///
/// In this example, if the pointer has moved past the drag threshold, then the
/// the first [TapAndPanGestureRecognizer] instance to receive the [PointerEvent]
/// will win the arena because the recognizer will immediately declare victory.
///
/// The first one to receive the event in the example will depend on where on both
/// containers the pointer lands first. If your pointer begins in the overlapping
/// area of both containers, then the inner-most widget will receive the event first.
/// If your pointer begins in the yellow container then it will be the first to
/// receive the event.
///
/// If the pointer has not moved past the drag threshold, then the first recognizer
/// to enter the arena will win (i.e. they both tie and the gesture arena will call
/// [GestureArenaManager.sweep] so the first member of the arena will win).
///
/// ```dart
/// RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// TapAndPanGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapAndPanGestureRecognizer>(
/// () => TapAndPanGestureRecognizer(),
/// (TapAndPanGestureRecognizer instance) {
/// instance
/// ..onTapDown = (TapDragDownDetails details) { setState(() { _last = 'down_a'; }); }
/// ..onDragStart = (TapDragStartDetails details) { setState(() { _last = 'drag_start_a'; }); }
/// ..onDragUpdate = (TapDragUpdateDetails details) { setState(() { _last = 'drag_update_a'; }); }
/// ..onDragEnd = (TapDragEndDetails details) { setState(() { _last = 'drag_end_a'; }); }
/// ..onTapUp = (TapDragUpDetails details) { setState(() { _last = 'up_a'; }); }
/// ..onCancel = () { setState(() { _last = 'cancel_a'; }); };
/// },
/// ),
/// },
/// child: Container(
/// width: 300.0,
/// height: 300.0,
/// color: Colors.yellow,
/// alignment: Alignment.center,
/// child: RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// TapAndPanGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapAndPanGestureRecognizer>(
/// () => TapAndPanGestureRecognizer(),
/// (TapAndPanGestureRecognizer instance) {
/// instance
/// ..onTapDown = (TapDragDownDetails details) { setState(() { _last = 'down_b'; }); }
/// ..onDragStart = (TapDragStartDetails details) { setState(() { _last = 'drag_start_b'; }); }
/// ..onDragUpdate = (TapDragUpdateDetails details) { setState(() { _last = 'drag_update_b'; }); }
/// ..onDragEnd = (TapDragEndDetails details) { setState(() { _last = 'drag_end_b'; }); }
/// ..onTapUp = (TapDragUpDetails details) { setState(() { _last = 'up_b'; }); }
/// ..onCancel = () { setState(() { _last = 'cancel_b'; }); };
/// },
/// ),
/// },
/// child: Container(
/// width: 150.0,
/// height: 150.0,
/// color: Colors.blue,
/// child: Text(_last),
/// ),
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognizer
with _TapStatusTrackerMixin {
/// Creates a tap and drag gesture recognizer.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
BaseTapAndDragGestureRecognizer({
super.debugOwner,
super.supportedDevices,
super.allowedButtonsFilter,
this.eagerVictoryOnDrag = true,
}) : _deadline = kPressTimeout,
dragStartBehavior = DragStartBehavior.start;
/// Configure the behavior of offsets passed to [onDragStart].
///
/// If set to [DragStartBehavior.start], the [onDragStart] callback will be called
/// with the position of the pointer at the time this gesture recognizer won
/// the arena. If [DragStartBehavior.down], [onDragStart] will be called with
/// the position of the first detected down event for the pointer. When there
/// are no other gestures competing with this gesture in the arena, there's
/// no difference in behavior between the two settings.
///
/// For more information about the gesture arena:
/// https://flutter.dev/to/gesture-disambiguation
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which includes more details and an example.
DragStartBehavior dragStartBehavior;
/// The frequency at which the [onDragUpdate] callback is called.
///
/// The value defaults to null, meaning there is no delay for [onDragUpdate] callback.
Duration? dragUpdateThrottleFrequency;
/// An upper bound for the amount of taps that can belong to one tap series.
///
/// When this limit is reached the series of taps being tracked by this
/// recognizer will be reset.
@override
int? maxConsecutiveTap;
/// Whether this recognizer eagerly declares victory when it has detected
/// a drag.
///
/// When this value is `false`, this recognizer will wait until it is the last
/// recognizer in the gesture arena before declaring victory on a drag.
///
/// Defaults to `true`.
bool eagerVictoryOnDrag;
/// {@macro flutter.gestures.tap.TapGestureRecognizer.onTapDown}
///
/// This triggers after the down event, once a short timeout ([kPressTimeout]) has
/// elapsed, or once the gestures has won the arena, whichever comes first.
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [TapDragDownDetails] object.
///
/// {@template flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
/// The number of consecutive taps, and the keys that were pressed on tap down
/// are also provided in the callback's `details` argument.
/// {@endtemplate}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragDownDetails], which is passed as an argument to this callback.
GestureTapDragDownCallback? onTapDown;
/// {@macro flutter.gestures.tap.TapGestureRecognizer.onTapUp}
///
/// This triggers on the up event, if the recognizer wins the arena with it
/// or has previously won.
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [TapDragUpDetails] object.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragUpDetails], which is passed as an argument to this callback.
GestureTapDragUpCallback? onTapUp;
/// {@macro flutter.gestures.monodrag.DragGestureRecognizer.onStart}
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [TapDragStartDetails] object. The [dragStartBehavior]
/// determines this position.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragStartDetails], which is passed as an argument to this callback.
GestureTapDragStartCallback? onDragStart;
/// {@macro flutter.gestures.monodrag.DragGestureRecognizer.onUpdate}
///
/// The distance traveled by the pointer since the last update is provided in
/// the callback's `details` argument, which is a [TapDragUpdateDetails] object.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragUpdateDetails], which is passed as an argument to this callback.
GestureTapDragUpdateCallback? onDragUpdate;
/// {@macro flutter.gestures.monodrag.DragGestureRecognizer.onEnd}
///
/// The velocity is provided in the callback's `details` argument, which is a
/// [TapDragEndDetails] object.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragEndDetails], which is passed as an argument to this callback.
GestureTapDragEndCallback? onDragEnd;
/// The pointer that previously triggered [onTapDown] did not complete.
///
/// This is called when a [PointerCancelEvent] is tracked when the [onTapDown] callback
/// was previously called.
///
/// It may also be called if a [PointerUpEvent] is tracked after the pointer has moved
/// past the tap tolerance but not past the drag tolerance, and the recognizer has not
/// yet won the arena.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
GestureCancelCallback? onCancel;
// Tap related state.
bool _pastSlopTolerance = false;
bool _sentTapDown = false;
bool _wonArenaForPrimaryPointer = false;
// Primary pointer being tracked by this recognizer.
int? _primaryPointer;
Timer? _deadlineTimer;
// The recognizer will call [onTapDown] after this amount of time has elapsed
// since starting to track the primary pointer.
//
// [onTapDown] will not be called if the primary pointer is
// accepted, rejected, or all pointers are up or canceled before [_deadline].
final Duration _deadline;
// Drag related state.
_DragState _dragState = _DragState.ready;
PointerEvent? _start;
late OffsetPair _initialPosition;
late OffsetPair _currentPosition;
late double _globalDistanceMoved;
late double _globalDistanceMovedAllAxes;
// For drag update throttle.
TapDragUpdateDetails? _lastDragUpdateDetails;
Timer? _dragUpdateThrottleTimer;
final Set<int> _acceptedActivePointers = <int>{};
Offset _getDeltaForDetails(Offset delta);
double? _getPrimaryValueFromOffset(Offset value);
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind);
// Drag updates may require throttling to avoid excessive updating, such as for text layouts in text
// fields. The frequency of invocations is controlled by the [dragUpdateThrottleFrequency].
//
// Once the drag gesture ends, any pending drag update will be fired
// immediately. See [_checkDragEnd].
void _handleDragUpdateThrottled() {
assert(_lastDragUpdateDetails != null);
if (onDragUpdate != null) {
invokeCallback<void>('onDragUpdate', () => onDragUpdate!(_lastDragUpdateDetails!));
}
_dragUpdateThrottleTimer = null;
_lastDragUpdateDetails = null;
}
@override
bool isPointerAllowed(PointerEvent event) {
if (_primaryPointer == null) {
switch (event.buttons) {
case kPrimaryButton:
if (onTapDown == null &&
onDragStart == null &&
onDragUpdate == null &&
onDragEnd == null &&
onTapUp == null &&
onCancel == null) {
return false;
}
default:
return false;
}
} else {
if (event.pointer != _primaryPointer) {
return false;
}
}
return super.isPointerAllowed(event as PointerDownEvent);
}
@override
void addAllowedPointer(PointerDownEvent event) {
if (_dragState == _DragState.ready) {
super.addAllowedPointer(event);
_primaryPointer = event.pointer;
_globalDistanceMoved = 0.0;
_globalDistanceMovedAllAxes = 0.0;
_dragState = _DragState.possible;
_initialPosition = OffsetPair(global: event.position, local: event.localPosition);
_currentPosition = _initialPosition;
_deadlineTimer = Timer(_deadline, () => _didExceedDeadlineWithEvent(event));
}
}
@override
void handleNonAllowedPointer(PointerDownEvent event) {
// There can be multiple drags simultaneously. Their effects are combined.
if (event.buttons != kPrimaryButton) {
if (!_wonArenaForPrimaryPointer) {
super.handleNonAllowedPointer(event);
}
}
}
@override
void acceptGesture(int pointer) {
if (pointer != _primaryPointer) {
return;
}
_stopDeadlineTimer();
assert(!_acceptedActivePointers.contains(pointer));
_acceptedActivePointers.add(pointer);
// Called when this recognizer is accepted by the [GestureArena].
if (currentDown != null) {