rust_widgets 2.9.3

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Gesture recognizer system — engine, trait, and constants.

use crate::core::Point;
use crate::event::Event;

use super::{
    DoubleTapGesture, FlingGesture, LongPressDragGesture, LongPressGesture, PanGesture,
    PinchGesture, RotateGesture, SwipeGesture, TapGesture, TwoFingerSwipeGesture,
    TwoFingerTapGesture,
};

// ────────────────────────────────────────────
// Constants
// ────────────────────────────────────────────

/// Maximum time delta (ms) between two taps to register as a double-tap.
pub(crate) const DOUBLE_TAP_TIMEOUT_MS: u64 = 400;
/// Minimum hold duration (ms) for long-press detection.
pub(crate) const LONG_PRESS_MIN_MS: u64 = 500;
/// Minimum swipe velocity to activate a swipe gesture.
///
/// **The unit everywhere is logical pixels per second**, matching the public
/// contract documented on `Event::Swipe` / `Event::TwoFingerSwipe` / `Event::Fling`.
/// Timestamps arrive in milliseconds, so each recogniser converts its px/ms ratio
/// by 1000. That conversion is the one thing to keep in step: it was previously
/// applied by `FlingGesture` only, leaving the two swipe recognisers reporting
/// px/ms for a field documented as px/s.
pub(crate) const SWIPE_MIN_VELOCITY: f32 = 500.0;
/// Maximum finger movement (px) to still consider the touch "stationary".
pub(crate) const MAX_STATIONARY_DISTANCE: f32 = 15.0;
/// Maximum finger movement (px) during a long-press hold.
pub(crate) const LONG_PRESS_MAX_MOVE: f32 = 10.0;
/// Minimum distance (px) for a swipe to be recognised.
pub(crate) const SWIPE_MIN_DISTANCE: f32 = 30.0;
/// Minimum total travel (px) before `PanGesture` reports a drag.
///
/// Deliberately smaller than [`SWIPE_MIN_DISTANCE`]: a pan is the continuous,
/// lower-energy gesture and must start responding well before a swipe would fire,
/// while still being large enough that hand tremor during a tap cannot trigger it.
/// `MAX_STATIONARY_DISTANCE` (15 px) is the tap recogniser's own bound and sits
/// between the two, which is what keeps the three recognisers from claiming each
/// other's gestures.
pub(crate) const PAN_MIN_DISTANCE: f32 = 8.0;
/// Maximum time delta (ms) between touch-down and release for a single tap.
pub(crate) const TAP_TIMEOUT_MS: u64 = 300;

// ────────────────────────────────────────────
// Tuning, lifecycle and conflict policy
// ────────────────────────────────────────────

/// Which recogniser a policy or priority applies to.
///
/// A named enum rather than a string so a typo cannot silently configure nothing, and rather
/// than a `TypeId` so a priority table survives a rebuild of the crate (a `TypeId` is not
/// stable across compilations).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GestureKind {
    /// Single tap.
    Tap,
    /// Double tap.
    DoubleTap,
    /// Stationary long press.
    LongPress,
    /// Long press followed by a drag.
    LongPressDrag,
    /// Continuous drag.
    Pan,
    /// Directional swipe.
    Swipe,
    /// High-velocity swipe.
    Fling,
    /// Two-finger tap.
    TwoFingerTap,
    /// Two-finger swipe.
    TwoFingerSwipe,
    /// Two-finger pinch.
    Pinch,
    /// Two-finger rotation.
    Rotate,
    /// A host-supplied recogniser that has no built-in kind.
    Custom(&'static str),
}

impl GestureKind {
    /// The stable name used in diagnostics and priority keys.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Tap => "tap",
            Self::DoubleTap => "double_tap",
            Self::LongPress => "long_press",
            Self::LongPressDrag => "long_press_drag",
            Self::Pan => "pan",
            Self::Swipe => "swipe",
            Self::Fling => "fling",
            Self::TwoFingerTap => "two_finger_tap",
            Self::TwoFingerSwipe => "two_finger_swipe",
            Self::Pinch => "pinch",
            Self::Rotate => "rotate",
            Self::Custom(name) => name,
        }
    }
}

/// Where a recogniser is in its own attempt.
///
/// # Why a state and not only an event
///
/// A recogniser that has not emitted anything is not necessarily idle: a pinch whose fingers
/// are down but whose scale has not crossed the emit threshold is in `Maybe`, and a consumer
/// that wants to preview it (a zoom that follows the fingers before it is committed) needs to
/// know the difference between "nothing is happening" and "a gesture is in progress".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GestureState {
    /// The recogniser is tracking input but has not committed to a gesture.
    #[default]
    Maybe,
    /// The recogniser produced a semantic event on this update.
    Triggered,
    /// The recogniser finished its gesture normally and has reset.
    Finished,
    /// The gesture was cancelled from outside (a touch cancelled, a host sweep).
    Canceled,
}

/// What one update through the chain produced.
#[derive(Debug, Clone)]
pub struct GestureUpdate {
    /// The lifecycle state after the update.
    pub state: GestureState,
    /// The semantic event, when the update produced one.
    pub event: Option<Event>,
    /// Whether the update claims the raw input.
    ///
    /// A recogniser can produce a **preview** without claiming the input — that is the
    /// `consume = false` case — which is what lets a scroll view keep following the fingers
    /// while a pinch previews a zoom.
    pub consume: bool,
}

impl GestureUpdate {
    /// An update with no event, in the given state.
    pub fn none(state: GestureState) -> Self {
        Self { state, event: None, consume: false }
    }

    /// An update carrying `event`, which claims the input.
    pub fn triggered(event: Event) -> Self {
        Self { state: GestureState::Triggered, event: Some(event), consume: true }
    }

    /// A preview event: produced, but not claiming the input.
    pub fn preview(event: Event) -> Self {
        Self { state: GestureState::Maybe, event: Some(event), consume: false }
    }
}

/// The numeric thresholds the recognisers use.
///
/// # Why these are runtime tokens
///
/// The constants are the defaults, not the only possible values: a platform with a different
/// pointer density or a host with a different feel needs a different swipe bar, and a global
/// compile-time constant cannot express that. The tuning value is thread-local for the same
/// reason the widget registry is — recognisers run on the UI thread, and a test can install a
/// tuning value without racing another thread's gestures.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GestureTuning {
    /// Minimum swipe velocity, in logical pixels per second.
    pub swipe_min_velocity: f32,
    /// Minimum swipe travel, in logical pixels.
    pub swipe_min_distance: f32,
    /// Minimum flick speed for a fling, in logical pixels per second.
    ///
    /// Lower than [`Self::swipe_min_velocity`]: a fling is allowed to cover a shorter
    /// distance, so its speed bar is the one a flick actually has to clear.
    pub fling_min_velocity: f32,
    /// Minimum flick travel for a fling, in logical pixels.
    pub fling_min_distance: f32,
    /// Maximum gap between the two taps of a double-tap, in milliseconds.
    pub double_tap_timeout_ms: u64,
    /// Minimum hold for a long press, in milliseconds.
    pub long_press_min_ms: u64,
    /// Maximum press duration for a single tap, in milliseconds.
    pub tap_timeout_ms: u64,
    /// Travel before a pan begins emitting, in logical pixels.
    pub pan_min_distance: f32,
    /// Movement that still counts as stationary, in logical pixels.
    pub max_stationary_distance: f32,
    /// Movement allowed during a long-press hold, in logical pixels.
    pub long_press_max_move: f32,
}

