rust_widgets 2.9.2

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
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Event loop implementation.
use super::double_click::DoubleClickTracker;
use super::event_queue::{EventQueue, EventSender};
use super::key_repeat::{with_dispatch_repeat, KeyRepeatState};
use super::timer::IdleTask;
use super::timer::TimerManager;
#[cfg(all(feature = "touch", not(alloc_frugal)))]
use super::translator::is_touch_cancel;
use super::types::{Event, EventPriority};
#[cfg(all(feature = "touch", not(alloc_frugal)))]
use crate::compat::HashMap;
use crate::compat::{lock, Box, Mutex, String, Vec};
use crate::core::ObjectId;
#[cfg(all(feature = "touch", not(alloc_frugal)))]
use crate::gesture::GestureEngine;
use alloc::sync::Arc;
#[cfg(all(not(alloc_frugal), declarative_view))]
use core::sync::atomic::AtomicBool;
use core::sync::atomic::AtomicU64;
use core::sync::atomic::AtomicUsize;
use core::sync::atomic::Ordering;
use core::time::Duration;
#[cfg(not(alloc_frugal))]
use std::thread;

/// Type alias for event dispatch function.
pub type EventDispatchFn = Arc<dyn Fn(ObjectId, &Event) + Send + Sync>;

/// Type alias for the accelerator hook that runs before normal dispatch.
///
/// Returning `true` means the event was consumed as a shortcut, so the focused control does not
/// see it. The hook exists so the crate's one shortcut path (`ActionRouter::dispatch_event`) can
/// be driven by the loop rather than by every host's hand-written key handler.
pub type EventShortcutFn = Arc<dyn Fn(&Event) -> bool + Send + Sync>;

/// The idle-task id [`EventLoop::install_reactive_idle_pump`] registers under.
///
/// A fixed id gives the registration replace-on-re-register semantics (the same id removes the
/// previous task), which is what a host that switches scenes wants: one pump, never two.
pub const REACTIVE_PUMP_TASK_ID: u64 = 0x7265_6163_7469_7665;

/// Milliseconds elapsed on the monotonic clock since `epoch`.
///
/// # Why not the wall clock
///
/// The gesture path used to stamp touches with `SystemTime::now()`. A wall clock can jump
/// (NTP correction, a user changing the time zone), which makes an elapsed-time subtraction
/// report a negative value that saturates to zero or an enormous one; on a touch-dense
/// stream that read also sat on the event hot path. The loop takes one [`Instant`] origin
/// when it starts and every gesture timestamp is measured from it, so the deltas it feeds
/// the recognisers are monotonic by construction.
fn monotonic_ms(epoch: crate::compat::Instant) -> u64 {
    epoch.elapsed().as_millis().min(u128::from(u64::MAX)) as u64
}

/// Whether an event should be handed to the gesture engine.
///
/// # Why this is not `Event::is_touch`
///
/// The engine's recognisers are driven by touch coordinates, so `is_touch()` was the obvious gate
/// — and it stranded two of them. `LongPressGesture`'s timeout lives in a `_` arm, and
/// `LongPressDragGesture` requires `Event::Timer` outright (`gesture/press.rs`), because a finger
/// held still produces **no** further touch event: time is the only thing that changes, and the
/// only thing that reports time is a timer tick. Gating on `is_touch()` therefore meant a stationary
/// 500 ms hold produced no `LongPress` on the real loop at all — the recogniser only ever fired in
/// its unit test, which fed it a `Timer` directly.
///
/// A timer is fed through for exactly that reason. Every other non-touch event is still skipped, so
/// the engine is not asked to interpret a `KeyPress` or a `Resize` as a gesture, and the events the
/// engine itself produces (`Tap`, `Swipe`, …) are `is_touch()`-true and so still round-trip.
#[cfg(feature = "touch")]
fn feeds_the_gesture_engine(event: &Event) -> bool {
    event.is_touch() || matches!(event, Event::Timer { .. })
}

/// Per-target gesture engines with a lifecycle, so a long-lived loop does not grow forever
/// (D09-EVT-03).
///
/// # The defect this closes
///
/// The loop kept a `HashMap<ObjectId, GestureEngine>` created on demand and **never** removed an
/// entry: every distinct target that ever received a touch retained an 11-recogniser engine until
/// the loop stopped, so an app that dynamically creates and destroys interaction targets grew the
/// map with the historical target count. `runtime::unregister` clears focus, hover and pointer
/// capture, but it cannot reach the loop thread's private map.
///
/// # The lifecycle boundary
///
/// An entry is dropped when its target is released (`release`), and swept when it has been idle
/// for longer than any recogniser's memory: [`Self::idle_grace`] exceeds the double-tap timeout,
/// so a target that is quietly waiting for the second tap of a double-tap keeps its engine, while
/// one that has not seen input for longer than that is reclaimed. Sweeping by *idle time* (rather
/// than on every touch end) is what keeps double-tap working — an engine removed the moment the
/// first tap ends could never recognise the second. A touch **cancel** drops the entry at once:
/// the interaction was withdrawn, so no recogniser state should survive it.
#[cfg(all(feature = "touch", not(alloc_frugal)))]
struct GestureRegistry {
    engines: HashMap<ObjectId, GestureEngineEntry>,
}

#[cfg(all(feature = "touch", not(alloc_frugal)))]
struct GestureEngineEntry {
    engine: GestureEngine,
    /// Last time this target received an event the engine consumed (`now_ms`).
    last_active_ms: u64,
}

#[cfg(all(feature = "touch", not(alloc_frugal)))]
impl GestureRegistry {
    fn new() -> Self {
        Self { engines: HashMap::new() }
    }

    /// How long an idle target's engine is retained after its last event.
    ///
    /// Strictly greater than `DOUBLE_TAP_TIMEOUT_MS` (400 ms) so a target waiting for the
    /// second tap of a double-tap is never swept, with headroom for the loop's own wake
    /// cadence.
    fn idle_grace() -> u64 {
        crate::gesture::tuning().double_tap_timeout_ms + 600
    }

    /// Routes `event` to `target`'s engine, creating it on demand, and returns any derived
    /// gesture event. A touch cancel discards the target's engine instead of feeding it, so no
    /// recogniser commits a withdrawn gesture and the entry does not linger.
    fn process(&mut self, target: ObjectId, event: &Event, now_ms: u64) -> Option<Event> {
        if is_touch_cancel(event) {
            self.engines.remove(&target);
            return None;
        }
        let entry = self.engines.entry(target).or_insert_with(|| GestureEngineEntry {
            engine: GestureEngine::new(),
            last_active_ms: now_ms,
        });
        entry.last_active_ms = now_ms;
        entry.engine.process(event, now_ms)
    }

    /// Drops engines idle longer than [`Self::idle_grace`]. Returns how many were removed.
    fn sweep(&mut self, now_ms: u64) -> usize {
        let grace = Self::idle_grace();
        let before = self.engines.len();
        self.engines.retain(|_, entry| now_ms.saturating_sub(entry.last_active_ms) <= grace);
        before - self.engines.len()
    }

    /// Drops the engine for `target` (on unregister). Returns whether one was present.
    fn release(&mut self, target: ObjectId) -> bool {
        self.engines.remove(&target).is_some()
    }

    /// Number of live engines (test/introspection only).
    #[cfg(test)]
    fn len(&self) -> usize {
        self.engines.len()
    }
}

/// Canonical event name for animation frame requests.
/// Used instead of a string literal to avoid fragile string matching.
pub const ANIMATION_FRAME_EVENT_NAME: &str = "animation_frame";

// ── Per-turn dispatch budgets (D09-EVT-04) ──
//
// # Why explicit limits rather than "drain everything"
//
// The loop used to pull **every** queued event into an unbounded `Vec` and then walk the
// High and Normal phases with no count or time limit. A sustained producer therefore made
// the buffer grow with the backlog, and an arbitrarily large High/Normal stream pushed the
// next platform pump, frame tasks and Idle work arbitrarily far out. The three constants
// below bound one turn's work; whatever a turn does not reach stays in the queue (or is
// retained locally in order) and is delivered on a later turn — bounded and eventually delivered,
// never silently dropped.

/// Maximum events pulled from the queue into a turn's dispatch buffer (D09-EVT-04).
///
/// This is what bounds the peak transient buffer: events beyond it simply remain in the
/// queue, so the buffer cannot grow with the backlog.
#[cfg(not(alloc_frugal))]
const PER_TURN_EVENT_DRAIN_CAP: usize = 512;

/// Time budget for the High-priority dispatch phase of one turn (D09-EVT-04).
///
/// High work is the most urgent, so it gets the largest share, but it is still bounded so
/// it cannot monopolise a turn and starve the platform pump and the next frame.
#[cfg(not(alloc_frugal))]
const HIGH_PHASE_BUDGET: Duration = Duration::from_millis(4);

/// Time budget for the Normal-priority dispatch phase of one turn (D09-EVT-04).
#[cfg(not(alloc_frugal))]
const NORMAL_PHASE_BUDGET: Duration = Duration::from_millis(4);

/// How long the thread waits for the next event when a turn dispatched nothing.
///
/// The wait is woken by `post_event`, so a busy loop still reacts immediately; the timeout only
/// bounds how often the loop re-checks state that has no wake channel (the `running` flag, a
/// gesture release, the native pump). It replaces a 1 ms sleep, which woke the thread 1000 times
/// a second on a completely idle window.
#[cfg(not(alloc_frugal))]
const IDLE_WAIT: Duration = Duration::from_millis(16);

/// The idle wait when a platform pump must be polled (Wayland `dispatch_pending`).
///
/// Such a pump has no file descriptor the loop can wait on, so its cadence is the loop's. Keeping
/// the shorter interval avoids trading 1 ms of Wayland dispatch for idle CPU.
#[cfg(not(alloc_frugal))]
const NATIVE_PUMP_WAIT: Duration = Duration::from_millis(1);

/// The request id carried by an animation-frame event, or `None` for any other event.
///
/// The id lives in the payload as eight little-endian bytes (see
/// [`EventLoop::request_animation_frame`]); decoding it here keeps the encoding in one place, so
/// the producer and the cancellation check cannot disagree about the layout.
/// Reads the frame id an animation-frame event carries, if it is one.
///
/// Used by both profiles: the threaded loop in its dispatch phase and the `mini`
/// `pump_once`, which must honour the same cancellation contract.
fn animation_frame_id(event: &Event) -> Option<u64> {
    // The variant is what this crate posts; the `Custom` arm keeps the legacy encoding working
    // for a host that replicates it (or a captured event), and costs one string compare on a
    // path that no longer runs per frame.
    if let Event::AnimationFrame(id) = event {
        return Some(*id);
    }
    let Event::Custom { name, payload } = event else {
        return None;
    };
    if name.as_ref() != ANIMATION_FRAME_EVENT_NAME {
        return None;
    }
    let bytes: [u8; 8] = payload.as_slice().try_into().ok()?;
    Some(u64::from_le_bytes(bytes))
}

/// Bookkeeping for animation-frame requests, shared with the loop thread.
///
/// # Why both a pending set and a cancelled set
///
/// `cancel_animation_frame` used to consult only the cancelled set, which records what
/// was cancelled, not what is still outstanding. It therefore reported `true` for a
/// handle that had already been dispatched, for one that was never issued, and for one
/// belonging to a different loop — and pushed duplicate entries. This type holds the
/// complementary fact: which ids are still pending. A cancel is accepted only for a
/// pending id, dispatches are marked, and the cancelled entries are consumed by the
/// dispatch check, so a repeated cancel and a cancel-after-dispatch both report `false`.
///
/// Both profiles use this type: the threaded loop shares it through an `Arc`, and the
/// `mini` synchronous pump owns it directly, so the two obey the same cancellation
/// contract (a cancelled frame is skipped before dispatch).
#[derive(Debug, Default)]
struct AnimFrameState {
    /// Ids requested but not yet dispatched or cancelled.
    pending: Vec<u64>,
    /// Pending ids whose dispatch must be skipped, consumed by the dispatch check.
    cancelled: Vec<u64>,
}

impl AnimFrameState {
    /// Records a new request as pending.
    fn request(&mut self, id: u64) {
        self.pending.push(id);
    }

    /// Drops a pending id without marking it cancelled.
    ///
    /// Used to roll back the registration made before publication when publishing the
    /// frame event fails (D09-EVT-08): the frame was never queued, so leaving it pending
    /// would let a later cancel of a request that was never issued report a change.
    fn forget(&mut self, id: u64) {
        if let Some(position) = self.pending.iter().position(|pending| *pending == id) {
            self.pending.swap_remove(position);
        }
    }

    /// Cancels `id` if it is still pending. Returns whether a state change occurred.
    fn cancel(&mut self, id: u64) -> bool {
        if let Some(position) = self.pending.iter().position(|pending| *pending == id) {
            self.pending.swap_remove(position);
            self.cancelled.push(id);
            return true;
        }
        false
    }

    /// Marks `id` dispatched if it is pending, then consumes a matching cancellation
    /// entry, returning whether the frame must be skipped.
    fn dispatched_and_cancelled(&mut self, id: u64) -> bool {
        if let Some(position) = self.pending.iter().position(|pending| *pending == id) {
            self.pending.swap_remove(position);
        }
        take_cancelled_ids(&mut self.cancelled, id)
    }
}