impl Default for GestureTuning {
    fn default() -> Self {
        Self {
            swipe_min_velocity: SWIPE_MIN_VELOCITY,
            swipe_min_distance: SWIPE_MIN_DISTANCE,
            fling_min_velocity: 300.0,
            fling_min_distance: 15.0,
            double_tap_timeout_ms: DOUBLE_TAP_TIMEOUT_MS,
            long_press_min_ms: LONG_PRESS_MIN_MS,
            tap_timeout_ms: TAP_TIMEOUT_MS,
            pan_min_distance: PAN_MIN_DISTANCE,
            max_stationary_distance: MAX_STATIONARY_DISTANCE,
            long_press_max_move: LONG_PRESS_MAX_MOVE,
        }
    }
}

thread_local! {
    /// The tuning in force on this thread, or `None` for the compiled defaults.
    static ACTIVE_TUNING: core::cell::Cell<Option<GestureTuning>> =
        const { core::cell::Cell::new(None) };
}

/// The gesture thresholds in force on this thread.
///
/// Falls back to [`GestureTuning::default`], which is the compiled constant set, so an
/// untouched build recognises exactly what it did before the tokens existed.
pub fn tuning() -> GestureTuning {
    ACTIVE_TUNING.try_with(|cell| cell.get()).ok().flatten().unwrap_or_default()
}

/// Replaces this thread's gesture thresholds; `None` restores the defaults.
///
/// Returns the previous value, so a test can restore what it found.
pub fn set_tuning(value: Option<GestureTuning>) -> Option<GestureTuning> {
    ACTIVE_TUNING.try_with(|cell| cell.replace(value)).ok().flatten()
}

// ────────────────────────────────────────────
// GestureRecognizer trait
// ────────────────────────────────────────────

/// A single gesture recognizer that processes raw events and optionally
/// produces a semantic gesture event.
pub trait GestureRecognizer: std::fmt::Debug + Send {
    /// Feed a raw event into the recognizer.
    ///
    /// Returns `Some(Event)` if the recognizer has completed a gesture,
    /// or `None` if it is still collecting data.
    fn process(&mut self, event: &Event, now_ms: u64) -> Option<Event>;

    /// Reset the recognizer to its initial idle state.
    fn reset(&mut self);

    /// Which gesture this recogniser recognises.
    ///
    /// Used by the priority and conflict configuration; a host-supplied recogniser that does
    /// not override this is configurable only through [`GestureKind::Custom`].
    fn kind(&self) -> GestureKind {
        GestureKind::Custom("gesture")
    }

    /// Where the recogniser is in its current attempt.
    ///
    /// The default is [`GestureState::Maybe`], the neutral answer for a recogniser that does not
    /// track phases: it is never wrong to say "possibly in progress", and a caller that needs a
    /// precise phase opts in.
    fn status(&self) -> GestureState {
        GestureState::Maybe
    }

    /// The in-progress gesture as an event, when the recogniser can describe one.
    ///
    /// This is the **partial delivery** hook: a pinch can report its current scale and centre
    /// before it crosses the commit threshold, a drag can report its displacement, and a host
    /// that wants live preview gets it without the recogniser having to emit a full gesture.
    /// `None` (the default) means the recogniser has nothing to preview.
    fn partial(&self) -> Option<Event> {
        None
    }
}

// ────────────────────────────────────────────
// GestureEngine — chain of recognizers
// ────────────────────────────────────────────

/// One of the eleven built-in recognisers, stored inline in the chain.
///
/// # Why an enum rather than a `Box<dyn GestureRecognizer>` per entry
///
/// [`GestureEngine::new`] used to heap-allocate eleven boxed trait objects per engine, and the
/// event loop builds one engine per interaction target. The built-in chain is fixed and closed, so
/// its concrete types are known here: an enum keeps them inline, removes eleven allocations per
/// target, and still dispatches through the same [`GestureRecognizer`] contract — implemented below
/// by delegation. A host-supplied chain keeps its boxed trait objects, because those types are not
/// known to the crate (see [`GestureEngine::from_recognizers`]).
#[derive(Debug)]
// Variants stay inline on purpose: the fixed built-in chain is what keeps this allocation-free.
#[allow(clippy::large_enum_variant)]
enum StandardRecognizer {
    Tap(TapGesture),
    DoubleTap(DoubleTapGesture),
    LongPress(LongPressGesture),
    LongPressDrag(LongPressDragGesture),
    Pan(PanGesture),
    Swipe(SwipeGesture),
    Fling(FlingGesture),
    TwoFingerTap(TwoFingerTapGesture),
    TwoFingerSwipe(TwoFingerSwipeGesture),
    Pinch(PinchGesture),
    Rotate(RotateGesture),
}

impl GestureRecognizer for StandardRecognizer {
    fn process(&mut self, event: &Event, now_ms: u64) -> Option<Event> {
        match self {
            Self::Tap(recognizer) => recognizer.process(event, now_ms),
            Self::DoubleTap(recognizer) => recognizer.process(event, now_ms),
            Self::LongPress(recognizer) => recognizer.process(event, now_ms),
            Self::LongPressDrag(recognizer) => recognizer.process(event, now_ms),
            Self::Pan(recognizer) => recognizer.process(event, now_ms),
            Self::Swipe(recognizer) => recognizer.process(event, now_ms),
            Self::Fling(recognizer) => recognizer.process(event, now_ms),
            Self::TwoFingerTap(recognizer) => recognizer.process(event, now_ms),
            Self::TwoFingerSwipe(recognizer) => recognizer.process(event, now_ms),
            Self::Pinch(recognizer) => recognizer.process(event, now_ms),
            Self::Rotate(recognizer) => recognizer.process(event, now_ms),
        }
    }

    fn reset(&mut self) {
        match self {
            Self::Tap(recognizer) => recognizer.reset(),
            Self::DoubleTap(recognizer) => recognizer.reset(),
            Self::LongPress(recognizer) => recognizer.reset(),
            Self::LongPressDrag(recognizer) => recognizer.reset(),
            Self::Pan(recognizer) => recognizer.reset(),
            Self::Swipe(recognizer) => recognizer.reset(),
            Self::Fling(recognizer) => recognizer.reset(),
            Self::TwoFingerTap(recognizer) => recognizer.reset(),
            Self::TwoFingerSwipe(recognizer) => recognizer.reset(),
            Self::Pinch(recognizer) => recognizer.reset(),
            Self::Rotate(recognizer) => recognizer.reset(),
        }
    }

    fn kind(&self) -> GestureKind {
        match self {
            Self::Tap(recognizer) => recognizer.kind(),
            Self::DoubleTap(recognizer) => recognizer.kind(),
            Self::LongPress(recognizer) => recognizer.kind(),
            Self::LongPressDrag(recognizer) => recognizer.kind(),
            Self::Pan(recognizer) => recognizer.kind(),
            Self::Swipe(recognizer) => recognizer.kind(),
            Self::Fling(recognizer) => recognizer.kind(),
            Self::TwoFingerTap(recognizer) => recognizer.kind(),
            Self::TwoFingerSwipe(recognizer) => recognizer.kind(),
            Self::Pinch(recognizer) => recognizer.kind(),
            Self::Rotate(recognizer) => recognizer.kind(),
        }
    }

    fn status(&self) -> GestureState {
        match self {
            Self::Tap(recognizer) => recognizer.status(),
            Self::DoubleTap(recognizer) => recognizer.status(),
            Self::LongPress(recognizer) => recognizer.status(),
            Self::LongPressDrag(recognizer) => recognizer.status(),
            Self::Pan(recognizer) => recognizer.status(),
            Self::Swipe(recognizer) => recognizer.status(),
            Self::Fling(recognizer) => recognizer.status(),
            Self::TwoFingerTap(recognizer) => recognizer.status(),
            Self::TwoFingerSwipe(recognizer) => recognizer.status(),
            Self::Pinch(recognizer) => recognizer.status(),
            Self::Rotate(recognizer) => recognizer.status(),
        }
    }

    fn partial(&self) -> Option<Event> {
        match self {
            Self::Tap(recognizer) => recognizer.partial(),
            Self::DoubleTap(recognizer) => recognizer.partial(),
            Self::LongPress(recognizer) => recognizer.partial(),
            Self::LongPressDrag(recognizer) => recognizer.partial(),
            Self::Pan(recognizer) => recognizer.partial(),
            Self::Swipe(recognizer) => recognizer.partial(),
            Self::Fling(recognizer) => recognizer.partial(),
            Self::TwoFingerTap(recognizer) => recognizer.partial(),
            Self::TwoFingerSwipe(recognizer) => recognizer.partial(),
            Self::Pinch(recognizer) => recognizer.partial(),
            Self::Rotate(recognizer) => recognizer.partial(),
        }
    }
}

/// One chain entry: a built-in recogniser stored inline, or a caller-supplied boxed one.
#[derive(Debug)]
// The built-in recogniser is inline by design; boxing it would restore the per-entry allocation.
#[allow(clippy::large_enum_variant)]
enum RecognizerSlot {
    Standard(StandardRecognizer),
    Custom(Box<dyn GestureRecognizer>),
}

impl RecognizerSlot {
    fn as_recognizer(&mut self) -> &mut dyn GestureRecognizer {
        match self {
            Self::Standard(recognizer) => recognizer,
            Self::Custom(recognizer) => recognizer.as_mut(),
        }
    }

    fn as_recognizer_ref(&self) -> &dyn GestureRecognizer {
        match self {
            Self::Standard(recognizer) => recognizer,
            Self::Custom(recognizer) => recognizer.as_ref(),
        }
    }
}

/// An ordered chain of gesture recognisers.
///
/// Events are fed to every recognizer in order. The first recognizer
/// that produces a semantic event wins (subsequent recognizers are
/// skipped for that round).
#[derive(Debug)]
pub struct GestureEngine {
    recognizers: Vec<RecognizerSlot>,
    last_timestamp_ms: u64,
    /// How more than one produced event in one update is resolved.
    conflict: GestureConflictPolicy,
    /// Explicit priorities, consulted only by [`GestureConflictPolicy::Priority`] and
    /// [`GestureConflictPolicy::Exclusive`]. A recogniser absent here has priority `0`.
    priorities: crate::compat::HashMap<GestureKind, i32>,
}

/// How the chain resolves several recognisers producing an event in one update.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GestureConflictPolicy {
    /// The default: the **most specific** event wins (see `is_more_specific`). Explicit
    /// priorities are ignored, so existing chains behave exactly as before.
    #[default]
    Specificity,
    /// The **highest explicit priority** wins, with specificity breaking ties. This is how a host
    /// says "the canvas's pan beats the parent page's scroll" without reordering recognisers.
    Priority,
    /// The highest-priority producer **claims** the update: every other recogniser is reset, so
    /// the losers cannot interleave a second gesture while the winner is running. Useful where
    /// two recognisers would otherwise alternate (a pinch and a rotate on the same fingers).
    Exclusive,
}

impl GestureEngine {
    /// Create an engine pre-populated with the standard recognizers.
    pub fn new() -> Self {
        // Inline enum entries: eleven boxed trait objects per engine became one buffer (G-27).
        let recognizers: Vec<RecognizerSlot> = vec![
            RecognizerSlot::Standard(StandardRecognizer::Tap(TapGesture::new())),
            RecognizerSlot::Standard(StandardRecognizer::DoubleTap(DoubleTapGesture::new())),
            RecognizerSlot::Standard(StandardRecognizer::LongPress(LongPressGesture::new())),
            RecognizerSlot::Standard(
                StandardRecognizer::LongPressDrag(LongPressDragGesture::new()),
            ),
            RecognizerSlot::Standard(StandardRecognizer::Pan(PanGesture::new())),
            RecognizerSlot::Standard(StandardRecognizer::Swipe(SwipeGesture::new())),
            RecognizerSlot::Standard(StandardRecognizer::Fling(FlingGesture::new())),
            RecognizerSlot::Standard(StandardRecognizer::TwoFingerTap(TwoFingerTapGesture::new())),
            RecognizerSlot::Standard(StandardRecognizer::TwoFingerSwipe(
                TwoFingerSwipeGesture::new(),
            )),
            RecognizerSlot::Standard(StandardRecognizer::Pinch(PinchGesture::new())),
            RecognizerSlot::Standard(StandardRecognizer::Rotate(RotateGesture::new())),
        ];
        Self {
            recognizers,
            last_timestamp_ms: 0,
            conflict: GestureConflictPolicy::default(),
            priorities: crate::compat::HashMap::new(),
        }
    }

    /// Builds an engine around a caller-supplied recogniser chain.
    ///
    /// The standard chain is [`Self::new`]; this constructor is for a host that wants its own
    /// recognisers, its own order, or a shorter chain (a canvas that only pans and zooms). All
    /// conflict configuration applies to the supplied chain unchanged.
    pub fn from_recognizers(recognizers: Vec<Box<dyn GestureRecognizer>>) -> Self {
        Self {
            recognizers: recognizers.into_iter().map(RecognizerSlot::Custom).collect(),
            last_timestamp_ms: 0,
            conflict: GestureConflictPolicy::default(),
            priorities: crate::compat::HashMap::new(),
        }
    }