/// Whether `id` is in `cancelled`, removing it.
fn take_cancelled_ids(cancelled: &mut Vec<u64>, id: u64) -> bool {
    if let Some(position) = cancelled.iter().position(|pending| *pending == id) {
        cancelled.swap_remove(position);
        return true;
    }
    false
}

/// A handle returned by `request_animation_frame` that can be used to cancel the request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AnimationFrameRequest {
    /// Unique identifier for this animation frame request.
    pub id: u64,
}

/// Delivers `event` to `target` through the capture/target/bubble route.
///
/// # Why a helper rather than inline code
///
/// Both loop profiles (the threaded loop and `pump_once`) deliver events, and the gesture path
/// delivers a derived event after the raw one. One helper means the propagation rule cannot
/// exist in one profile and not the other — the drift that previously made `pump_once` ignore
/// priorities that the threaded loop honoured.
///
/// # One panic barrier per event, not per node
///
/// The route can visit the target plus every ancestor up to three times. Wrapping each delivery
/// in `catch_unwind` therefore paid one unwind barrier per node per event even though a panic
/// ends the route anyway. The barrier is hoisted around the whole route and the node currently
/// being delivered is recorded in a `Cell`, so a panic is still intercepted and logged with the
/// node that caused it, at one barrier per event instead of O(nodes).
fn deliver_event(
    dispatch: Option<&EventDispatchFn>,
    parents: &Arc<dyn Fn(ObjectId) -> Option<ObjectId> + Send + Sync>,
    target: ObjectId,
    event: &Event,
) {
    let Some(dispatch) = dispatch else {
        log::warn!(
            "[event-loop] No dispatch_fn set — dropping event {event:?} for target {target:?}"
        );
        return;
    };
    // Records which node's handler is running, so the single barrier can name the culprit.
    let current = core::cell::Cell::new(target);
    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        crate::event::propagation::with_ancestor_chain(target, parents.as_ref(), |ancestors| {
            let _ = crate::event::propagation::route_event(
                target,
                ancestors,
                event,
                &mut |node, ev, _phase| {
                    current.set(node);
                    dispatch(node, ev);
                },
            );
        });
    }));
    if let Err(error) = outcome {
        log::error!(
            "[event-loop] Dispatch panicked for target {target:?} at node {:?}: {error:?}",
            current.get()
        );
    }
}

/// The built-in parent resolver the loop installs at construction (W-01).
///
/// # Why the loop must own a default resolver
///
/// `set_parent_lookup` was documented as the switch that turns capture/target/bubble on, and no
/// production caller ever installed it. The propagation implementation was therefore reachable
/// only from tests: the loop's real dispatch entry always took the flat branch. The widget
/// registry already answers "who is this control's parent", so the loop asks it directly. A host
/// that owns a different tree can still override the resolver through `set_parent_lookup`; it no
/// longer has to remember to install one for bubbling to work at all.
///
/// The resolver is a plain function rather than a closure so it captures nothing and is therefore
/// trivially `Send + Sync`. It reads the thread-local widget registry, which is the same thread
/// the controls are mounted on (the loop thread is the UI thread in both profiles).
#[cfg(not(alloc_frugal))]
fn runtime_parent(id: ObjectId) -> Option<ObjectId> {
    crate::widget::runtime::read_widget(id, |widget| widget.parent()).flatten()
}

/// The `mini` resolver.
///
/// The widget registry (`widget::runtime`) is compiled out of the allocation-frugal profile, so
/// there is no tree for the loop to walk: the honest answer is "this id has no parent". The
/// three-phase route still runs (one target delivery), which is the same observable behaviour a
/// flat dispatch had, and a host that builds its own tree installs a resolver explicitly.
#[cfg(alloc_frugal)]
fn runtime_parent(_id: ObjectId) -> Option<ObjectId> {
    None
}

/// Main event loop for processing events.
pub struct EventLoop {
    /// Event queue for processing.
    #[cfg_attr(alloc_frugal, allow(dead_code))]
    // Only read by the non-mini `start()`; kept to mirror the desktop API.
    // Under mini the queue uses a single-threaded channel, so the Arc is not
    // Send/Sync — that is intentional for the mini (single-threaded) profile.
    #[cfg_attr(alloc_frugal, allow(clippy::arc_with_non_send_sync))]
    queue: Arc<Mutex<EventQueue>>,
    /// Budget-deferred events survive stop/start without a channel round trip. The total is
    /// bounded by `PER_TURN_EVENT_DRAIN_CAP`; accepted events are never dropped on overflow.
    #[cfg(not(alloc_frugal))]
    deferred_events: Arc<Mutex<[Vec<(ObjectId, Event)>; 3]>>,
    /// Independent sender for posting events without locking the queue.
    /// Avoids deadlock with the event loop thread which holds the queue mutex
    /// while blocked on `dequeue_blocking()`.
    sender: EventSender,
    /// Shared flag indicating if the loop is running.
    running: Arc<Mutex<bool>>,
    /// Processing thread handle.
    #[cfg(not(alloc_frugal))]
    thread_handle: Option<thread::JoinHandle<()>>,
    /// Field kept in `mini` so the shared method bodies compile unchanged.
    ///
    /// `mini` is single-threaded, so the loop runs on the caller's thread and there is
    /// no handle to join. This is *not* a placeholder with no behaviour: the alternative
    /// is two copies of every method, which is the drift this mirror prevents (see
    /// `mini`'s `pump`-driven `TimerManager` for the same pattern).
    #[cfg(alloc_frugal)]
    #[cfg_attr(alloc_frugal, allow(dead_code))]
    thread_handle: Option<()>,
    /// Optional dispatch callback invoked for each event.
    dispatch_fn: Option<EventDispatchFn>,
    /// Optional accelerator hook, consulted for every key press before normal dispatch.
    ///
    /// This is the event-loop half of W-14/W-15: one entry point asks the shortcut registry (the
    /// only conflict judge) and triggers the command through `ActionManager`.
    shortcut_dispatch: Option<EventShortcutFn>,
    /// Resolves a control's parent for the capture/bubble route.
    ///
    /// # Why propagation is on by default (W-01)
    ///
    /// The resolver is built in ([`runtime_parent`]) so the three-phase route
    /// ([`crate::event::propagation::route_event`]) is the loop's **only** delivery path. It was an
    /// opt-in `Option` before, and no production caller ever installed it, so the whole
    /// capture/target/bubble implementation was dead in production. A host that owns a tree the
    /// widget registry cannot describe overrides it through [`EventLoop::set_parent_lookup`];
    /// there is no longer a "flat vs propagating" fork to fall through by accident.
    parent_lookup: Arc<dyn Fn(ObjectId) -> Option<ObjectId> + Send + Sync>,
    /// Which keys are physically held, so a repeated `KeyPress` can be marked as a repeat (W-204).
    ///
    /// The platform auto-repeat source is the raw key stream: a platform that repeats a held key
    /// sends another `KeyPress` for the same code without an intervening `KeyRelease`. Tracking
    /// the held set in the loop is what turns that stream into the additive repeat flag exposed
    /// through [`Event::is_key_repeat`].
    key_state: KeyRepeatState,
    /// Monotonic origin for the `mini` pump's gesture and double-click timestamps.
    ///
    /// The threaded loop takes its own origin when it spawns; the single-threaded pump lives on
    /// the caller's thread for the loop's whole life, so it stores one here instead of resetting
    /// it on every call (which would make every timestamp zero).
    #[cfg_attr(not(alloc_frugal), allow(dead_code))]
    clock_origin: crate::compat::Instant,
    /// The event layer's one double-click judgement (W-203).
    ///
    /// Touch double-taps are decided by `gesture::DoubleTapGesture`; this tracker applies the
    /// same rule (the gesture timing tokens) to the mouse stream, so the loop does not accept a
    /// host `MouseDoubleClick` that contradicts the interval the gesture engine uses.
    double_click: DoubleClickTracker,
    /// Runtime timer manager emitting `Event::Timer` into this loop queue.
    timer_manager: TimerManager,
    /// Next animation frame request ID.
    next_anim_frame_id: AtomicU64,
    /// Optional native platform event pump.
    /// Called on each loop iteration to dispatch pending native platform events
    /// (e.g., Wayland dispatch_pending). Replaces standalone platform dispatch loops.
    native_pump: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Deferred callbacks that run only when no frame-critical work is pending.
    ///
    /// Ticked in the loop's Idle phase, alongside Idle-priority events. Without this
    /// the loop had an Idle phase that idle *tasks* could not reach —
    /// [`IdleTask::tick`] documented itself as "called each frame by the event loop"
    /// while nothing ever called it.
    idle_tasks: Vec<IdleTask>,
    /// The loop's built-in animation-frame driver.
    ///
    /// # Why the loop owns this
    ///
    /// An animation needs one **measured** frame delta, not a `now()` read per animation: a
    /// host that advanced each control on its own would let two controls that started on the
    /// same frame drift apart by however long their `advance` calls took. The loop already sees
    /// every [`Event::AnimationFrame`] and the moment it dispatches it, so it is the only place
    /// that can measure the delta once.
    ///
    /// The driver is `Send` because it runs on the loop thread; it takes the **delta in
    /// milliseconds** rather than a timestamp so an implementation cannot disagree with the
    /// loop about where the clock started. `start` consumes it, so a restart needs a fresh
    /// driver — the same honest state `idle_tasks` has.
    #[cfg(not(alloc_frugal))]
    frame_driver: Option<Box<dyn FnMut(u32) + Send>>,
    /// Ids of [`EventLoop::request_animation_frame`] requests that have been cancelled.
    ///
    /// # Why this exists
    ///
    /// [`AnimationFrameRequest`] was introduced as something that "can be used to identify or
    /// cancel" a frame, but nothing in the crate ever read its `id` and there was no cancel
    /// entry point at all — so the field was write-only (principle #99) and the documented
    /// capability did not exist. A host could request a frame, decide against it, and the
    /// callback still ran.
    ///
    /// Cancellation is checked at **dispatch** time rather than by removing the event from the
    /// queue: the queue is a lock-protected priority structure shared with the loop thread, and
    /// a removal would have to race the `dequeue_blocking` that already holds the mutex. An id
    /// set the dispatcher consults is the same guarantee without touching that lock discipline.
    ///
    /// The state ([`AnimFrameState`]) also records which ids are still *pending*, so a cancel
    /// of an already-dispatched, never-issued, or foreign handle is refused rather than
    /// accumulating a cancellation entry that can never match. Cancellation entries are taken
    /// (consumed) by the dispatch check, so the set does not grow without bound; ids are `u64`
    /// and never reused, so a stale entry can never cancel a later frame.
    ///
    /// Both profiles hold this state; only the sharing differs (the threaded loop shares it
    /// with the loop thread through an `Arc`, `mini` owns it directly).
    #[cfg_attr(alloc_frugal, allow(clippy::arc_with_non_send_sync))]
    cancelled_anim_frames: Arc<Mutex<AnimFrameState>>,
    /// Round-robin start index into `idle_tasks` for the next loop iteration.
    ///
    /// The Idle-task phase used to restart at index 0 every round and break on the 5 ms
    /// budget, so a slow first task let later tasks starve. Persisting the next start
    /// position rotates the phase: every task eventually reaches the front of the round,
    /// while the budget and the normal (cooldown-respecting) ordering are unchanged.
    ///
    /// Shared with the loop thread through an `Arc`, mirroring `cancelled_anim_frames`:
    /// the thread mutates it each round and the loop reads it on the next `start`.
    ///
    /// `mini` has no loop thread and no Idle-task phase, so the field is kept only to
    /// mirror the desktop layout (same reason `thread_handle` is mirrored there).
    #[cfg_attr(alloc_frugal, allow(dead_code))]
    idle_task_cursor: Arc<AtomicUsize>,
    /// Targets whose gesture state the host has asked the loop to drop (D09-EVT-03).
    ///
    /// The per-target gesture registry lives on the loop thread, so the host cannot reach
    /// it directly. This is the handoff: `EventLoop::release_gesture_target` pushes an id
    /// here and the loop drains the set at the top of each turn. A plain `Vec` under its own
    /// mutex (never the queue mutex) keeps the discipline simple — the producer never blocks
    /// on the loop's queue, and the loop never blocks on the producer beyond this short push.
    #[cfg(all(feature = "touch", not(alloc_frugal)))]
    gesture_releases: Arc<Mutex<Vec<ObjectId>>>,
}