    /// Feeds an event through all recognizers and returns the most specific semantic
    /// gesture event produced, or `None`.
    ///
    /// # Why every recognizer gets a chance
    ///
    /// Returning on the first hit made several recognizers unreachable, because a
    /// recognizer's *input* is often another recognizer's *output*: `DoubleTapGesture`
    /// consumes `Event::Tap`, which `TapGesture` produces, and `TapGesture` sits
    /// earlier in the chain. Returning `Tap` immediately meant `DoubleTapGesture` was
    /// never asked, so `Event::DoubleTap` could not be produced at all.
    ///
    /// # Why "first hit wins" is the wrong rule
    ///
    /// Running every recognizer is necessary but not sufficient: the winner must be
    /// chosen by **specificity**, not by position. `TapGesture` is by construction the
    /// easiest recognizer to satisfy — every completed touch that did not move is a tap
    /// — so it fires on the second tap of a double-tap as well. If position decided the
    /// winner, the richer `DoubleTap` that a later recognizer computed would be
    /// discarded in favour of the coarser earlier `Tap`, and the recognizer chain would
    /// still be effectively unreachable even though every recognizer had run.
    ///
    /// See `GestureEngine::is_more_specific` for the ordering. It is a total order on
    /// the gesture events that can be produced within one call, so the result does not
    /// depend on recognizer registration order.
    ///
    /// # How the derived event reaches its consumers
    ///
    /// A recognizer is offered the raw event first, then (if the raw event produced
    /// nothing) the most recent semantic event. `TapGesture` consumes the raw `TouchEnd`
    /// and yields `Tap`; `DoubleTapGesture` is then handed that `Tap` and can arm itself
    /// or complete a double-tap. The derived event is never offered to recognizers
    /// *ahead* of its producer — feeding backwards would let `TapGesture` re-consume the
    /// `Tap` it just emitted. Each recognizer sees at most two events per call, so this
    /// cannot loop.
    pub fn process(&mut self, event: &Event, now_ms: u64) -> Option<Event> {
        self.last_timestamp_ms = now_ms;
        let mut produced: Option<(Event, i32, usize)> = None;
        let mut derived: Option<Event> = None;
        let conflict = self.conflict;
        let priorities = &self.priorities;
        for (index, slot) in self.recognizers.iter_mut().enumerate() {
            let r = slot.as_recognizer();
            // W-P02: a recogniser that has reported `Finished` and cannot re-arm from this event
            // is skipped. The only built-in recogniser that reports a phase is `Pinch`, which is
            // `Finished` while it has fewer than two contacts: a move in that state can only
            // update a single point and cannot produce a pinch, so the work is pure overhead.
            // Touch begin/end (and the mouse press/release pair) are deliberately *not* skipped —
            // they are what lets the recogniser start the next gesture.
            if !can_rearm_recognizer(event) && r.status() == GestureState::Finished {
                continue;
            }
            // The raw event first: recognizers that track the touch sequence directly
            // (tap, press, swipe, pinch, rotate) read this one.
            let mut hit = r.process(event, now_ms);
            // Then the most recent semantic event, for recognizers that refine another
            // recognizer's output rather than the raw stream.
            if hit.is_none() {
                if let Some(ref derived_event) = derived {
                    hit = r.process(derived_event, now_ms);
                }
            }
            if let Some(gesture_event) = hit {
                let priority = priorities.get(&r.kind()).copied().unwrap_or(0);
                let better = match (conflict, produced.as_ref()) {
                    // No incumbent: any produced event wins.
                    (_, None) => true,
                    (GestureConflictPolicy::Specificity, Some((best, _, _))) => {
                        Self::is_more_specific(&gesture_event, best)
                    }
                    // A higher explicit priority wins; equal priorities fall back to the
                    // specificity rule so the outcome is stable for an unconfigured chain.
                    (GestureConflictPolicy::Priority, Some((best, best_priority, _))) => {
                        priority > *best_priority
                            || (priority == *best_priority
                                && Self::is_more_specific(&gesture_event, best))
                    }
                    // Exclusive uses priority only: the first of the highest-priority
                    // producers wins and the ordering within one priority is registration
                    // order, so an unconfigured exclusive chain is still deterministic.
                    (GestureConflictPolicy::Exclusive, Some((_, best_priority, _))) => {
                        priority > *best_priority
                    }
                };
                if better {
                    produced = Some((gesture_event.clone(), priority, index));
                }
                // The derived event is the *most specific* output of this round, regardless
                // of which producer wins: it is what the later refiners (double-tap building
                // on tap) should see.
                derived = Some(gesture_event);
            }
        }
        if conflict == GestureConflictPolicy::Exclusive {
            if let Some((_, _, winner)) = produced.as_ref() {
                for (index, recognizer) in self.recognizers.iter_mut().enumerate() {
                    if index != *winner {
                        recognizer.as_recognizer().reset();
                    }
                }
            }
        }
        produced.map(|(event, _, _)| event)
    }

    /// Configures how simultaneous producers are resolved.
    ///
    /// [`GestureConflictPolicy::Specificity`] is the default and reproduces the historical
    /// behaviour, so a chain that is not configured here cannot change its output.
    pub fn set_conflict_policy(&mut self, policy: GestureConflictPolicy) {
        self.conflict = policy;
    }

    /// The conflict policy in force.
    pub fn conflict_policy(&self) -> GestureConflictPolicy {
        self.conflict
    }

    /// Sets an explicit priority for `kind`; higher wins under
    /// [`GestureConflictPolicy::Priority`] and [`GestureConflictPolicy::Exclusive`].
    pub fn set_priority(&mut self, kind: GestureKind, priority: i32) {
        self.priorities.insert(kind, priority);
    }

    /// The explicit priority configured for `kind`, or `0` when none was set.
    pub fn priority_of(&self, kind: GestureKind) -> i32 {
        self.priorities.get(&kind).copied().unwrap_or(0)
    }

    /// Feeds one event and reports the lifecycle as well as the event.
    ///
    /// [`Self::process`] answers "did this produce a gesture"; this answers "and what is the
    /// recogniser's state now", which is what a caller needs for partial delivery and for an
    /// outside cancellation. Prefer this entry point when the answer drives UI state; `process`
    /// stays for the loop's existing call site and for tests that only assert the event.
    pub fn process_update(&mut self, event: &Event, now_ms: u64) -> GestureUpdate {
        match self.process(event, now_ms) {
            Some(event) => GestureUpdate::triggered(event),
            None => GestureUpdate::none(GestureState::Maybe),
        }
    }

    /// The in-progress previews of every recogniser that can describe one.
    ///
    /// This is the "partial delivery" half of [`GestureUpdate`]: a pinch reports its current
    /// scale and centre, so a consumer can follow the fingers before the recogniser commits.
    pub fn previews(&self) -> Vec<Event> {
        self.recognizers
            .iter()
            .filter_map(|recognizer| recognizer.as_recognizer_ref().partial())
            .collect()
    }

    /// Cancels any in-progress gesture from outside and resets every recogniser.
    ///
    /// # Why a cancel needs to be reported
    ///
    /// A host that knows the interaction is over (a modal opened, the target was hidden, a
    /// touch sequence was interrupted) must be able to tell a consumer to abandon its preview.
    /// Resetting silently left the consumer with a half-applied zoom and no notification that
    /// it would never be completed.
    pub fn cancel(&mut self) -> GestureUpdate {
        self.reset_all();
        GestureUpdate::none(GestureState::Canceled)
    }

    /// Returns whether `candidate` describes the user's gesture more precisely than
    /// `incumbent`.
    ///
    /// The order, least to most specific:
    ///
    /// 1. `Drag` — the continuous fallback; it fires for any sustained movement, so it
    ///    is the weakest claim on an event.
    /// 2. `Tap` / `LongPress` — a completed discrete gesture, but one that a more
    ///    deliberate gesture can be built on top of.
    /// 3. `Swipe` / `Pinch` / `Rotate` — directional or multi-touch gestures that
    ///    required more from the user than a tap did.
    /// 4. `Fling` — a swipe that also met the higher *velocity* bar, so it is a strictly
    ///    more specific claim on the same motion than `Swipe`. Ordering them equally
    ///    meant a hard flick was reported only as a `Swipe`, because `SwipeGesture` sits
    ///    earlier in the chain and therefore held the incumbent spot.
    /// 5. `DoubleTap` / `TwoFingerTap` / `TwoFingerSwipe` — recognitions that *include*
    ///    another gesture as a precondition, so they are strictly more informed than the
    ///    gesture they subsume.
    ///
    /// Two events of the same rank are equally specific and the incumbent is kept, which
    /// makes the outcome stable regardless of registration order.
    fn is_more_specific(candidate: &Event, incumbent: &Event) -> bool {
        Self::gesture_rank(candidate) > Self::gesture_rank(incumbent)
    }

    /// The specificity rank used by `GestureEngine::is_more_specific`.
    fn gesture_rank(event: &Event) -> u8 {
        match event {
            Event::Drag { .. } => 0,
            Event::Tap { .. } | Event::LongPress { .. } => 1,
            Event::Swipe { .. } | Event::Pinch { .. } | Event::Rotate { .. } => 2,
            Event::Fling { .. } => 3,
            Event::DoubleTap { .. } | Event::TwoFingerTap { .. } | Event::TwoFingerSwipe { .. } => {
                4
            }
            // Anything else the engine may forward (raw touch/mouse events) never
            // outranks a recognised gesture.
            _ => 0,
        }
    }

    /// Reset all recognizers (e.g., when a touch sequence is cancelled).
    pub fn reset_all(&mut self) {
        for r in &mut self.recognizers {
            r.as_recognizer().reset();
        }
    }
}

crate::impl_default_via_new!(GestureEngine);

// ────────────────────────────────────────────
// Helpers
// ────────────────────────────────────────────

/// Euclidean distance between two points.
///
/// The subtraction is widened to `i64` before it happens: `Point` holds `i32`, and a bare `a.x -
/// b.x` on coordinates near the `i32` extremes overflows (aborting in a debug build, wrapping to a
/// wrong — often tiny — distance in release). Widening and then converting to `f32` is exact for
/// the whole `i32` domain.
pub(crate) fn distance(a: Point, b: Point) -> f32 {
    let dx = (a.x as i64 - b.x as i64) as f32;
    let dy = (a.y as i64 - b.y as i64) as f32;
    (dx * dx + dy * dy).sqrt()
}

/// Whether two pointer contacts form a double-tap pair under this thread's tuning.
///
/// # One rule for touch and mouse (W-203)
///
/// `DoubleTapGesture` used to spell the interval and the movement bound out inline, and the
/// event layer had no shared definition at all. This predicate is the single spelling: the touch
/// recogniser feeds it the two `Tap` positions, and the event layer's mouse tracker feeds it the
/// two press positions. A change to [`GestureTuning::double_tap_timeout_ms`] or
/// [`GestureTuning::max_stationary_distance`] therefore moves both input families at once.
///
/// The inputs are `(position, monotonic_ms)` pairs. The time delta saturates, so a caller that
/// supplies the newer reading first gets a zero interval rather than a wrapped one.
pub(crate) fn is_double_tap_pair(first: (Point, u64), second: (Point, u64)) -> bool {
    let tuning = tuning();
    crate::event::double_click::is_double_click_pair(
        first,
        second,
        tuning.double_tap_timeout_ms,
        tuning.max_stationary_distance,
    )
}

/// Whether `event` can change a finished recogniser's state.
///
/// Every touch event is included, not just the begin/end pair: `PinchGesture` reports
/// `Finished` while it holds fewer than two contacts, yet it still tracks the single contact it
/// does hold through `TouchMove`, so skipping moves would give it a stale position when the second
/// finger lands. What the skip actually removes is work for events from an unrelated family
/// (a key press, a resize, a wheel), which no finished recogniser can act on and which the
/// feedback loop used to pay for on every event.
fn can_rearm_recognizer(event: &Event) -> bool {
    matches!(
        event,
        Event::TouchBegin { .. }
            | Event::TouchEnd { .. }
            | Event::TouchMove { .. }
            | Event::MousePress { .. }
            | Event::MouseRelease { .. }
            | Event::Tap { .. }
            | Event::DoubleTap { .. }
            | Event::Timer { .. }
    )
}

/// The per-axis displacement from `from` to `to`, computed without overflow.
///
/// Every recognizer that reports a drag delta did the subtraction inline as `to.x - from.x` on two
/// `i32`s, so a gesture between coordinates near the `i32` extremes overflowed (debug abort, release
/// wrap) even though the *reported* delta fits comfortably in `i32` for any realistic gesture. The
/// subtraction is widened to `i64` and saturated back, so a pathological pair yields a bounded delta
/// rather than a wrapped one. One helper because this is one relationship, stated in five places
/// before.
pub(crate) fn point_delta(from: Point, to: Point) -> (i32, i32) {
    let dx = (to.x as i64 - from.x as i64).clamp(i32::MIN as i64, i32::MAX as i64) as i32;
    let dy = (to.y as i64 - from.y as i64).clamp(i32::MIN as i64, i32::MAX as i64) as i32;
    (dx, dy)
}