impl EventLoop {
    /// Creates a new event loop.
    #[cfg_attr(alloc_frugal, allow(clippy::arc_with_non_send_sync))]
    pub fn new() -> Self {
        let queue = EventQueue::new();
        let sender = queue.sender();
        let timer_manager = TimerManager::new(sender.clone());
        Self {
            queue: Arc::new(Mutex::new(queue)),
            sender,
            #[cfg(not(alloc_frugal))]
            deferred_events: Arc::new(Mutex::new([Vec::new(), Vec::new(), Vec::new()])),
            running: Arc::new(Mutex::new(false)),
            thread_handle: None,
            dispatch_fn: None,
            shortcut_dispatch: None,
            parent_lookup: Arc::new(runtime_parent),
            key_state: KeyRepeatState::new(),
            clock_origin: crate::compat::Instant::now(),
            double_click: DoubleClickTracker::new(),
            timer_manager,
            next_anim_frame_id: AtomicU64::new(1),
            native_pump: None,
            idle_tasks: Vec::new(),
            #[cfg(not(alloc_frugal))]
            frame_driver: None,
            idle_task_cursor: Arc::new(AtomicUsize::new(0)),
            #[cfg(all(feature = "touch", not(alloc_frugal)))]
            gesture_releases: Arc::new(Mutex::new(Vec::new())),
            cancelled_anim_frames: Arc::new(Mutex::new(AnimFrameState::default())),
        }
    }

    /// Registers a deferred task that runs when the loop has no frame-critical work.
    ///
    /// The task runs only after `threshold_frames` loop iterations have passed, so it
    /// is suited to background upkeep — cache trimming, statistics, prefetch — that
    /// must not compete with input or animation. Tasks are ticked only while the loop
    /// runs, and only within the same 5ms budget the Idle event phase uses.
    ///
    /// Must be called before [`EventLoop::start`]: the tasks move onto the loop
    /// thread. Registering after `start` would be a silent no-op, so this returns
    /// `false` in that case rather than accepting a task that will never run.
    ///
    /// Gated off `mini`, which never spawns the loop thread these run on — the same
    /// reason `start` itself is. Offering it there would promise work that cannot run.
    #[cfg(not(alloc_frugal))]
    pub fn add_idle_task(&mut self, task: IdleTask) -> bool {
        if *lock(&self.running) {
            return false;
        }
        // Replacing a task with the same id keeps the registry keyed rather than
        // letting a re-registration accumulate duplicates that all fire.
        self.idle_tasks.retain(|existing| existing.id != task.id);
        self.idle_tasks.push(task);
        true
    }

    /// Removes the idle task with `id`. Returns whether one was registered.
    pub fn remove_idle_task(&mut self, id: u64) -> bool {
        let before = self.idle_tasks.len();
        self.idle_tasks.retain(|task| task.id != id);
        self.idle_tasks.len() != before
    }

    /// Returns how many idle tasks are registered.
    pub fn idle_task_count(&self) -> usize {
        self.idle_tasks.len()
    }