/// The per-axis **absolute** displacement between two points, without overflow.
///
/// Equivalent to `(to.x - from.x).abs()` widened to `u32`, but it cannot overflow and — unlike
/// `i32::abs` — cannot panic on `i32::MIN` (whose negation is not representable).
pub(crate) fn point_delta_abs(from: Point, to: Point) -> (u32, u32) {
    let dx = (to.x as i64 - from.x as i64).unsigned_abs().min(u32::MAX as u64) as u32;
    let dy = (to.y as i64 - from.y as i64).unsigned_abs().min(u32::MAX as u64) as u32;
    (dx, dy)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::Event;

    #[test]
    fn gesture_engine_new() {
        let engine = GestureEngine::new();
        assert_eq!(engine.recognizers.len(), 11);
    }

    /// The standard chain is stored inline, not as eleven boxed trait objects (G-27).
    #[test]
    fn the_standard_chain_is_inline() {
        let engine = GestureEngine::new();
        assert!(engine.recognizers.iter().all(|slot| matches!(slot, RecognizerSlot::Standard(_))));
        assert_eq!(engine.previews().len(), 0, "an idle chain has no previews");
    }

    #[test]
    fn gesture_engine_process_none_for_unrelated_event() {
        let mut engine = GestureEngine::new();
        let result = engine.process(
            &Event::MousePress { pos: crate::core::Point::new(0, 0), button: 0, modifiers: 0 },
            0,
        );
        assert!(result.is_none());
    }

    #[test]
    fn gesture_engine_reset_all_clears_state() {
        let mut engine = GestureEngine::new();
        engine.reset_all();
        assert_eq!(engine.recognizers.len(), 11);
    }

    /// Every recogniser must report velocity in the **same** unit: px/s.
    ///
    /// This is the regression guard for a real defect, found while documenting:
    /// `Event::Swipe::velocity` / `TwoFingerSwipe::velocity` / `Fling::velocity` are
    /// all documented as *logical pixels per second*, but `SwipeGesture` and
    /// `TwoFingerSwipeGesture` emitted px/ms while `FlingGesture` emitted px/s — a
    /// 1000x disagreement between two recognisers populating the same field. No test
    /// exercised those paths, so nothing caught it.
    ///
    /// Both recognisers are fed the same physical motion (100 px in 100 ms = 1000
    /// px/s) and must agree.
    #[test]
    fn every_recogniser_reports_velocity_in_pixels_per_second() {
        const START: i32 = 0;
        const END: i32 = 100; // 100 px
        const ELAPSED_MS: u64 = 100; // over 100 ms -> 1000 px/s
        const TOUCH: u64 = 1;
        // Generous band: the point is to catch a wrong *scale*, not to pin rounding.
        const EXPECTED: std::ops::RangeInclusive<f32> = 900.0..=1100.0;

        // Single-finger swipe.
        let mut swipe = SwipeGesture::new();
        assert!(swipe
            .process(&Event::TouchBegin { pos: Point::new(START, START), touch_id: TOUCH }, 0)
            .is_none());
        let swipe_event = swipe
            .process(&Event::TouchEnd { pos: Point::new(END, START), touch_id: TOUCH }, ELAPSED_MS);
        let swipe_velocity = match swipe_event {
            Some(Event::Swipe { velocity, .. }) => velocity,
            other => panic!("expected Event::Swipe over 100px in 100ms, got {other:?}"),
        };

        // Fling over the same physical motion.
        let mut fling = FlingGesture::new();
        assert!(fling
            .process(&Event::TouchBegin { pos: Point::new(START, START), touch_id: TOUCH }, 0)
            .is_none());
        for step in 1..=4u64 {
            fling.process(
                &Event::TouchMove {
                    pos: Point::new(START + (step as i32) * (END - START) / 4, START),
                    touch_id: TOUCH,
                },
                ELAPSED_MS / 4 * step,
            );
        }
        let fling_event = fling
            .process(&Event::TouchEnd { pos: Point::new(END, START), touch_id: TOUCH }, ELAPSED_MS);
        let fling_velocity = match fling_event {
            Some(Event::Fling { velocity, .. }) => velocity,
            other => panic!("expected Event::Fling over 100px in 100ms, got {other:?}"),
        };

        // 100 px in 100 ms is 1000 px/s. A value near 1 means the px/ms ratio was
        // emitted unscaled — the defect this test exists for.
        for (name, velocity) in [("swipe", swipe_velocity), ("fling", fling_velocity.x as f32)] {
            assert!(
                EXPECTED.contains(&velocity),
                "{name} velocity must be ~1000 px/s for 100px in 100ms, got {velocity}. \
                 A value near 1 means px/ms leaked through, which contradicts the \
                 unit documented on Event::Swipe / Event::Fling"
            );
        }
    }

    /// A double tap must reach the consumer as `DoubleTap`, not as two `Tap`s.
    ///
    /// Regression guard for a real defect: `DoubleTapGesture` consumes `Event::Tap`,
    /// which `TapGesture` produces and which sits **earlier** in the chain, so the
    /// engine's "first hit wins, then return" rule meant the double-tap recogniser was
    /// never consulted on the second tap. `Event::DoubleTap` was therefore impossible
    /// to observe through the engine even though the recogniser itself worked, and its
    /// unit tests passed because they drove it directly.
    ///
    /// The second tap must also still be reported as *something* on the first tap of a
    /// pair: a lone tap is a `Tap`.
    #[test]
    fn second_tap_is_reported_as_double_tap() {
        let mut engine = GestureEngine::new();
        let p = Point::new(10, 10);
        // Two taps inside `DOUBLE_TAP_TIMEOUT_MS` (400 ms), same spot.
        assert!(engine.process(&Event::TouchBegin { pos: p, touch_id: 1 }, 0).is_none());
        let first = engine.process(&Event::TouchEnd { pos: p, touch_id: 1 }, 50);
        assert!(
            matches!(first, Some(Event::Tap { .. })),
            "a lone tap must be reported as Tap, got {first:?}"
        );
        assert!(engine.process(&Event::TouchBegin { pos: p, touch_id: 1 }, 100).is_none());
        let second = engine.process(&Event::TouchEnd { pos: p, touch_id: 1 }, 150);
        assert!(
            matches!(second, Some(Event::DoubleTap { .. })),
            "the second tap must upgrade to DoubleTap, got {second:?}"
        );
    }

    /// A single finger must never be reported as a two-finger gesture.
    ///
    /// Regression guard: `TwoFingerTapGesture` accepted a one-finger tap because it
    /// tested `touches.is_empty()` — which is also true once the *only* finger lifts —
    /// and never counted the fingers it had seen. Every ordinary tap was therefore also
    /// reported as `TwoFingerTap`.
    #[test]
    fn one_finger_tap_is_never_two_finger_tap() {
        let mut engine = GestureEngine::new();
        let p = Point::new(10, 10);
        engine.process(&Event::TouchBegin { pos: p, touch_id: 1 }, 0);
        let released = engine.process(&Event::TouchEnd { pos: p, touch_id: 1 }, 50);
        assert!(
            !matches!(released, Some(Event::TwoFingerTap { .. })),
            "one finger cannot make a two-finger tap, got {released:?}"
        );
    }

    /// Two fingers landing and lifting together *are* a two-finger tap.
    ///
    /// The positive half of the pair above: narrowing the recogniser to reject one
    /// finger must not have made it reject two as well.
    #[test]
    fn two_fingers_together_are_two_finger_tap() {
        let mut engine = GestureEngine::new();
        engine.process(&Event::TouchBegin { pos: Point::new(10, 10), touch_id: 1 }, 0);
        engine.process(&Event::TouchBegin { pos: Point::new(30, 10), touch_id: 2 }, 10);
        engine.process(&Event::TouchEnd { pos: Point::new(10, 10), touch_id: 1 }, 40);
        let released =
            engine.process(&Event::TouchEnd { pos: Point::new(30, 10), touch_id: 2 }, 50);
        assert!(
            matches!(released, Some(Event::TwoFingerTap { .. })),
            "two fingers down and up together must be a TwoFingerTap, got {released:?}"
        );
    }

    /// `PanGesture` must not report a drag until the finger has actually travelled.
    ///
    /// Regression guard: `PanGesture` emitted `Drag` on the *first* `TouchMove` with no
    /// displacement threshold. `ScrollArea` scrolls by `Drag::delta`, so a finger that
    /// merely landed and jittered one pixel scrolled the content — the drag and the tap
    /// were indistinguishable to every consumer.
    #[test]
    fn pan_waits_for_the_distance_threshold() {
        let mut engine = GestureEngine::new();
        engine.process(&Event::TouchBegin { pos: Point::new(0, 0), touch_id: 1 }, 0);

        // Below the threshold: jitter, not a drag.
        let jitter = engine.process(&Event::TouchMove { pos: Point::new(3, 0), touch_id: 1 }, 10);
        assert!(jitter.is_none(), "3 px is jitter, so no Drag yet, got {jitter:?}");

        // Past the threshold: a real drag, and it must be reported.
        let drag = engine.process(&Event::TouchMove { pos: Point::new(50, 0), touch_id: 1 }, 20);
        assert!(
            matches!(drag, Some(Event::Drag { .. })),
            "50 px of travel is a drag, got {drag:?}"
        );
    }

    /// Every emitted rotation must be the shortest signed turn, never a full twist.
    ///
    /// Regression guard for a wrap-around defect (principle #76): `angle_between`
    /// returns `atan2`, whose range is `(-pi, pi]`, and the recogniser subtracted two
    /// such angles directly. Crossing the boundary made a real rotation of ~0.05 rad
    /// report a delta near `-2*pi`, i.e. a full turn the user never made.
    #[test]
    fn rotation_never_reports_a_full_turn_for_a_tiny_change() {
        let mut engine = GestureEngine::new();
        // Place the pair so its angle sits just under +pi, then nudge one finger across
        // the boundary. The true change is a fraction of a radian.
        let a = Point::new(1000, 26); // atan2(26, 1000)  ~ +0.026
        let b = Point::new(-1000, -26); // atan2(-26, -1000) ~ -3.116
        engine.process(&Event::TouchBegin { pos: a, touch_id: 1 }, 0);
        engine.process(&Event::TouchBegin { pos: b, touch_id: 2 }, 0);
        let b2 = Point::new(-1000, 26); // atan2(26, -1000) ~ +3.116
        let produced = engine.process(&Event::TouchMove { pos: b2, touch_id: 2 }, 10);

        if let Some(Event::Rotate { angle }) = produced {
            assert!(
                angle.abs() <= core::f32::consts::PI,
                "a rotation must be the shortest signed turn (|angle| <= pi), got {angle}. \
                 A value near 2*pi means the atan2 wrap-around was not normalised"
            );
        }
    }

    // ────────────────────────────────────────
    // Behaviour tests for the recognisers that had none (BLUE16 B-5d).
    //
    // `src/gesture/` previously held four tests, all in `engine.rs`, and they covered
    // the engine's bookkeeping rather than any recogniser's behaviour. Each test below
    // asserts an observable outcome — the event produced and its payload — not merely
    // that a call returned.
    // ────────────────────────────────────────

    /// A hold longer than `LONG_PRESS_MIN_MS` must produce `LongPress` at the press point.
    #[test]
    fn long_hold_produces_long_press() {
        let mut engine = GestureEngine::new();
        let p = Point::new(40, 60);
        assert!(engine.process(&Event::TouchBegin { pos: p, touch_id: 1 }, 0).is_none());

        // The recogniser fires on the first event *after* the timeout, so a timer-like
        // tick drives it — the same way the event loop does.
        let produced = engine.process(&Event::Timer { id: 0 }, LONG_PRESS_MIN_MS + 1);
        match produced {
            Some(Event::LongPress { pos }) => assert_eq!(pos, p),
            other => panic!("a {LONG_PRESS_MIN_MS}ms hold must be a LongPress, got {other:?}"),
        }
    }

    /// A quick, fast flick must produce `Fling` with a px/s velocity on the moved axis.
    #[test]
    fn fast_flick_produces_fling() {
        let mut engine = GestureEngine::new();
        let start = Point::new(0, 0);
        let end = Point::new(200, 0);
        engine.process(&Event::TouchBegin { pos: start, touch_id: 1 }, 0);
        // 200 px in 50 ms = 4000 px/s.
        engine.process(&Event::TouchMove { pos: Point::new(100, 0), touch_id: 1 }, 25);
        let produced = engine.process(&Event::TouchEnd { pos: end, touch_id: 1 }, 50);

        match produced {
            Some(Event::Fling { velocity, .. }) => assert!(
                velocity.x > 0,
                "a flick to the right must have positive x velocity, got {velocity:?}"
            ),
            other => panic!("a 200px flick in 50ms must produce Fling, got {other:?}"),
        }
    }

    /// Moving two fingers apart must produce `Pinch` with a scale above 1.
    ///
    /// This is the multi-touch path, which needs two independent touches to be tracked
    /// at once — the case the single-pointer capture manager could not serve.
    #[test]
    fn fingers_moving_apart_produce_pinch_out() {
        let mut engine = GestureEngine::new();
        engine.process(&Event::TouchBegin { pos: Point::new(100, 100), touch_id: 1 }, 0);
        engine.process(&Event::TouchBegin { pos: Point::new(200, 100), touch_id: 2 }, 0);
        // Double the separation: 100 px -> 200 px.
        let produced =
            engine.process(&Event::TouchMove { pos: Point::new(300, 100), touch_id: 2 }, 10);

        match produced {
            Some(Event::Pinch { scale, .. }) => {
                assert!(scale > 1.0, "spreading the fingers must zoom in (scale > 1), got {scale}")
            }
            other => panic!("two fingers moving apart must produce Pinch, got {other:?}"),
        }
    }

    /// Two fingers moving together must produce `TwoFingerSwipe` on release.
    #[test]
    fn two_fingers_moving_together_produce_two_finger_swipe() {
        let mut engine = GestureEngine::new();
        engine.process(&Event::TouchBegin { pos: Point::new(0, 100), touch_id: 1 }, 0);
        engine.process(&Event::TouchBegin { pos: Point::new(0, 120), touch_id: 2 }, 0);
        // Both fingers travel 150 px right in 50 ms = 3000 px/s.
        engine.process(&Event::TouchMove { pos: Point::new(150, 100), touch_id: 1 }, 25);
        engine.process(&Event::TouchMove { pos: Point::new(150, 120), touch_id: 2 }, 25);
        engine.process(&Event::TouchEnd { pos: Point::new(150, 100), touch_id: 1 }, 50);
        let produced =
            engine.process(&Event::TouchEnd { pos: Point::new(150, 120), touch_id: 2 }, 50);

        assert!(
            matches!(produced, Some(Event::TwoFingerSwipe { .. })),
            "two fingers swiping together must produce TwoFingerSwipe, got {produced:?}"
        );
    }

    /// Two independent contacts must reach `Pinch` — the B-5b acceptance test.
    ///
    /// # Why this is the test that matters for backend touch support
    ///
    /// Adding `WM_TOUCH` / `NSTouch` / GDK touch forwarding is only worth anything if
    /// two separately-identified fingers survive the whole path. Before it, the capture
    /// manager held a single pointer and no backend emitted `TouchBegin`, so
    /// `Pinch`/`Rotate` were unreachable no matter how correct the recognisers were.
    ///
    /// The two `touch_id`s here are what a backend now supplies (Win32 `dwID`, AppKit's
    /// `NSTouch.identity`, GDK's `GdkEventSequence`), so the recogniser sees the same
    /// shape of input the real backends produce.
    #[test]
    fn two_independent_contacts_reach_pinch() {
        let mut engine = GestureEngine::new();
        engine.process(&Event::TouchBegin { pos: Point::new(100, 100), touch_id: 1 }, 0);
        engine.process(&Event::TouchBegin { pos: Point::new(200, 100), touch_id: 2 }, 1);
        // Spread both fingers outward: separation grows from 100 px to 220 px.
        engine.process(&Event::TouchMove { pos: Point::new(40, 100), touch_id: 1 }, 2);
        let produced =
            engine.process(&Event::TouchMove { pos: Point::new(260, 100), touch_id: 2 }, 3);

        match produced {
            Some(Event::Pinch { scale, .. }) => assert!(
                scale > 1.0,
                "spreading two identified fingers must zoom in, got scale {scale}"
            ),
            other => panic!(
                "two independent contacts must reach Pinch; got {other:?}. \
                 If this fails, a backend has stopped emitting TouchBegin/Move with \
                 distinct touch ids"
            ),
        }
    }

    /// Two independent contacts must reach `Rotate` with the quarter turn that happened.
    ///
    /// The companion to the pinch test: it is the other recogniser that needs two
    /// simultaneous fingers, and it is also the one whose angle had to be normalised.
    #[test]
    fn two_independent_contacts_reach_rotate() {
        let mut engine = GestureEngine::new();
        engine.process(&Event::TouchBegin { pos: Point::new(100, 100), touch_id: 1 }, 0);
        engine.process(&Event::TouchBegin { pos: Point::new(200, 100), touch_id: 2 }, 1);
        // Swing the second finger onto the first one's vertical: a quarter turn.
        let produced =
            engine.process(&Event::TouchMove { pos: Point::new(100, 200), touch_id: 2 }, 2);

        match produced {
            Some(Event::Rotate { angle }) => {
                let quarter_turn = core::f32::consts::FRAC_PI_2;
                assert!(
                    (angle - quarter_turn).abs() < 0.01,
                    "a quarter turn must report pi/2 (~1.5708), got {angle}"
                );
            }
            other => panic!("two independent contacts must reach Rotate, got {other:?}"),
        }
    }

    /// An ordinary rotation is reported with the sign the user's motion implies.
    ///
    /// The positive counterpart to the wrap-around test: narrowing the angle to the
    /// shortest turn must not have made ordinary rotations stop being reported, nor
    /// flipped their sign.
    #[test]
    fn ordinary_rotation_is_reported_with_the_correct_sign() {
        let mut engine = GestureEngine::new();
        // Two fingers on the x axis: the pair angle is 0.
        engine.process(&Event::TouchBegin { pos: Point::new(100, 100), touch_id: 1 }, 0);
        engine.process(&Event::TouchBegin { pos: Point::new(200, 100), touch_id: 2 }, 0);
        // Move the second finger to sit directly above the first. The pair angle runs
        // from 0 to atan2(dy, dx) with dy = -100, i.e. -pi/2: a quarter turn. The sign is
        // negative because screen y grows downward, so "up" is the negative direction.
        let produced =
            engine.process(&Event::TouchMove { pos: Point::new(100, 0), touch_id: 2 }, 10);

        match produced {
            Some(Event::Rotate { angle }) => {
                let quarter_turn = core::f32::consts::FRAC_PI_2;
                assert!(
                    (angle + quarter_turn).abs() < 0.01,
                    "a quarter turn to the screen-up direction must report -pi/2 (~-1.5708), \
                     got {angle}"
                );
            }
            other => panic!("a quarter-turn rotation must produce Rotate, got {other:?}"),
        }
    }

    /// N-K-04: `distance` is exact across the whole `i32` domain instead of overflowing.
    ///
    /// The old body subtracted two `i32` coordinates before widening, so points near the extremes
    /// aborted in a debug build (and wrapped to a tiny distance in release). The widened form
    /// computes the true separation.
    #[test]
    fn distance_is_total_across_the_i32_domain() {
        let a = Point::new(i32::MIN, i32::MIN);
        let b = Point::new(i32::MAX, i32::MAX);
        // The diagonal is `sqrt(2) * (2^32 - 1)`; the important part is that it is finite, large,
        // and non-zero, which a wrapped difference could not be.
        let d = distance(a, b);
        assert!(d.is_finite() && d > 1.0e9, "distance overflowed to {d}");

        // A zero-length distance is still zero.
        assert_eq!(distance(Point::new(5, 7), Point::new(5, 7)), 0.0);
        // A 3-4-5 triangle is still exact.
        assert!((distance(Point::new(0, 0), Point::new(3, 4)) - 5.0).abs() < 1.0e-6);
    }

    /// N-K-05 / N-K-06: `point_delta` and `point_delta_abs` do not overflow.
    #[test]
    fn point_delta_helpers_saturate_instead_of_wrapping() {
        let (dx, dy) = point_delta(Point::new(i32::MIN, 0), Point::new(i32::MAX, 0));
        assert_eq!(dx, i32::MAX, "the difference must saturate, not wrap to -1");
        assert_eq!(dy, 0);

        // `abs` of a full-range delta must not panic on the unrepresentable `i32::MIN` negation.
        let (ax, _) = point_delta_abs(Point::new(0, 0), Point::new(i32::MIN, 0));
        assert_eq!(ax, 1u32 << 31, "`|-2^31|` is representable as a `u32`");
        let (bx, _) = point_delta_abs(Point::new(i32::MAX, 0), Point::new(i32::MIN, 0));
        assert_eq!(bx, u32::MAX, "the full-range span saturates at u32::MAX");
    }
}

#[cfg(test)]
mod engine_policy_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    /// A recogniser that produces one fixed event on every input.
    #[derive(Debug)]
    struct Emits {
        event: Event,
        kind: GestureKind,
        resets: Arc<AtomicUsize>,
    }

    impl GestureRecognizer for Emits {
        fn process(&mut self, _event: &Event, _now_ms: u64) -> Option<Event> {
            Some(self.event.clone())
        }

        fn reset(&mut self) {
            self.resets.fetch_add(1, Ordering::SeqCst);
        }

        fn kind(&self) -> GestureKind {
            self.kind
        }
    }

    fn emits(event: Event, kind: GestureKind) -> (Box<dyn GestureRecognizer>, Arc<AtomicUsize>) {
        let resets = Arc::new(AtomicUsize::new(0));
        let recognizer = Emits { event, kind, resets: Arc::clone(&resets) };
        (Box::new(recognizer), resets)
    }

    /// Under the priority policy, the higher explicit priority wins even when the other
    /// event would be more specific.
    #[test]
    fn the_priority_policy_picks_the_higher_configured_priority() {
        let (low, _) = emits(
            Event::LongPress { pos: crate::core::Point::new(0, 0) },
            GestureKind::Custom("low"),
        );
        let (high, _) =
            emits(Event::Tap { pos: crate::core::Point::new(0, 0) }, GestureKind::Custom("high"));
        let mut engine = GestureEngine::from_recognizers(vec![low, high]);
        engine.set_conflict_policy(GestureConflictPolicy::Priority);
        engine.set_priority(GestureKind::Custom("low"), 0);
        engine.set_priority(GestureKind::Custom("high"), 10);

        let produced = engine.process(&Event::Paint, 0);
        assert!(matches!(produced, Some(Event::Tap { .. })), "got {produced:?}");
    }

    /// Exclusive claims the update and resets the losing recognisers.
    #[test]
    fn the_exclusive_policy_resets_the_losers() {
        let (first, first_resets) =
            emits(Event::Tap { pos: crate::core::Point::new(0, 0) }, GestureKind::Custom("first"));
        let (second, _) = emits(
            Event::DoubleTap { pos: crate::core::Point::new(0, 0) },
            GestureKind::Custom("second"),
        );
        let mut engine = GestureEngine::from_recognizers(vec![first, second]);
        engine.set_conflict_policy(GestureConflictPolicy::Exclusive);
        engine.set_priority(GestureKind::Custom("second"), 5);

        let produced = engine.process(&Event::Paint, 0);
        assert!(matches!(produced, Some(Event::DoubleTap { .. })), "got {produced:?}");
        assert_eq!(
            first_resets.load(Ordering::SeqCst),
            1,
            "the loser must be reset so it cannot interleave"
        );
    }

    /// The default policy is the historical specificity rule, so an unconfigured chain is
    /// unaffected by the new configuration surface.
    #[test]
    fn the_default_policy_is_specificity() {
        let engine = GestureEngine::new();
        assert_eq!(engine.conflict_policy(), GestureConflictPolicy::Specificity);
        assert_eq!(engine.priority_of(GestureKind::Pan), 0);
    }

    /// An outside cancel reports the state and resets everything.
    #[test]
    fn cancel_reports_canceled_and_resets_the_chain() {
        let (recognizer, resets) =
            emits(Event::Tap { pos: crate::core::Point::new(0, 0) }, GestureKind::Tap);
        let mut engine = GestureEngine::from_recognizers(vec![recognizer]);
        let update = engine.cancel();
        assert_eq!(update.state, GestureState::Canceled);
        assert!(update.event.is_none());
        assert_eq!(resets.load(Ordering::SeqCst), 1);
    }

    /// The tuning tokens default to the compiled constants and can be overridden per thread.
    #[test]
    fn tuning_tokens_override_the_compiled_defaults() {
        assert_eq!(tuning(), GestureTuning::default());
        let custom = GestureTuning { swipe_min_velocity: 900.0, ..GestureTuning::default() };
        let previous = set_tuning(Some(custom));
        assert_eq!(tuning().swipe_min_velocity, 900.0);
        set_tuning(previous);
        assert_eq!(tuning(), GestureTuning::default());
    }
}