    /// Starts the event loop in a separate thread.
    #[cfg(not(alloc_frugal))]
    pub fn start(&mut self) {
        if *lock(&self.running) {
            return;
        }
        *lock(&self.running) = true;
        let running = Arc::clone(&self.running);
        let queue = Arc::clone(&self.queue);
        let dispatch_fn = self.dispatch_fn.clone();
        let shortcut_dispatch = self.shortcut_dispatch.clone();
        let parent_lookup = Arc::clone(&self.parent_lookup);
        #[cfg(feature = "touch")]
        let mut gesture_engines = GestureRegistry::new();
        let mut key_state = core::mem::take(&mut self.key_state);
        let mut double_click = core::mem::take(&mut self.double_click);
        let native_pump = self.native_pump.clone();
        // Gesture and double-click timestamps are measured from one monotonic origin (W-P02).
        // Taking it before the thread starts is what makes every recogniser in this run share the
        // same base.
        let gesture_epoch = crate::compat::Instant::now();
        // Idle tasks run on the loop thread, so they move with it. `mem::take` leaves the
        // field empty; a restart after `stop()` therefore begins with none, which is the
        // honest state — the caller re-registers what it still wants.
        let mut idle_tasks = core::mem::take(&mut self.idle_tasks);
        // The frame driver runs on the loop thread, so it moves with it. `take` leaves the field
        // empty: a restart begins with no driver, which the caller re-registers explicitly
        // rather than inheriting a closure that captured a scene it no longer describes.
        #[cfg(not(alloc_frugal))]
        let mut frame_driver = self.frame_driver.take();
        #[cfg(not(alloc_frugal))]
        let mut last_frame_at: Option<std::time::Instant> = None;
        // The loop thread consults this state at dispatch time; it is shared rather than moved so
        // `cancel_animation_frame` (called from the host's thread) mutates the same one.
        let cancelled_anim_frames = Arc::clone(&self.cancelled_anim_frames);
        let idle_task_cursor = Arc::clone(&self.idle_task_cursor);
        #[cfg(all(feature = "touch", not(alloc_frugal)))]
        let gesture_releases = Arc::clone(&self.gesture_releases);
        // The three per-priority dispatch buffers live for the whole loop and are cleared each
        // turn. Declaring them inside the `while` body made every non-empty turn allocate from
        // empty, which during animations meant one to three heap allocations per frame.
        let deferred_events = Arc::clone(&self.deferred_events);
        let [mut high_events, mut normal_events, mut idle_events] =
            core::mem::take(&mut *lock(&deferred_events));
        let handle = thread::spawn(move || {
            while *lock(&running) {
                // Phase 0: Pump native platform events (e.g., Wayland dispatch)
                if let Some(ref pump) = native_pump {
                    pump();
                }
                // Phase 0a: Drain any pending scheduled tasks
                crate::event::types::drain_tasks();
                // Phase 0b: Apply host-requested gesture-state releases (D09-EVT-03). A target
                // that was unregistered no longer needs its engine, so dropping it here bounds
                // the registry by *live* targets rather than by every target ever seen.
                #[cfg(feature = "touch")]
                {
                    let releases: Vec<ObjectId> = {
                        let mut pending = lock(&gesture_releases);
                        core::mem::take(&mut *pending)
                    };
                    for target in releases {
                        gesture_engines.release(target);
                    }
                }
                // The dispatch closure borrows the gesture registry for its lifetime, so phase 1
                // (including the idle wait that also dispatches) runs in its own scope: the
                // gesture sweep below needs the registry back by name.
                {
                    // Phase 1a: Drain up to `PER_TURN_EVENT_DRAIN_CAP` events into per-priority
                    // buffers (D09-EVT-04). Draining a bounded prefix — rather than everything —
                    // keeps the transient buffer bounded under a sustained producer; the rest
                    // stays queued and is picked up next turn, so ordering is preserved.
                    // Resume older events before appending new ones at the same priority. Count
                    // the retained tail against the cap, so a slow handler cannot grow local storage.
                    let pending = high_events.len() + normal_events.len() + idle_events.len();
                    // W-P06: consume the wake-dedup flag before the drain. A post that lands from
                    // here on sets it again and wakes the loop, so no wake-up is lost while the
                    // posts already queued are handled by this turn.
                    lock(&queue).clear_wake_pending();
                    // One lock acquisition and one refill for the whole bounded prefix. The
                    // per-event `dequeue` this replaces took the queue mutex n times a turn.
                    let mut had_work = lock(&queue).drain_into(
                        &mut high_events,
                        &mut normal_events,
                        &mut idle_events,
                        PER_TURN_EVENT_DRAIN_CAP.saturating_sub(pending),
                    ) > 0
                        || pending > 0;

                    // One dispatch helper shared by the High and Normal phases, so both honour the
                    // same animation-frame cancellation and gesture-routing rules (and neither is a
                    // copy that can drift from the other). It borrows the gesture registry and the
                    // cancellation state; the phase loops below own only their event buffers.
                    let dispatch_fn_ref = &dispatch_fn;
                    let shortcut_ref = shortcut_dispatch.as_ref();
                    let cancelled_ref = &cancelled_anim_frames;
                    #[cfg(feature = "touch")]
                    let gesture_ref = &mut gesture_engines;
                    let key_ref = &mut key_state;
                    let double_click_ref = &mut double_click;
                    // `mut` is only needed when the `touch` feature captures the gesture
                    // registry by `&mut`; without it the binding is immutable.
                    #[cfg_attr(not(feature = "touch"), allow(unused_mut))]
                    let mut dispatch_one = |target: ObjectId, event: &Event| {
                        // A cancelled animation frame is discarded here, before any dispatch, so a
                        // host that cancelled never sees the callback. See `cancel_animation_frame`
                        // for why this is checked at dispatch rather than removed from the queue.
                        let anim_id = animation_frame_id(event);
                        let skip = match anim_id {
                            Some(id) => lock(cancelled_ref).dispatched_and_cancelled(id),
                            None => false,
                        };
                        if skip {
                            return;
                        }

                        // The accelerator hook runs before the focused control sees the key.
                        // A consumed key press must not also be delivered as text/activation:
                        // the host asked the shortcut path to own it. Non-key events are
                        // untouched, so the hook has exactly one trigger condition.
                        if let Some(shortcut) = shortcut_ref {
                            if matches!(event, Event::KeyPress { .. }) && shortcut(event) {
                                return;
                            }
                        }

                        // One measured delta per animation frame, before dispatch, so an
                        // animation advanced by the default clock and one advanced by the
                        // control's own tick see the same elapsed time for this frame.
                        #[cfg(not(alloc_frugal))]
                        if matches!(event, Event::AnimationFrame(_)) {
                            let now = std::time::Instant::now();
                            let delta = last_frame_at
                                .map(|previous| {
                                    now.duration_since(previous)
                                        .as_millis()
                                        .min(u128::from(u32::MAX))
                                        as u32
                                })
                                .unwrap_or(0);
                            last_frame_at = Some(now);
                            if let Some(driver) = frame_driver.as_mut() {
                                driver(delta);
                            }
                        }

                        // W-204: the repeat fact comes from the key stream itself. A `KeyPress`
                        // for a code that is already held is the platform auto-repeat, and the
                        // flag is scoped to this delivery so a consumer can branch on it without
                        // an event-layout change. A `KeyRelease` clears the held bit at once.
                        let repeat = match event {
                            Event::KeyPress { key, .. } => key_ref.note_press(*key),
                            Event::KeyRelease { key, .. } => {
                                key_ref.note_release(*key);
                                false
                            }
                            _ => false,
                        };

                        // W-203: the loop is the one double-click judge for the mouse stream.
                        // A host `MouseDoubleClick` that falls outside the gesture engine's
                        // interval is delivered as the single click it actually is; two plain
                        // presses inside the interval gain the synthesized double-click the
                        // gesture engine would have produced for touch.
                        let mut synthesized_double_click = None;
                        // Storage for the "a host double-click that the unified interval rejects"
                        // case. It lives outside the match so the replayed press outlives the
                        // borrow that `delivery` holds. Declared without an initialiser so the
                        // allocation only happens on the arm that needs it.
                        let single_click_replay: Event;
                        let delivery: &Event = match event {
                            Event::MousePress { pos, button, modifiers } => {
                                if double_click_ref.observe_press(
                                    target,
                                    *pos,
                                    *button,
                                    *modifiers,
                                    monotonic_ms(gesture_epoch),
                                ) {
                                    synthesized_double_click =
                                        Some(Event::mouse_double_click(pos.x, pos.y, *button));
                                }
                                event
                            }
                            Event::MouseDoubleClick { pos, button } => {
                                if double_click_ref.accept_platform_double_click(
                                    target,
                                    *pos,
                                    *button,
                                    monotonic_ms(gesture_epoch),
                                ) {
                                    event
                                } else {
                                    // Outside the unified interval: this is a single click whose
                                    // host-side detector fired too early or too late. Replaying
                                    // it as a press is what keeps the click from being lost, and
                                    // it keeps the modifiers the original press carried.
                                    single_click_replay = Event::MousePress {
                                        pos: *pos,
                                        button: *button,
                                        modifiers: double_click_ref.last_press_modifiers(),
                                    };
                                    &single_click_replay
                                }
                            }
                            _ => event,
                        };

                        #[cfg(feature = "touch")]
                        let maybe_gesture_event =
                            if feeds_the_gesture_engine(event) || is_touch_cancel(event) {
                                gesture_ref.process(target, event, monotonic_ms(gesture_epoch))
                            } else {
                                None
                            };

                        if let Some(_dispatch) = dispatch_fn_ref {
                            // The repeat flag is scoped around the whole route, so every node the
                            // event reaches sees the same fact.
                            with_dispatch_repeat(repeat, || {
                                deliver_event(
                                    dispatch_fn_ref.as_ref(),
                                    &parent_lookup,
                                    target,
                                    delivery,
                                )
                            });
                            if let Some(ref synthesized) = synthesized_double_click {
                                deliver_event(
                                    dispatch_fn_ref.as_ref(),
                                    &parent_lookup,
                                    target,
                                    synthesized,
                                );
                            }
                            #[cfg(feature = "touch")]
                            if let Some(ref gesture) = maybe_gesture_event {
                                deliver_event(
                                    dispatch_fn_ref.as_ref(),
                                    &parent_lookup,
                                    target,
                                    gesture,
                                );
                            }
                        } else {
                            log::warn!(
                            "[event-loop] No dispatch_fn set — dropping event {event:?} for target {target:?}"
                        );
                        }
                    };

                    // Phase 1b: Dispatch High-priority events first, within a time budget. Events
                    // the budget does not reach stay in their local buffer for the next turn.
                    let mut processed = 0usize;
                    let budget_start = std::time::Instant::now();
                    while processed < high_events.len() {
                        if budget_start.elapsed() >= HIGH_PHASE_BUDGET {
                            break;
                        }
                        let (target, event) = &high_events[processed];
                        dispatch_one(*target, event);
                        processed += 1;
                    }
                    high_events.drain(..processed);

                    // Phase 1c: Dispatch Normal-priority events second, also budgeted. A cancelled
                    // animation frame is discarded before any dispatch, so a host that cancelled
                    // never sees the callback (see `cancel_animation_frame`), and every delivered
                    // id is marked dispatched so a later cancel reports `false`.
                    let mut processed = 0usize;
                    let budget_start = std::time::Instant::now();
                    while processed < normal_events.len() {
                        if budget_start.elapsed() >= NORMAL_PHASE_BUDGET {
                            break;
                        }
                        let (target, event) = &normal_events[processed];
                        dispatch_one(*target, event);
                        processed += 1;
                    }
                    normal_events.drain(..processed);

                    // Phase 1e: Process buffered idle events with a 5ms time budget.
                    // This prevents idle processing from starving frame-critical work. Whatever
                    // the budget does not allow stays local: idle means deferred,
                    // not discarded.
                    if !idle_events.is_empty() {
                        #[cfg(not(alloc_frugal))]
                        let idle_budget_start = std::time::Instant::now();
                        let mut processed = 0;
                        while processed < idle_events.len() {
                            #[cfg(not(alloc_frugal))]
                            if idle_budget_start.elapsed().as_millis() >= 5 {
                                break;
                            }
                            let (target, event) = &idle_events[processed];
                            // Same cancellation and gesture rules the High/Normal phases apply; an
                            // animation frame may be posted at any priority. `dispatch_one` owns
                            // those rules, so idle events cannot drift from the others.
                            dispatch_one(*target, event);
                            processed += 1;
                        }
                        // Deliver the remainder on a later, quieter iteration, in order.
                        idle_events.drain(..processed);
                    }

                    // Phase 1e: Tick deferred idle tasks, under the same 5ms budget as
                    // idle events so a task cannot starve frame-critical work either. A
                    // task runs only once its `threshold_frames` have elapsed, which is
                    // what makes it "idle" work rather than a per-frame callback.
                    if !idle_tasks.is_empty() {
                        #[cfg(not(alloc_frugal))]
                        let task_budget_start = std::time::Instant::now();
                        let task_count = idle_tasks.len();
                        // Rotate the starting point each round so the tail is not starved by a slow
                        // head task. The phase still breaks on the 5ms budget; the saved cursor is
                        // where a later round resumes, and running the whole ring (at most once per
                        // task) keeps the normal ordering and `threshold_frames` cooldown intact.
                        let start_at = idle_task_cursor.load(Ordering::SeqCst) % task_count;
                        let mut offset = 0;
                        while offset < task_count {
                            #[cfg(not(alloc_frugal))]
                            if task_budget_start.elapsed().as_millis() >= 5 {
                                break;
                            }
                            let index = (start_at + offset) % task_count;
                            offset += 1;
                            let task = &mut idle_tasks[index];
                            // A panicking task must not take the loop down with it: the
                            // rest of the queue is still valid work.
                            let outcome =
                                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                    task.tick()
                                }));
                            match outcome {
                                Ok(true) => had_work = true,
                                Ok(false) => {}
                                Err(e) => {
                                    log::error!(
                                        "[event-loop] Idle task {} panicked: {e:?}",
                                        task.id
                                    )
                                }
                            }
                        }
                        // Resume at the task after the last one attempted, wrapping around. A task
                        // the budget cut off is `start_at + offset` (offset was incremented past
                        // it), so the whole ring is covered across rounds even if every task is slow.
                        idle_task_cursor.store((start_at + offset) % task_count, Ordering::SeqCst);
                    }

                    // Phase 2: If no events were dispatched, wait for the next one instead of
                    // polling on a fixed 1 ms tick. The wait is woken by `post_event`, so a
                    // producer is never delayed behind it; the timeout only re-checks state that
                    // has no wake channel. A turn that dispatched nothing was previously a
                    // 1000 Hz busy-poll on an idle window.
                    //
                    // The wait happens **outside** the queue mutex. The previous form held the
                    // queue lock across `dequeue_timeout`, so any other reader (or a test) blocked
                    // for up to the whole timeout. The generation is read before the empty check,
                    // so a post racing the check/wait window returns at once instead of sleeping
                    // until the timeout (see `frame_wait::wait_after`).
                    if !had_work {
                        let wait = if native_pump.is_some() { NATIVE_PUMP_WAIT } else { IDLE_WAIT };
                        let generation = crate::platform::frame_wait::generation();
                        let queued = lock(&queue).dequeue();
                        let event = match queued {
                            Some(event) => Some(event),
                            None => {
                                crate::platform::frame_wait::wait_after(generation, wait);
                                lock(&queue).dequeue()
                            }
                        };
                        if let Some((target, event, _priority)) = event {
                            dispatch_one(target, &event);
                        }
                    }
                }

                // Phase 1f: Reclaim gesture engines whose targets have gone quiet (D09-EVT-03).
                // The sweep runs on the loop's own cadence, so a target that received a touch and
                // then went silent does not retain an 11-recogniser engine for the life of the
                // loop. The grace exceeds the double-tap timeout, so a target still waiting for the
                // second tap keeps its engine and double-tap keeps working.
                #[cfg(feature = "touch")]
                {
                    let removed = gesture_engines.sweep(monotonic_ms(gesture_epoch));
                    if removed > 0 {
                        log::trace!("[event-loop] reclaimed {removed} idle gesture engine(s)");
                    }
                }
            }
            *lock(&deferred_events) = [high_events, normal_events, idle_events];
        });
        self.thread_handle = Some(handle);
    }

    /// Starts the event loop (no-op under mini/embedded).
    #[cfg(alloc_frugal)]
    pub fn start(&mut self) {
        *lock(&self.running) = true;
    }

    /// Processes one queued event and pumps timers in the mini profile.
    ///
    /// Mini builds do not spawn a background thread, so hosts must call this
    /// from their own frame/input loop to make `post_event` and timers live.
    ///
    /// # Priority (D09-EVT-06)
    ///
    /// The event dispatched is the **highest-priority** one available — High before Normal
    /// before Idle — with same-priority events kept in FIFO order. This matches the threaded
    /// loop's phased dispatch, so a High event posted after older Normal/Idle work is not
    /// delayed behind it. (The old pump dequeued strictly oldest-first and ignored the
    /// priority metadata entirely, giving the two profiles different ordering semantics.)
    ///
    /// This remains the synchronous counterpart of the threaded loop's dispatch in every
    /// other respect: it honours the same animation-frame contract (a cancelled frame is
    /// discarded before dispatch and its cancellation entry is consumed, exactly as the
    /// threaded loop does) and routes touch through the same gesture path.
    #[cfg(alloc_frugal)]
    pub fn pump_once(&mut self) -> bool {
        if !self.is_running() {
            return false;
        }
        self.timer_manager.pump();
        // This pump is the consumer of the queue's wake dedup (W-P06): clearing the flag before
        // selecting work means a post that lands after this point sets it again and wakes the
        // next pump, while the posts already drained are handled by this one.
        lock(&self.queue).clear_wake_pending();
        let next = lock(&self.queue).dequeue_priority_first();
        let Some((target, event, _priority)) = next else {
            return false;
        };
        let id = animation_frame_id(&event);
        let skip = match id {
            Some(id) => lock(&self.cancelled_anim_frames).dispatched_and_cancelled(id),
            None => false,
        };
        if skip {
            // The frame was cancelled: treat it as consumed work, not a dispatch.
            return true;
        }
        if matches!(event, Event::KeyPress { .. }) {
            if let Some(shortcut) = self.shortcut_dispatch.as_ref() {
                if shortcut(&event) {
                    return true;
                }
            }
        }
        // W-204: the mini profile derives the repeat fact from the same held-key stream.
        let repeat = match &event {
            Event::KeyPress { key, .. } => self.key_state.note_press(*key),
            Event::KeyRelease { key, .. } => {
                self.key_state.note_release(*key);
                false
            }
            _ => false,
        };
        // W-203: one mouse double-click judgement, shared with the threaded loop.
        let now_ms = monotonic_ms(self.clock_origin);
        let mut synthesized_double_click = None;
        let single_click_replay: Event;
        let delivery: &Event = match &event {
            Event::MousePress { pos, button, modifiers } => {
                if self.double_click.observe_press(target, *pos, *button, *modifiers, now_ms) {
                    synthesized_double_click =
                        Some(Event::mouse_double_click(pos.x, pos.y, *button));
                }
                &event
            }
            Event::MouseDoubleClick { pos, button } => {
                if self.double_click.accept_platform_double_click(target, *pos, *button, now_ms) {
                    &event
                } else {
                    single_click_replay = Event::MousePress {
                        pos: *pos,
                        button: *button,
                        modifiers: self.double_click.last_press_modifiers(),
                    };
                    &single_click_replay
                }
            }
            _ => &event,
        };
        with_dispatch_repeat(repeat, || {
            deliver_event(self.dispatch_fn.as_ref(), &self.parent_lookup, target, delivery)
        });
        if let Some(synthesized) = synthesized_double_click {
            deliver_event(self.dispatch_fn.as_ref(), &self.parent_lookup, target, &synthesized);
        }
        true
    }

    /// Stops the event loop.
    #[cfg(not(alloc_frugal))]
    pub fn stop(&mut self) {
        *lock(&self.running) = false;
        self.timer_manager.clear();
        // Post a wake event so the loop thread's next poll observes the running flag without
        // waiting out its idle sleep. It does not hold the queue lock while sleeping — the loop
        // polls `dequeue` and releases the lock between iterations — so this is politeness, not
        // the deadlock-avoidance measure it was once described as.
        let _ = self.sender.post(0, Event::Custom { name: "__stop_wake".into(), payload: vec![] });
        if let Some(handle) = self.thread_handle.take() {
            if let Err(e) = handle.join() {
                log::error!("[event-loop] Thread join failed: {e:?}");
            }
        }
    }

    /// Stops the event loop.
    ///
    /// In `mini` there is no loop thread to stop, so this only clears the running flag;
    /// the caller's `pump` loop observes it. Same name and signature as the threaded
    /// version so call sites need no profile branch.
    #[cfg(alloc_frugal)]
    pub fn stop(&mut self) {
        *lock(&self.running) = false;
        self.timer_manager.clear();
        // A key held across the stop boundary must not turn its next press into a phantom
        // repeat, and a click run must not survive a scene change.
        self.key_state.reset();
        self.double_click.reset();
    }

    /// Posts an event to the event loop.
    ///
    /// Uses an independent sender so posting never contends on the queue mutex. The loop
    /// *polls* `dequeue` each iteration and releases that lock between polls, so a producer is
    /// not blocked behind a sleeping loop thread.
    pub fn post_event(
        &self,
        target: ObjectId,
        event: Event,
        priority: EventPriority,
    ) -> Result<(), String> {
        self.sender.post_with_priority(target, event, priority)
    }

    /// Request the event loop to dispatch a custom animation frame event on the next iteration.
    ///
    /// Returns an `AnimationFrameRequest` handle that can be used to identify the request or to
    /// cancel it with [`EventLoop::cancel_animation_frame`]. This is similar to
    /// `window.requestAnimationFrame()` in browsers, cancellation included.
    pub fn request_animation_frame(
        &self,
        target: ObjectId,
    ) -> Result<AnimationFrameRequest, String> {
        let id = self.next_anim_frame_id.fetch_add(1, Ordering::SeqCst);
        // D09-EVT-08: register the request as pending **before** publishing the frame
        // event. Publishing first left a window in which the loop thread could dequeue
        // and dispatch the frame before this thread recorded it as pending; the dispatch
        // then consumed nothing, and the id was added to `pending` *after* it had already
        // run — so `cancel_animation_frame` would later report `true` for an already
        // dispatched frame, leaving an orphan cancellation entry no event could consume.
        //
        // Registering first closes that window: the frame event cannot be dequeued until
        // after `post_event`, by which point its id is already pending, so the dispatch
        // removes it from `pending` and every later cancel correctly reports `false`. The
        // lock is **not** held across `post_event` (which can synchronously run dispatch
        // callbacks), so this cannot deadlock against them.
        lock(&self.cancelled_anim_frames).request(id);
        let event = Event::AnimationFrame(id);
        if let Err(error) = self.post_event(target, event, EventPriority::Normal) {
            // The frame was never published, so the pending record must not survive it.
            lock(&self.cancelled_anim_frames).forget(id);
            return Err(error);
        }
        Ok(AnimationFrameRequest { id })
    }

    /// Cancels a previously requested animation frame, reporting whether it was still pending.
    ///
    /// # What "cancelled" means here
    ///
    /// The frame event may already be queued when this is called, so cancellation is enforced by
    /// the loop: when it dequeues an animation-frame event whose id is pending-and-cancelled, it
    /// **discards it without invoking the dispatch callback**. A host that cancels therefore never
    /// sees the callback, which is the guarantee `requestAnimationFrame`'s counterpart gives.
    ///
    /// # The return value
    ///
    /// `true` when this call is the one that cancelled a still-pending request. A second cancel
    /// of the same request returns `false`: the frame is already cancelled, and reporting `true`
    /// again would say a state change happened when none did. A request that has **already been
    /// dispatched** also reports `false`, because there is nothing left to cancel — as does a
    /// handle that was never issued through this loop. Tracking the pending set is what lets the
    /// return value mean this rather than merely "an id was recorded".
    pub fn cancel_animation_frame(&mut self, request: AnimationFrameRequest) -> bool {
        // The request is cancellable only while it is still pending in this loop. An
        // already-dispatched frame, a repeated cancel, and a handle from another loop (or
        // one never issued here) all report `false` because none of them changes state.
        lock(&self.cancelled_anim_frames).cancel(request.id)
    }

    /// Whether `id` was cancelled, consuming the entry.
    ///
    /// Kept for callers that hold an [`EventLoop`] and want to ask without going through the
    /// dispatch path (a test, or a host with its own pump). The loop thread uses the shared
    /// `AnimFrameState` because it captures the `Arc`, not `self`.
    pub fn take_cancelled_animation_frame(&self, id: u64) -> bool {
        lock(&self.cancelled_anim_frames).dispatched_and_cancelled(id)
    }

    /// Sets the dispatch callback invoked for each dequeued event.
    pub fn set_dispatch_fn(&mut self, f: EventDispatchFn) {
        self.dispatch_fn = Some(f);
    }

    /// Installs the accelerator hook consulted for every key press.
    ///
    /// Must be called before [`Self::start`] (or before the first `pump_once`), because the
    /// threaded loop captures the callback when it spawns. The intended argument is the closure
    /// form of `ActionRouter::dispatch_event`; installing it is what puts the shortcut registry on
    /// the event path instead of leaving it host-driven.
    pub fn set_shortcut_dispatch(&mut self, f: EventShortcutFn) {
        self.shortcut_dispatch = Some(f);
    }

    /// Installs a parent resolver override, replacing the built-in one.
    ///
    /// Capture/target/bubble propagation is **already on** when the loop is constructed: the loop
    /// asks the widget registry for each control's parent (`runtime_parent`). This method is the
    /// override entry for a host whose tree the registry cannot describe, not the switch that
    /// enables propagation (W-01).
    ///
    /// Must be called before [`Self::start`]: the closure moves onto the loop thread.
    pub fn set_parent_lookup(
        &mut self,
        lookup: Box<dyn Fn(ObjectId) -> Option<ObjectId> + Send + Sync>,
    ) {
        self.parent_lookup = Arc::from(lookup);
    }

    /// Installs the loop's animation-frame driver.
    ///
    /// The driver is called once per [`Event::AnimationFrame`] with the milliseconds elapsed
    /// since the previous frame; the first frame reports `0` because there is no previous
    /// timestamp to measure from. It must be set **before** [`Self::start`], which moves it onto
    /// the loop thread and leaves the field empty.
    ///
    /// This is the loop half of the unified animation clock: the loop decides *when* a frame's
    /// delta is known, and the driver decides what advances. See
    /// [`Self::drive_default_animation_clock`] for the ready-made pairing with the crate's
    /// thread-local clock.
    #[cfg(not(alloc_frugal))]
    pub fn set_frame_driver(&mut self, driver: Box<dyn FnMut(u32) + Send>) {
        self.frame_driver = Some(driver);
    }

    /// Drives the crate's default animation clock from this loop's animation frames.
    ///
    /// After this call, every animation added through
    /// [`with_default_animation_clock`](crate::style::animation::with_default_animation_clock)
    /// — and every named group attached to that clock — advances once per frame with the delta
    /// the loop measured. The closure captures nothing, so it is `Send` even though the clock it
    /// reaches is thread-local: it runs on the loop thread, which is the thread the controls and
    /// their clock live on.
    #[cfg(not(alloc_frugal))]
    pub fn drive_default_animation_clock(&mut self) {
        self.set_frame_driver(Box::new(|delta_ms| {
            crate::style::animation::advance_default_animation_clock(delta_ms);
        }));
    }

    /// Registers an idle task that asks a reactive host to pump during the loop's idle phase.
    ///
    /// `pending` is the host's
    /// [`idle_flag`](crate::view::ReactiveHost::idle_flag): the task posts
    /// [`REACTIVE_PUMP_EVENT`](crate::view::REACTIVE_PUMP_EVENT) to `target` **only while the
    /// flag is set**. Without that check the task would post every turn by itself and the loop
    /// would never go idle. The host's dispatch callback hands each occurrence to
    /// [`ReactiveHost::pump_if`](crate::view::ReactiveHost::pump_if), which coalesces the queued
    /// binding changes into one rebuild and clears the flag. The indirection is what keeps a
    /// `!Send` engine off the loop thread while still letting the loop choose *when* the rebuild
    /// runs.
    ///
    /// Returns `false` when the loop is already running (an idle task registered after `start`
    /// would never run) or when the profile has no idle phase.
    #[cfg(all(not(alloc_frugal), declarative_view))]
    pub fn install_reactive_idle_pump(
        &mut self,
        target: ObjectId,
        pending: Arc<AtomicBool>,
    ) -> bool {
        let sender = self.sender.clone();
        self.add_idle_task(IdleTask::new(REACTIVE_PUMP_TASK_ID, 1, move || {
            if pending.load(Ordering::SeqCst) {
                let _ = sender.post(target, crate::view::reactive_pump_event());
            }
        }))
    }

    /// Set a native platform event pump function.
    ///
    /// The pump is called at the start of each event loop iteration to dispatch
    /// pending native platform events (e.g., Wayland `dispatch_pending`).
    /// This replaces standalone platform dispatch loops with EventLoop-integrated
    /// dispatch.
    pub fn set_native_pump(&mut self, pump: Box<dyn Fn() + Send + Sync>) {
        self.native_pump = Some(Arc::from(pump));
    }

    /// Checks if the event loop is running.
    pub fn is_running(&self) -> bool {
        *lock(&self.running)
    }

    /// Start or replace a timer bound to `target` and `timer_id`.
    pub fn start_timer(
        &self,
        target: ObjectId,
        timer_id: u32,
        interval: Duration,
        repeating: bool,
    ) -> Result<(), String> {
        self.timer_manager.start_timer(target, timer_id, interval, repeating)
    }

    /// Stop one timer by target and id.
    pub fn stop_timer(&self, target: ObjectId, timer_id: u32) -> bool {
        self.timer_manager.stop_timer(target, timer_id)
    }

    /// Stop all timers associated with a target widget.
    pub fn stop_timers_for_target(&self, target: ObjectId) -> usize {
        self.timer_manager.stop_timers_for_target(target)
    }

    /// Releases the gesture state the loop holds for `target` (D09-EVT-03).
    ///
    /// # When to call this
    ///
    /// This is the loop-side half of a widget unregister: when a host tears down an
    /// interaction target (`runtime::unregister` clears focus, hover and pointer capture, but
    /// cannot reach the loop thread's per-target gesture registry), it should call this so
    /// the target's 11-recogniser engine is dropped rather than retained for the life of the
    /// loop. The request is queued and applied on the loop's next turn; if the loop is not
    /// running the request simply waits, and if it is never started the state is dropped with
    /// the loop.
    ///
    /// The idle sweep would eventually reclaim the engine anyway, but only after the
    /// registry's idle grace (longer than the double-tap timeout); this makes the reclaim
    /// immediate and explicit, which is what a deterministic teardown needs.
    #[cfg(all(feature = "touch", not(alloc_frugal)))]
    pub fn release_gesture_target(&self, target: ObjectId) {
        lock(&self.gesture_releases).push(target);
    }
}

crate::impl_default_via_new!(EventLoop);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::types::Event;
    use crate::event::EventPriority;
    use crate::event::EventQueue;
    #[cfg(not(alloc_frugal))]
    use alloc::sync::Arc;
    #[cfg(not(alloc_frugal))]
    use core::sync::atomic::{AtomicUsize, Ordering};
    // `AtomicBool` is only used by the native-pump tests, which are themselves gated
    // on `not(target_arch = "wasm32")` (there is no native pump in a browser sandbox).
    // Importing it unconditionally left an `unused_imports` warning on wasm32 builds.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    use core::sync::atomic::AtomicBool;

    /// A timer tick must reach the gesture engine, or long press can never fire.
    ///
    /// # The defect this pins
    ///
    /// The loop gated the engine on `Event::is_touch()`. A finger held still emits no further
    /// touch event, so the only input that reports the passage of time is a `Timer` — and
    /// `is_touch()` excludes `Timer`. `LongPressGesture`'s timeout lives in a `_` arm reached only
    /// by a non-touch event, and `LongPressDragGesture` requires `Event::Timer` outright, so both
    /// were unreachable from the real loop while passing their own unit tests (which fed the
    /// recogniser a `Timer` directly).
    #[test]
    #[cfg(feature = "touch")]
    fn a_timer_reaches_the_gesture_engine() {
        use crate::core::Point;
        assert!(
            feeds_the_gesture_engine(&Event::Timer { id: 0 }),
            "a timer must reach the engine, or a long press can never time out"
        );
        assert!(
            feeds_the_gesture_engine(&Event::touch_begin(1, 1, 7)),
            "touch input is what the recognisers follow"
        );
        // A keyboard or geometry event is not a gesture, and must not be interpreted as one.
        assert!(!feeds_the_gesture_engine(&Event::KeyPress { key: 65, modifiers: 0 }));
        assert!(!feeds_the_gesture_engine(&Event::Resize { size: crate::core::Size::new(10, 10) }));
        assert!(!feeds_the_gesture_engine(&Event::Custom {
            name: "x".into(),
            payload: alloc::vec::Vec::new(),
        }));
        // And the engine's own output still round-trips.
        assert!(feeds_the_gesture_engine(&Event::LongPress { pos: Point::new(0, 0) }));
    }

    /// An idle task must actually run once the loop ticks enough frames.
    ///
    /// `IdleTask::tick` documented itself as "called each frame by the event loop"
    /// while nothing called it: the loop had an Idle *event* phase but idle *tasks*
    /// were unreachable. This drives the real loop and asserts the callback fires.
    #[test]
    #[cfg(not(alloc_frugal))]
    fn registered_idle_task_runs_on_the_loop() {
        let runs = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&runs);

        let mut el = EventLoop::new();
        assert!(el.add_idle_task(IdleTask::new(1, 2, move || {
            counter.fetch_add(1, Ordering::SeqCst);
        })));
        assert_eq!(el.idle_task_count(), 1);

        el.start();
        // The idle turn waits up to 16ms for an event, so a threshold of 2 frames plus
        // scheduling delay lands well inside this budget.
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(600);
        while runs.load(Ordering::SeqCst) == 0 && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        el.stop();

        assert!(
            runs.load(Ordering::SeqCst) > 0,
            "a registered idle task must run; nothing was ticking it before"
        );
    }

    /// Registering after the loop started must be refused, not silently accepted.
    ///
    /// Tasks move onto the loop thread at `start`, so a late registration could never
    /// run — and accepting it would look like success while doing nothing.
    #[test]
    #[cfg(not(alloc_frugal))]
    fn idle_task_registration_is_refused_once_running() {
        let mut el = EventLoop::new();
        el.start();
        assert!(
            !el.add_idle_task(IdleTask::new(7, 1, || {})),
            "a task registered after start could never run, so it must be refused"
        );
        assert_eq!(el.idle_task_count(), 0);
        el.stop();
    }

    /// Re-registering the same id replaces the task rather than queueing both.
    #[test]
    #[cfg(not(alloc_frugal))]
    fn idle_task_ids_are_unique() {
        let mut el = EventLoop::new();
        assert!(el.add_idle_task(IdleTask::new(3, 1, || {})));
        assert!(el.add_idle_task(IdleTask::new(3, 1, || {})));
        assert_eq!(el.idle_task_count(), 1, "a duplicate id must replace, not accumulate");
        assert!(el.remove_idle_task(3));
        assert!(!el.remove_idle_task(3), "removing twice must report no-op");
        assert_eq!(el.idle_task_count(), 0);
    }

    #[test]
    fn test_event_queue_high_throughput() {
        let queue = EventQueue::new();
        let sender = queue.sender();
        let target: ObjectId = 1;

        for i in 0..1000 {
            let bytes: [u8; 8] = (i as u64).to_le_bytes();
            let event = Event::Custom { name: "test".into(), payload: bytes.to_vec() };
            sender.post_with_priority(target, event, EventPriority::Normal).unwrap();
        }

        let mut count = 0;
        while let Some((_, _, _)) = queue.dequeue() {
            count += 1;
        }
        assert_eq!(count, 1000);
    }

    #[test]
    fn test_event_queue_empty_drain() {
        let queue = EventQueue::new();
        // Drain immediately on an empty queue — should return None
        assert!(queue.dequeue().is_none());
    }

    #[test]
    fn test_event_priority_order() {
        let queue = EventQueue::new();
        let sender = queue.sender();
        let target: ObjectId = 1;
        let normal_event = Event::Custom { name: "normal".into(), payload: vec![] };
        let high_event = Event::Custom { name: "high".into(), payload: vec![] };
        let idle_event = Event::Custom { name: "idle".into(), payload: vec![] };

        sender.post_with_priority(target, normal_event, EventPriority::Normal).unwrap();
        sender.post_with_priority(target, high_event, EventPriority::High).unwrap();
        sender.post_with_priority(target, idle_event, EventPriority::Idle).unwrap();

        // Drain and verify each event carries the correct priority metadata
        let mut events: Vec<EventPriority> = Vec::new();
        while let Some((_, _, prio)) = queue.dequeue() {
            events.push(prio);
        }
        // Since the underlying channel is FIFO, priority is stored as metadata;
        // each envelope retains the priority it was posted with.
        assert_eq!(events.len(), 3);
        assert_eq!(events[0], EventPriority::Normal);
        assert_eq!(events[1], EventPriority::High);
        assert_eq!(events[2], EventPriority::Idle);
    }

    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn test_native_pump_called_on_empty_queue() {
        let mut el = EventLoop::new();
        let pump_called = Arc::new(AtomicBool::new(false));
        let pump_called_clone = pump_called.clone();

        el.set_native_pump(Box::new(move || {
            pump_called_clone.store(true, Ordering::SeqCst);
        }));

        el.start();
        #[cfg(not(alloc_frugal))]
        std::thread::sleep(std::time::Duration::from_millis(50));
        el.stop();

        assert!(
            pump_called.load(Ordering::SeqCst),
            "native pump should have been called during loop iteration"
        );
    }

    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn test_event_loop_timer_integration() {
        let mut el = EventLoop::new();
        let timer_fired = Arc::new(AtomicBool::new(false));
        let timer_fired_clone = timer_fired.clone();

        el.set_dispatch_fn(Arc::new(move |_target, event| {
            if matches!(event, Event::Timer { id: 1 }) {
                timer_fired_clone.store(true, Ordering::SeqCst);
            }
        }));

        el.start_timer(1u64, 1, Duration::from_millis(20), false).unwrap();
        el.start();
        #[cfg(not(alloc_frugal))]
        std::thread::sleep(Duration::from_millis(150));
        el.stop();

        assert!(
            timer_fired.load(Ordering::SeqCst),
            "timer should have fired and been dispatched through the event loop"
        );
    }

    /// The frame id travels in the variant; the legacy `Custom` encoding still decodes.
    ///
    /// Both arms matter. The variant is what `request_animation_frame` now posts, and the byte
    /// encoding is what a host that replicates it — or an event captured before the variant
    /// existed — still carries. Dropping the legacy arm would silently stop honouring
    /// `cancel_animation_frame` for such a sender: the frame would run and the cancellation would
    /// be reported as `true`, which is the opposite of what happened.
    #[test]
    fn the_frame_id_decodes_both_the_variant_and_the_legacy_encoding() {
        assert_eq!(animation_frame_id(&Event::AnimationFrame(7)), Some(7));
        assert_eq!(
            animation_frame_id(&Event::Custom {
                name: ANIMATION_FRAME_EVENT_NAME.into(),
                payload: 7u64.to_le_bytes().to_vec(),
            }),
            Some(7),
            "the legacy byte encoding must keep decoding"
        );
        assert_eq!(animation_frame_id(&Event::Quit), None, "an unrelated event is not a frame");
        assert_eq!(
            animation_frame_id(&Event::Custom { name: "something_else".into(), payload: vec![] }),
            None,
            "a custom event with another name is not a frame"
        );
    }

    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn test_event_loop_animation_frame_dispatch() {
        let mut el = EventLoop::new();
        let anim_fired = Arc::new(AtomicBool::new(false));
        let anim_fired_clone = anim_fired.clone();

        el.set_dispatch_fn(Arc::new(move |_target, event| {
            // The frame is now its own variant. The `Custom` arm is kept in this observer on
            // purpose: it is what would catch a regression that went back to the allocating
            // encoding, and `animation_frame_id` still decodes it for a host that does.
            if let Event::AnimationFrame(_) = event {
                anim_fired_clone.store(true, Ordering::SeqCst);
            }
            if let Event::Custom { name, .. } = event {
                if name.as_ref() == ANIMATION_FRAME_EVENT_NAME {
                    anim_fired_clone.store(true, Ordering::SeqCst);
                }
            }
        }));

        el.request_animation_frame(1u64).unwrap();
        el.start();
        #[cfg(not(alloc_frugal))]
        std::thread::sleep(Duration::from_millis(100));
        el.stop();

        assert!(
            anim_fired.load(Ordering::SeqCst),
            "animation frame event should have been dispatched through the event loop"
        );
    }

    /// A cancelled animation frame never reaches the dispatcher.
    ///
    /// # The defect this pins
    ///
    /// `AnimationFrameRequest` documented itself as something that "can be used to identify or
    /// cancel" a request, but nothing read its `id` and there was no cancel entry point at all
    /// (principle #99: a written-and-never-read field). A host could request a frame, decide
    /// against it, and the callback ran anyway.
    ///
    /// # Why the assertion is on the callback, not on the return value
    ///
    /// `cancel_animation_frame` returning `true` only proves the id was recorded. The guarantee
    /// the API advertises is behavioural — the callback does not run — so the test observes the
    /// callback, and a *different* request in the same loop is asserted to still fire, which is
    /// what stops the test passing because dispatch stopped entirely.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn test_cancelled_animation_frame_never_dispatches() {
        let mut el = EventLoop::new();
        let cancelled_fired = Arc::new(AtomicBool::new(false));
        let kept_fired = Arc::new(AtomicBool::new(false));
        let cancelled_flag = Arc::clone(&cancelled_fired);
        let kept_flag = Arc::clone(&kept_fired);
        // Two requests are distinguished by their ids, which is exactly the payload the host
        // never had to decode before this test existed.
        let cancelled_id = Arc::new(AtomicU64::new(0));
        let seen_id = Arc::clone(&cancelled_id);

        el.set_dispatch_fn(Arc::new(move |_target, event| {
            let Some(id) = animation_frame_id(event) else { return };
            if id == seen_id.load(Ordering::SeqCst) {
                cancelled_flag.store(true, Ordering::SeqCst);
            } else {
                kept_flag.store(true, Ordering::SeqCst);
            }
        }));

        let doomed = el.request_animation_frame(1u64).unwrap();
        let kept = el.request_animation_frame(1u64).unwrap();
        assert_ne!(doomed.id, kept.id, "each request carries its own id");
        cancelled_id.store(doomed.id, Ordering::SeqCst);

        assert!(el.cancel_animation_frame(doomed), "the first cancel reports the change");
        assert!(
            !el.cancel_animation_frame(doomed),
            "a second cancel of the same request changes nothing, so it must not report `true`"
        );

        el.start();
        std::thread::sleep(Duration::from_millis(100));
        el.stop();

        assert!(
            !cancelled_fired.load(Ordering::SeqCst),
            "a cancelled frame must never reach the dispatcher"
        );
        assert!(
            kept_fired.load(Ordering::SeqCst),
            "the un-cancelled frame in the same loop must still fire, or this test would pass \
             for the wrong reason"
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_event_loop_start_stop_idempotent() {
        let mut el = EventLoop::new();

        // Start once
        el.start();
        assert!(el.is_running());

        // Start again — should be a no-op (running flag already true)
        el.start();
        assert!(el.is_running());

        // Stop
        el.stop();
        assert!(!el.is_running());

        // Stop again — should not panic
        el.stop();
        assert!(!el.is_running());
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_event_loop_post_event_without_dispatch() {
        // Posting events should not panic even when no dispatch function is set
        let mut el = EventLoop::new();
        el.start();
        let result = el.post_event(
            1u64,
            Event::Custom { name: "orphan".into(), payload: vec![] },
            EventPriority::Normal,
        );
        assert!(result.is_ok());
        #[cfg(not(alloc_frugal))]
        std::thread::sleep(Duration::from_millis(30));
        el.stop();
    }

    /// A cancel must be refused for a request that is not pending: already dispatched,
    /// never issued here, or belonging to another loop.
    ///
    /// The old `cancel_animation_frame` consulted only the cancelled set, so it returned
    /// `true` for any first-seen id — including a forged handle — and pushed a duplicate
    /// entry that no dispatch could ever consume.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn cancel_is_refused_for_non_pending_handles() {
        let mut el = EventLoop::new();

        // Never issued through this loop.
        assert!(
            !el.cancel_animation_frame(AnimationFrameRequest { id: 999 }),
            "a forged id is not cancellable"
        );

        // Issued by another loop.
        let other = EventLoop::new();
        let foreign = other.request_animation_frame(1u64).unwrap();
        assert!(!el.cancel_animation_frame(foreign), "a foreign loop's handle is not cancellable");

        assert!(el.cancel_animation_frame(el.request_animation_frame(1).unwrap()));
        assert!(el.cancel_animation_frame(el.request_animation_frame(1).unwrap()));
    }

    /// Once a frame is dispatched, its handle can no longer be cancelled.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn cancel_after_dispatch_reports_false() {
        let mut el = EventLoop::new();
        let dispatched = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&dispatched);
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            if animation_frame_id(event).is_some() {
                flag.store(true, Ordering::SeqCst);
            }
        }));

        let handle = el.request_animation_frame(1u64).unwrap();
        el.start();
        let deadline = std::time::Instant::now() + Duration::from_millis(500);
        while !dispatched.load(Ordering::SeqCst) && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        el.stop();
        assert!(dispatched.load(Ordering::SeqCst), "the frame must have been dispatched first");

        assert!(
            !el.cancel_animation_frame(handle),
            "a dispatched frame has nothing left to cancel, so the report must be false"
        );
    }

    /// After a cancellation is consumed by dispatch, cancelling the same id again must
    /// report false rather than recording a stale entry.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn a_consumed_cancellation_makes_later_cancels_false() {
        let mut el = EventLoop::new();
        let handle = el.request_animation_frame(1u64).unwrap();

        assert!(el.cancel_animation_frame(handle), "the first cancel reports the change");
        // Consume the cancellation the way the dispatch phase does.
        assert!(el.take_cancelled_animation_frame(handle.id));
        assert!(
            !el.cancel_animation_frame(handle),
            "the cancellation was consumed, so a later cancel changes nothing"
        );
    }

    /// Cancelling a still-pending frame prevents its callback from running.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn a_pending_cancel_prevents_the_callback() {
        let mut el = EventLoop::new();
        let fired = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&fired);
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            if animation_frame_id(event).is_some() {
                flag.store(true, Ordering::SeqCst);
            }
        }));

        let handle = el.request_animation_frame(1u64).unwrap();
        assert!(el.cancel_animation_frame(handle));

        el.start();
        std::thread::sleep(Duration::from_millis(100));
        el.stop();

        assert!(!fired.load(Ordering::SeqCst), "a cancelled pending frame must never dispatch");
    }

    /// A slow front idle task must not starve a later one forever.
    ///
    /// The Idle phase restarted at index 0 and broke on the 5ms budget every round, so a
    /// first task that always spent the budget left the tail unreachable. The saved
    /// round-robin cursor rotates which task is tried first.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn a_slow_front_idle_task_does_not_starve_the_tail() {
        let slow_runs = Arc::new(AtomicUsize::new(0));
        let tail_runs = Arc::new(AtomicUsize::new(0));

        let mut el = EventLoop::new();
        let slow = Arc::clone(&slow_runs);
        // Threshold 1: eligible on every iteration, and it always burns the 5ms budget.
        assert!(el.add_idle_task(IdleTask::new(1, 1, move || {
            slow.fetch_add(1, Ordering::SeqCst);
            std::thread::sleep(Duration::from_millis(8));
        })));
        let tail = Arc::clone(&tail_runs);
        assert!(el.add_idle_task(IdleTask::new(2, 1, move || {
            tail.fetch_add(1, Ordering::SeqCst);
        })));

        el.start();
        let deadline = std::time::Instant::now() + Duration::from_millis(1_500);
        while tail_runs.load(Ordering::SeqCst) == 0 && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        el.stop();

        assert!(
            tail_runs.load(Ordering::SeqCst) > 0,
            "the task behind a budget-burning head task must eventually run"
        );
        assert!(slow_runs.load(Ordering::SeqCst) > 0, "the slow task still runs too");
    }

    /// The animation-frame state machine: a cancel is accepted only while pending, a
    /// dispatch consumes the cancellation, and an uncancelled dispatch is never skipped.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn the_anim_frame_state_tracks_pending_and_cancelled() {
        let mut state = AnimFrameState::default();
        state.request(1);
        assert!(state.cancel(1), "a pending id can be cancelled");
        assert!(!state.cancel(1), "a second cancel of the same id changes nothing");
        // Dispatch sees the pending-and-cancelled id and must skip it, consuming the entry.
        assert!(state.dispatched_and_cancelled(1), "a cancelled pending frame is skipped");
        assert!(!state.dispatched_and_cancelled(1), "the cancellation was consumed");

        state.request(2);
        assert!(!state.dispatched_and_cancelled(2), "an uncancelled dispatch is not skipped");
        assert!(!state.cancel(2), "a dispatched id is no longer pending");
    }

    /// D09-EVT-08: a frame registered-then-dispatched before the caller cancels must not
    /// be cancellable, and no orphan entry may remain.
    ///
    /// This drives the exact interleaving the fix is about: the id is pending, the loop
    /// dispatches it (removing it from `pending`), and only then does the caller cancel.
    /// The cancel must report `false` (nothing to cancel) and leave both sets empty, rather
    /// than recording a cancellation that no future event can consume.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_frame_dispatched_before_cancel_leaves_no_orphan_entry() {
        let mut el = EventLoop::new();
        let handle = el.request_animation_frame(1u64).unwrap();

        // The request is pending the instant it is issued — the registration precedes
        // publication, so the loop can never dispatch ahead of it.
        {
            let state = lock(&el.cancelled_anim_frames);
            assert!(
                state.pending.contains(&handle.id),
                "the id must be pending immediately after the request returns"
            );
        }

        // The loop dispatches it (this is what the dispatch phase calls).
        assert!(
            !el.take_cancelled_animation_frame(handle.id),
            "an un-cancelled frame is not skipped at dispatch"
        );

        // Now the caller cancels: the frame already ran, so this changes nothing.
        assert!(
            !el.cancel_animation_frame(handle),
            "a frame dispatched before the cancel must report `false`"
        );

        let state = lock(&el.cancelled_anim_frames);
        assert!(state.pending.is_empty(), "no pending entry may survive a dispatched frame");
        assert!(
            state.cancelled.is_empty(),
            "no orphan cancellation entry may be recorded for a dispatched frame"
        );
    }

    /// D09-EVT-08: a long request/dispatch/cancel sequence converges to empty bookkeeping.
    ///
    /// Each request is dispatched immediately and then cancelled; because the registration
    /// precedes publication, every cancel must be refused and neither `pending` nor
    /// `cancelled` may grow.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_request_dispatch_cancel_sequence_leaves_the_sets_empty() {
        let mut el = EventLoop::new();
        for _ in 0..512 {
            let handle = el.request_animation_frame(1u64).unwrap();
            // Dispatch the frame (not cancelled → not skipped).
            assert!(!el.take_cancelled_animation_frame(handle.id));
            // Cancelling after dispatch must be a no-op.
            assert!(!el.cancel_animation_frame(handle));
        }
        let state = lock(&el.cancelled_anim_frames);
        assert!(state.pending.is_empty(), "no pending entries may accumulate");
        assert!(state.cancelled.is_empty(), "no cancelled entries may accumulate");
    }

    /// D09-EVT-08: a cancel before dispatch still wins, and the dispatch then consumes the
    /// cancellation, leaving both sets empty.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_cancel_before_dispatch_is_honoured_and_consumed() {
        let mut el = EventLoop::new();
        let handle = el.request_animation_frame(1u64).unwrap();
        assert!(el.cancel_animation_frame(handle), "a still-pending frame can be cancelled");
        assert!(
            el.take_cancelled_animation_frame(handle.id),
            "the dispatch must skip the cancelled frame"
        );
        let state = lock(&el.cancelled_anim_frames);
        assert!(state.pending.is_empty(), "the cancelled id is no longer pending");
        assert!(state.cancelled.is_empty(), "the cancellation was consumed by dispatch");
    }

    /// D09-EVT-08: under real concurrency the bookkeeping still converges to empty.
    ///
    /// The host thread issues and cancels frames while the loop thread dispatches them —
    /// the actual threading model of the API (`request_animation_frame`/
    /// `cancel_animation_frame` take `&mut self`, so the host owns the loop and `start`
    /// moves only the dispatch onto a thread). Whatever the interleaving, once the loop is
    /// stopped every request is either dispatched or cancelled-and-consumed, so no
    /// `pending` id and no orphan `cancelled` entry may remain. This is the race the fix
    /// closes: before it, a frame dispatched in the publish/registration window left a
    /// permanent `pending` entry and a `cancelled` entry that no event could consume.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn concurrent_request_dispatch_cancel_converges_to_empty_state() {
        let dispatched = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&dispatched);

        let mut el = EventLoop::new();
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            if animation_frame_id(event).is_some() {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }));
        el.start();

        // The host issues and immediately cancels frames while the loop drains them. The
        // cancel races the dispatch, which is the window D09-EVT-08 is about.
        for i in 0..2_000u64 {
            let request = el.request_animation_frame(1u64).unwrap();
            if i % 2 == 0 {
                let _ = el.cancel_animation_frame(request);
            }
        }

        // Let the loop drain what is left, then stop it (which joins the dispatch thread).
        let deadline = std::time::Instant::now() + Duration::from_millis(1_000);
        while std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        el.stop();

        let state = lock(&el.cancelled_anim_frames);
        assert!(
            state.pending.is_empty(),
            "every request must be resolved to dispatched or cancelled; {} still pending",
            state.pending.len()
        );
        assert!(
            state.cancelled.is_empty(),
            "every recorded cancellation must be consumed by a dispatch; {} orphaned",
            state.cancelled.len()
        );
        assert!(
            dispatched.load(Ordering::SeqCst) > 0,
            "the loop must actually have dispatched frames, or the race was never exercised"
        );
    }

    /// The `mini` synchronous pump honours the same cancellation contract as the
    /// threaded loop: a cancelled frame is discarded before dispatch.
    ///
    /// Only compiled (and only runnable) under `alloc_frugal`, because `pump_once` itself is;
    /// there is no desktop equivalent to exercise. The desktop dispatch-phase tests
    /// (`a_pending_cancel_prevents_the_callback`) cover the same contract for the threaded loop.
    #[cfg(alloc_frugal)]
    #[test]
    fn pump_once_honours_cancellation() {
        use core::sync::atomic::AtomicBool;

        let mut el = EventLoop::new();
        let fired = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&fired);
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            if animation_frame_id(event).is_some() {
                flag.store(true, Ordering::SeqCst);
            }
        }));
        el.start();

        let handle = el.request_animation_frame(1).unwrap();
        assert!(el.cancel_animation_frame(handle));
        // The queue still holds the frame event; the pump must skip it.
        assert!(el.pump_once(), "a cancelled frame is consumed work");
        assert!(!fired.load(Ordering::SeqCst), "a cancelled frame must not dispatch in mini");

        // A later, uncancelled frame still dispatches.
        el.request_animation_frame(1).unwrap();
        assert!(el.pump_once());
        assert!(fired.load(Ordering::SeqCst), "an uncancelled frame still dispatches");
    }

    /// D09-EVT-06: the mini pump dispatches the highest-priority event available, not merely
    /// the oldest, and keeps FIFO order within a priority.
    ///
    /// The old `pump_once` dequeued strictly oldest-first and ignored the priority metadata,
    /// so a Normal/Idle event posted before a High one was dispatched first — different
    /// semantics from the threaded loop. This drives the mini pump directly and asserts the
    /// High event comes out first, then the remaining events in their posted order.
    #[cfg(alloc_frugal)]
    #[test]
    fn pump_once_dispatches_by_priority() {
        use std::sync::Mutex;

        let order: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
        let log = Arc::clone(&order);

        let mut el = EventLoop::new();
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            let Event::Custom { name, .. } = event else { return };
            // The event payload's name is `Cow<str>` in one profile and `&str` in the other;
            // `as_ref` is the one spelling both implement, so this test compiles in every
            // profile `check_profiles.sh` builds instead of using the unstable `str::as_str`.
            let event_name: &str = name.as_ref();
            let label = match event_name {
                "idle" => "idle",
                "normal" => "normal",
                "high" => "high",
                _ => return,
            };
            log.lock().unwrap().push(label);
        }));
        el.start();

        // Posted oldest-first: Normal, then Idle, then a High. FIFO would yield Normal first.
        el.post_event(
            1,
            Event::Custom { name: "normal".into(), payload: vec![] },
            EventPriority::Normal,
        )
        .unwrap();
        el.post_event(
            1,
            Event::Custom { name: "idle".into(), payload: vec![] },
            EventPriority::Idle,
        )
        .unwrap();
        el.post_event(
            1,
            Event::Custom { name: "high".into(), payload: vec![] },
            EventPriority::High,
        )
        .unwrap();

        // Three pumps drain the three events.
        assert!(el.pump_once());
        assert!(el.pump_once());
        assert!(el.pump_once());
        assert!(!el.pump_once(), "the queue is empty after three events");

        assert_eq!(
            *order.lock().unwrap(),
            vec!["high", "normal", "idle"],
            "mini must dispatch High before Normal before Idle"
        );

        // Same-priority FIFO: two High events come out in the order posted.
        order.lock().unwrap().clear();
        el.post_event(
            1,
            Event::Custom { name: "high".into(), payload: vec![1] },
            EventPriority::High,
        )
        .unwrap();
        el.post_event(
            1,
            Event::Custom { name: "high".into(), payload: vec![2] },
            EventPriority::High,
        )
        .unwrap();
        assert!(el.pump_once());
        assert!(el.pump_once());
        assert_eq!(order.lock().unwrap().len(), 2, "both High events are dispatched");
    }

    /// Gesture recogniser state is scoped to the interaction target: a tap on one target must
    /// not arm a double-tap on another, and the registry reclaims engines for quiet targets
    /// (D09-EVT-03).
    #[test]
    #[cfg(all(feature = "touch", not(alloc_frugal)))]
    fn gesture_state_is_scoped_to_its_interaction_target() {
        let mut registry = GestureRegistry::new();

        // Target 1: a single tap produces a Tap.
        let _ = registry.process(1, &Event::touch_begin(10, 10, 1), 0);
        let first = registry.process(1, &Event::touch_end(10, 10, 1), 100);
        assert!(matches!(first, Some(Event::Tap { .. })), "a single tap on target 1 is a Tap");

        // Target 2: the same tap must not inherit target 1's first tap into a DoubleTap.
        let _ = registry.process(2, &Event::touch_begin(10, 10, 2), 200);
        let second = registry.process(2, &Event::touch_end(10, 10, 2), 250);
        assert!(
            !matches!(second, Some(Event::DoubleTap { .. })),
            "a first tap on target 2 must not inherit target 1's tap"
        );
        assert!(matches!(second, Some(Event::Tap { .. })), "target 2's own tap is still a Tap");

        // A second tap on target 2, within the window, does complete a double-tap.
        let _ = registry.process(2, &Event::touch_begin(10, 10, 3), 300);
        let third = registry.process(2, &Event::touch_end(10, 10, 3), 350);
        assert!(
            matches!(third, Some(Event::DoubleTap { .. })),
            "two taps on the same target still complete a double tap"
        );
    }

    /// D09-EVT-03: many distinct touch targets are reclaimed once they go quiet, so the
    /// registry stays bounded by *live* targets rather than by history.
    ///
    /// The old map created an engine per target and never removed one, so the count grew with
    /// every distinct target ever touched. This drives 1000 distinct targets and then sweeps
    /// past the idle grace: no orphan engine may remain.
    #[test]
    #[cfg(all(feature = "touch", not(alloc_frugal)))]
    fn many_distinct_targets_are_reclaimed_after_they_go_quiet() {
        let mut registry = GestureRegistry::new();
        // Touch every target at the same instant so "within the grace" is unambiguous.
        let touched_at = 1_000u64;
        for target in 0..1000u64 {
            let _ = registry.process(target, &Event::touch_begin(1, 1, target), touched_at);
            let _ = registry.process(target, &Event::touch_end(1, 1, target), touched_at);
        }
        assert_eq!(registry.len(), 1000, "every target touched so far holds an engine");

        // Sweep at exactly the grace boundary: nothing is reclaimed yet (a target may be
        // waiting for a second tap).
        let within_grace = touched_at + GestureRegistry::idle_grace();
        assert_eq!(registry.sweep(within_grace), 0, "a target within the grace must be kept");
        assert_eq!(registry.len(), 1000);

        // Past the grace, every quiet target is reclaimed.
        let past_grace = touched_at + GestureRegistry::idle_grace() + 1;
        assert_eq!(registry.sweep(past_grace), 1000, "quiet targets must be reclaimed");
        assert_eq!(registry.len(), 0, "no orphan gesture engine may remain");
    }

    /// D09-EVT-03: an explicit release drops one target's engine without touching the others.
    #[test]
    #[cfg(all(feature = "touch", not(alloc_frugal)))]
    fn release_drops_only_the_named_target() {
        let mut registry = GestureRegistry::new();
        let _ = registry.process(1, &Event::touch_begin(0, 0, 1), 0);
        let _ = registry.process(2, &Event::touch_begin(0, 0, 2), 0);
        assert_eq!(registry.len(), 2);

        assert!(registry.release(1), "releasing a present target reports true");
        assert_eq!(registry.len(), 1, "only the named target is dropped");
        assert!(!registry.release(1), "releasing an absent target reports false");
        assert_eq!(registry.len(), 1);
    }

    /// D09-EVT-03: a touch cancel discards the target's engine at once and yields no gesture,
    /// so a withdrawn contact neither commits nor lingers.
    #[test]
    #[cfg(all(feature = "touch", not(alloc_frugal)))]
    fn a_touch_cancel_drops_the_engine_and_produces_no_gesture() {
        let mut registry = GestureRegistry::new();
        let _ = registry.process(7, &Event::touch_begin(10, 10, 1), 0);
        assert_eq!(registry.len(), 1);

        let cancel = crate::event::translator::touch_cancel(crate::core::Point::new(10, 10), 1);
        let produced = registry.process(7, &cancel, 50);
        assert!(produced.is_none(), "a cancel must not produce a completed gesture");
        assert_eq!(registry.len(), 0, "the cancelled target's engine must be dropped");

        // The contact is gone: a following end for the same id carries no state and no Tap.
        let after = registry.process(7, &Event::touch_end(10, 10, 1), 60);
        assert!(after.is_none(), "an end after a cancel must not synthesise a tap");
    }

    /// D09-EVT-03: sweeping by idle time must not break double-tap — an engine kept within
    /// the grace still recognises the second tap.
    #[test]
    #[cfg(all(feature = "touch", not(alloc_frugal)))]
    fn double_tap_still_works_across_a_sweep_within_the_grace() {
        let mut registry = GestureRegistry::new();
        // First tap.
        let _ = registry.process(5, &Event::touch_begin(10, 10, 1), 0);
        let first = registry.process(5, &Event::touch_end(10, 10, 1), 50);
        assert!(matches!(first, Some(Event::Tap { .. })));

        // A sweep inside the grace keeps the engine that remembers the first tap.
        assert_eq!(registry.sweep(200), 0);

        // Second tap within the double-tap window completes the double-tap.
        let _ = registry.process(5, &Event::touch_begin(10, 10, 2), 250);
        let second = registry.process(5, &Event::touch_end(10, 10, 2), 300);
        assert!(
            matches!(second, Some(Event::DoubleTap { .. })),
            "double-tap must survive a sweep that happens within the idle grace"
        );
    }

    /// D09-EVT-04: a burst far larger than the per-turn drain cap is delivered completely and
    /// in order — boundedness is achieved by deferral, not by dropping.
    ///
    /// The queue used to be drained whole each turn and the High/Normal phases walked without
    /// limit. The drain cap bounds one turn's buffer; this asserts the other half of the
    /// contract: nothing is lost and the promised FIFO order survives the deferral across
    /// turns.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn a_burst_larger_than_the_drain_cap_is_delivered_in_order_without_loss() {
        const BURST: usize = PER_TURN_EVENT_DRAIN_CAP * 3 + 7;
        let delivered = Arc::new(std::sync::Mutex::new(Vec::<usize>::new()));
        let order = Arc::clone(&delivered);

        let mut el = EventLoop::new();
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            let Event::Custom { name, payload } = event else { return };
            if name != "burst" {
                return;
            }
            let index = u32::from_le_bytes(payload[0..4].try_into().unwrap()) as usize;
            order.lock().unwrap().push(index);
        }));

        for index in 0..BURST {
            el.post_event(
                1,
                Event::Custom {
                    name: "burst".into(),
                    payload: (index as u32).to_le_bytes().to_vec(),
                },
                EventPriority::Normal,
            )
            .unwrap();
        }

        el.start();
        let deadline = std::time::Instant::now() + Duration::from_millis(5_000);
        while delivered.lock().unwrap().len() < BURST && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(2));
        }
        el.stop();

        let seen = delivered.lock().unwrap().clone();
        assert_eq!(seen.len(), BURST, "every event in the burst must be delivered");
        assert_eq!(
            seen,
            (0..BURST).collect::<Vec<_>>(),
            "deferring past the drain cap must preserve FIFO order"
        );
    }

    /// D09-EVT-04: a High event posted behind a large Normal backlog is still delivered in a
    /// bounded number of turns, and High is always dispatched before Normal within a turn.
    ///
    /// # What "not starved" means here
    ///
    /// The queue is FIFO, so an event behind a backlog is drained in order — but the drain is
    /// capped per turn, so the delay is bounded by the backlog size rather than unbounded, and
    /// the platform pump and frame tasks run every turn regardless. This test pins that: the
    /// High event arrives within a wall-clock deadline, and the phase order (High before the
    /// Normal events drained in the same turn) is observed.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn a_high_event_behind_a_normal_backlog_is_delivered_within_bounded_turns() {
        let saw_high = Arc::new(AtomicBool::new(false));
        let saw_high_flag = Arc::clone(&saw_high);

        let mut el = EventLoop::new();
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            let Event::Custom { name, .. } = event else { return };
            if name == "high" {
                saw_high_flag.store(true, Ordering::SeqCst);
            }
        }));

        let backlog = PER_TURN_EVENT_DRAIN_CAP * 4;
        for _ in 0..backlog {
            el.post_event(
                1,
                Event::Custom { name: "normal".into(), payload: vec![] },
                EventPriority::Normal,
            )
            .unwrap();
        }
        el.post_event(
            1,
            Event::Custom { name: "high".into(), payload: vec![] },
            EventPriority::High,
        )
        .unwrap();

        el.start();
        let deadline = std::time::Instant::now() + Duration::from_millis(3_000);
        while !saw_high.load(Ordering::SeqCst) && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(2));
        }
        el.stop();

        assert!(
            saw_high.load(Ordering::SeqCst),
            "a High event must not be starved: it was not delivered within the bounded deadline"
        );
    }

    /// D09-EVT-04: within a single turn, every High event is dispatched before any Normal
    /// event, even when they are drained together.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn high_events_dispatch_before_normal_events_in_the_same_turn() {
        let order = Arc::new(std::sync::Mutex::new(Vec::<&'static str>::new()));
        let log = Arc::clone(&order);
        let mut el = EventLoop::new();
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            let Event::Custom { name, .. } = event else { return };
            // Only the first few of each kind matter; a short prefix keeps the log small.
            let mut guard = log.lock().unwrap();
            if name == "h" && guard.iter().filter(|entry| **entry == "h").count() < 4 {
                guard.push("h");
            } else if name == "n" && guard.iter().filter(|entry| **entry == "n").count() < 4 {
                guard.push("n");
            }
        }));

        // Interleave so the FIFO order alone would put Normal before High.
        for i in 0..4 {
            el.post_event(
                1,
                Event::Custom { name: "n".into(), payload: vec![i] },
                EventPriority::Normal,
            )
            .unwrap();
            el.post_event(
                1,
                Event::Custom { name: "h".into(), payload: vec![i] },
                EventPriority::High,
            )
            .unwrap();
        }

        el.start();
        let deadline = std::time::Instant::now() + Duration::from_millis(2_000);
        while order.lock().unwrap().len() < 8 && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(2));
        }
        el.stop();

        let seen = order.lock().unwrap().clone();
        let first_four = &seen[..seen.len().min(4)];
        assert!(
            first_four.iter().all(|entry| *entry == "h"),
            "the High phase must run before the Normal phase; observed {seen:?}"
        );
    }

    /// Idle events that exceed the 5ms budget are re-queued and delivered later, in order,
    /// instead of being dropped.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn idle_events_beyond_the_budget_are_delivered_later() {
        let delivered = Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
        let delivered_clone = Arc::clone(&delivered);

        let mut el = EventLoop::new();
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            let Event::Custom { name, payload } = event else { return };
            if name != "idle" {
                return;
            }
            let index = payload.first().copied().unwrap_or(0);
            let first = {
                let mut order = delivered_clone.lock().unwrap();
                order.push(index);
                order.len() == 1
            };
            // Exceed the 5ms idle budget on the first idle event so the rest must be re-queued.
            if first {
                std::thread::sleep(Duration::from_millis(8));
            }
        }));

        for index in 0u8..3 {
            el.post_event(
                1,
                Event::Custom { name: "idle".into(), payload: vec![index] },
                EventPriority::Idle,
            )
            .unwrap();
        }

        el.start();
        let deadline = std::time::Instant::now() + Duration::from_millis(1_500);
        while delivered.lock().unwrap().len() < 3 && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        el.stop();

        assert_eq!(
            *delivered.lock().unwrap(),
            vec![0, 1, 2],
            "idle events beyond the budget are delivered later, in order, not dropped"
        );
    }

    /// W-01: the loop's dispatch helper walks the widget tree with no host-installed resolver.
    ///
    /// The old `set_parent_lookup` was the only switch that enabled capture/target/bubble and no
    /// production caller ever set it, so the whole route was dead outside tests. The loop now
    /// installs a resolver backed by the widget registry at construction; this test registers a
    /// real parent and child and observes both phases without touching `set_parent_lookup`.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32"), not(feature = "mini")))]
    #[test]
    fn the_default_resolver_makes_the_propagation_route_reachable() {
        use crate::core::Rect;
        use crate::widget::{runtime, BaseWidget, Widget, WidgetKind};

        // A minimal mounted control: the registry only needs the `Widget` contract.
        struct Node {
            base: BaseWidget,
        }
        impl crate::event::EventHandler for Node {
            fn handle_event(&mut self, _event: &Event) {}
        }
        impl Widget for Node {
            fn base(&self) -> &BaseWidget {
                &self.base
            }
            fn base_mut(&mut self) -> &mut BaseWidget {
                &mut self.base
            }
        }
        let node = |width: u32, class_name: &'static str| Node {
            base: BaseWidget::new(WidgetKind::Frame, Rect::new(0, 0, width, 100), class_name),
        };

        let parent = runtime::register(Box::new(node(100, "parent"))).expect("parent registers");
        let child = runtime::register(Box::new(node(10, "child"))).expect("child registers");
        runtime::with_widget_mut(child, |widget| widget.base_mut().set_parent(Some(parent)))
            .expect("child is mounted");

        assert_eq!(
            runtime_parent(child),
            Some(parent),
            "the built-in resolver must read the same tree the controls were mounted in"
        );

        let mut el = EventLoop::new();
        let seen = Arc::new(Mutex::new(Vec::new()));
        let seen_in_dispatch = Arc::clone(&seen);
        el.set_dispatch_fn(Arc::new(move |id, _event| {
            seen_in_dispatch.lock().unwrap().push(id);
        }));
        // The helper both loop profiles use; no `set_parent_lookup` call anywhere in this test.
        deliver_event(el.dispatch_fn.as_ref(), &el.parent_lookup, child, &Event::Paint);

        assert_eq!(
            *seen.lock().unwrap(),
            vec![parent, child, parent],
            "capture, target and bubble must all be reached through the default resolver"
        );

        let _ = runtime::unregister(child);
        let _ = runtime::unregister(parent);
    }

    /// W-204: the repeat flag follows the raw key stream, without changing the event layout.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn repeated_key_presses_are_marked_as_repeats_on_the_loop() {
        let mut el = EventLoop::new();
        let observed: Arc<Mutex<Vec<bool>>> = Arc::new(Mutex::new(Vec::new()));
        let observed_in_dispatch = Arc::clone(&observed);
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            if matches!(event, Event::KeyPress { .. }) {
                observed_in_dispatch.lock().unwrap().push(event.is_key_repeat());
            }
        }));
        el.start();
        let key = 65u32;
        el.post_event(1, Event::KeyPress { key, modifiers: 0 }, EventPriority::High).unwrap();
        // A second press with no release in between is the platform auto-repeat.
        el.post_event(1, Event::KeyPress { key, modifiers: 0 }, EventPriority::High).unwrap();
        el.post_event(1, Event::KeyRelease { key, modifiers: 0 }, EventPriority::High).unwrap();
        // After the release the key starts a new run, so this press is not a repeat.
        el.post_event(1, Event::KeyPress { key, modifiers: 0 }, EventPriority::High).unwrap();

        let deadline = std::time::Instant::now() + Duration::from_millis(1_500);
        while observed.lock().unwrap().len() < 3 && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        el.stop();

        assert_eq!(
            *observed.lock().unwrap(),
            vec![false, true, false],
            "the second press of a held key is a repeat; the press after a release is not"
        );
    }

    /// W-P01: one panic barrier per event still contains a panicking handler.
    #[cfg(all(not(alloc_frugal), not(target_arch = "wasm32")))]
    #[test]
    fn a_panicking_handler_does_not_stop_the_next_event() {
        let mut el = EventLoop::new();
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let delivered_in_dispatch = Arc::clone(&delivered);
        el.set_dispatch_fn(Arc::new(move |_target, event| {
            if let Event::Custom { name, payload } = event {
                // Ignore the loop's own `__stop_wake` wake-up.
                if name.as_ref() != "x" {
                    return;
                }
                if payload.first() == Some(&1) {
                    panic!("handler failure");
                }
                delivered_in_dispatch.lock().unwrap().push(payload.clone());
            }
        }));
        el.start();
        el.post_event(1, Event::Custom { name: "x".into(), payload: vec![1] }, EventPriority::High)
            .unwrap();
        el.post_event(1, Event::Custom { name: "x".into(), payload: vec![2] }, EventPriority::High)
            .unwrap();

        let deadline = std::time::Instant::now() + Duration::from_millis(1_500);
        while delivered.lock().unwrap().is_empty() && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        el.stop();

        assert_eq!(
            *delivered.lock().unwrap(),
            vec![vec![2]],
            "the event after a panicking one must still be delivered"
        );
    }
}