frust-widgets 0.6.1

Baseline widget set for Frust: text, buttons, images, flex, stack and scroll containers, and the authoring helpers for custom widgets.
Documentation
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
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
//! [`DragCoordinator`]: the shared drag-session state machine. See the
//! [module docs](super) for the session model, transition rules and
//! notification contract.
//!
//! # Keyboard sessions
//!
//! [`DragCoordinator::lift`] begins a session the same way
//! [`DragCoordinator::arm`] + [`DragCoordinator::begin`] do, but with no
//! pointer driving it: [`DragSession::keyboard`] marks the result, and
//! [`DragCoordinator::update_pointer`]/[`DragCoordinator::resolve_hover`]
//! both no-op for one rather than resolving a registry point that was never
//! reported. Hover instead advances explicitly, through
//! [`DragCoordinator::move_to_next_target`]/
//! [`DragCoordinator::move_to_previous_target`] — cycling the registered
//! targets in registration ("tree") order, wrapping at either end, and
//! starting at the first (next) or last (previous) target when nothing is
//! hovered yet. Cycling skips exactly what pointer resolution skips: a
//! target that accepts a different payload type, and one that did not
//! report visible bounds in the latest paint pass (see the [module
//! docs](super) on *Target resolution*). Both raise the same `Leave`/`Enter` notification pair
//! pointer resolution does, so a target subscriber (or poller — see
//! [`mod@super::target`]) sees identical callbacks regardless of which drove
//! the session. [`DragCoordinator::drop`]/[`DragCoordinator::cancel`] are
//! unchanged: a keyboard session drops on whatever
//! [`move_to_next_target`](DragCoordinator::move_to_next_target)/
//! [`move_to_previous_target`](DragCoordinator::move_to_previous_target)
//! left hovered (or cancels, with nothing hovered) exactly like a pointer
//! release does. The ghost's placement for a keyboard session — anchored at
//! the source's own bounds on [`lift`](DragCoordinator::lift), then at the
//! hovered target's bounds on every `Enter` — is
//! [`mod@super::draggable`]'s concern, not the coordinator's; see its
//! module docs.

use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell};
use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::path::PathBuf;
use std::rc::{Rc, Weak};

use frust_core::FrameTime;
use kurbo::{Point, Rect, Vec2};

/// Identity of a draggable source, allocated by
/// [`DragCoordinator::new_source_id`] and unique within that coordinator.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DragSourceId(u64);

impl DragSourceId {
    /// The raw id.
    pub fn get(self) -> u64 {
        self.0
    }
}

/// Identity of a drop target, allocated by
/// [`DragCoordinator::new_target_id`] and unique within that coordinator.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DragTargetId(u64);

impl DragTargetId {
    /// The raw id.
    pub fn get(self) -> u64 {
        self.0
    }
}

/// Where a drag session came from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DragKind {
    /// Started in-app by a source through [`DragCoordinator::arm`] +
    /// [`DragCoordinator::begin`]; carries whatever payload the source handed
    /// over.
    Internal,
    /// An OS file drag entering the window, started by
    /// [`DragCoordinator::begin_external`]. Has no source; its payload is the
    /// same `Vec<PathBuf>` this variant lists.
    ExternalFiles(Vec<PathBuf>),
}

/// The phase tag of a drag session — what a [`DragStateChange::Phase`]
/// reports and [`DragCoordinator::phase`] reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DragPhase {
    /// No session.
    Idle,
    /// A source was pressed and may start a drag.
    Armed,
    /// A drag is in flight.
    Dragging,
    /// Released over a target; waiting for it to claim the payload and call
    /// [`DragCoordinator::complete_drop`].
    Dropping,
    /// Transient: the session was abandoned. Only ever reported between the
    /// phase it left and `Idle`; [`DragCoordinator::phase`] never reads it.
    Cancelled,
}

/// A snapshot of an in-flight (`Dragging`/`Dropping`) session, minus the
/// payload itself.
#[derive(Clone, Debug, PartialEq)]
pub struct DragSession {
    /// Where the session came from.
    pub kind: DragKind,
    /// The source that started it; `None` for [`DragKind::ExternalFiles`].
    pub source: Option<DragSourceId>,
    /// The point the source was pressed at (for an external session, the
    /// point the OS drag first entered at).
    pub press: Point,
    /// The latest pointer position ([`DragCoordinator::update_pointer`]).
    pub pointer: Point,
    /// Offset from the pointer to the ghost's origin
    /// ([`DragCoordinator::set_ghost_offset`]); zero until a source sets it.
    pub ghost_offset: Vec2,
    /// The target currently under the pointer, if any. While `Dropping` it
    /// is the drop target.
    pub hovered: Option<DragTargetId>,
    /// The payload's type, while the payload is still held — `None` once a
    /// target has moved it out with [`DragCoordinator::take_payload`].
    pub payload_type: Option<TypeId>,
    /// Whether this session was begun by [`DragCoordinator::lift`] rather
    /// than [`DragCoordinator::begin`]/[`DragCoordinator::begin_external`] —
    /// a keyboard session, with no pointer driving it.
    /// [`DragCoordinator::update_pointer`]/[`DragCoordinator::resolve_hover`]
    /// no-op for one; hover instead advances only through
    /// [`DragCoordinator::move_to_next_target`]/
    /// [`DragCoordinator::move_to_previous_target`] (see the [module
    /// docs](self#keyboard-sessions)).
    pub keyboard: bool,
}

impl DragSession {
    /// Where the ghost's origin sits: the pointer plus the ghost offset.
    pub fn ghost_origin(&self) -> Point {
        self.pointer + self.ghost_offset
    }
}

/// A snapshot of a coordinator's state ([`DragCoordinator::state`]).
#[derive(Clone, Debug, PartialEq)]
pub enum DragState {
    /// No session.
    Idle,
    /// `source` was pressed at `press` and may start a drag.
    Armed {
        /// The pressed source.
        source: DragSourceId,
        /// Where it was pressed.
        press: Point,
        /// Whether this arm came from [`DragCoordinator::lift`] rather than
        /// [`DragCoordinator::arm`] — see [`DragSession::keyboard`].
        keyboard: bool,
    },
    /// A drag is in flight.
    Dragging(DragSession),
    /// Released over `target`, awaiting [`DragCoordinator::complete_drop`].
    Dropping {
        /// The session being dropped.
        session: DragSession,
        /// The target it was released over.
        target: DragTargetId,
    },
}

impl DragState {
    /// This state's phase tag.
    pub fn phase(&self) -> DragPhase {
        match self {
            DragState::Idle => DragPhase::Idle,
            DragState::Armed { .. } => DragPhase::Armed,
            DragState::Dragging(_) => DragPhase::Dragging,
            DragState::Dropping { .. } => DragPhase::Dropping,
        }
    }

    /// The in-flight session, while `Dragging` or `Dropping`.
    pub fn session(&self) -> Option<&DragSession> {
        match self {
            DragState::Dragging(session) | DragState::Dropping { session, .. } => Some(session),
            DragState::Idle | DragState::Armed { .. } => None,
        }
    }
}

/// One change a [`DragCoordinator::subscribe`] listener hears.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DragStateChange {
    /// The session moved from `previous` to `next`.
    Phase {
        /// The phase left.
        previous: DragPhase,
        /// The phase entered.
        next: DragPhase,
    },
    /// The pointer moved onto `target` while dragging.
    Enter {
        /// The newly hovered target.
        target: DragTargetId,
    },
    /// The pointer left `target`, or the session hovering it (or about to
    /// drop on it) was cancelled.
    Leave {
        /// The target no longer hovered.
        target: DragTargetId,
    },
    /// The dragged pointer moved to `pointer`.
    Move {
        /// The new pointer position.
        pointer: Point,
    },
}

/// A subscribed [`DragCoordinator::subscribe`] listener.
type Listener = Rc<dyn Fn(DragStateChange)>;

/// An in-flight session's full state, payload included.
struct Session {
    kind: DragKind,
    source: Option<DragSourceId>,
    press: Point,
    pointer: Point,
    ghost_offset: Vec2,
    hovered: Option<DragTargetId>,
    payload: Option<Box<dyn Any>>,
    /// Recorded at `begin` rather than read back off the box, where
    /// `type_id()` would resolve on `Box<dyn Any>` itself.
    payload_type: TypeId,
    /// See [`DragSession::keyboard`].
    keyboard: bool,
}

impl Session {
    fn snapshot(&self) -> DragSession {
        DragSession {
            kind: self.kind.clone(),
            source: self.source,
            press: self.press,
            pointer: self.pointer,
            ghost_offset: self.ghost_offset,
            hovered: self.hovered,
            payload_type: self.payload.as_ref().map(|_| self.payload_type),
            keyboard: self.keyboard,
        }
    }
}

/// The coordinator's internal state machine.
enum Machine {
    Idle,
    Armed {
        source: DragSourceId,
        press: Point,
        keyboard: bool,
    },
    Dragging(Session),
    Dropping {
        session: Session,
        target: DragTargetId,
    },
}

impl Machine {
    fn phase(&self) -> DragPhase {
        match self {
            Machine::Idle => DragPhase::Idle,
            Machine::Armed { .. } => DragPhase::Armed,
            Machine::Dragging(_) => DragPhase::Dragging,
            Machine::Dropping { .. } => DragPhase::Dropping,
        }
    }

    fn session(&self) -> Option<&Session> {
        match self {
            Machine::Dragging(session) | Machine::Dropping { session, .. } => Some(session),
            Machine::Idle | Machine::Armed { .. } => None,
        }
    }

    fn session_mut(&mut self) -> Option<&mut Session> {
        match self {
            Machine::Dragging(session) | Machine::Dropping { session, .. } => Some(session),
            Machine::Idle | Machine::Armed { .. } => None,
        }
    }
}

/// The state every clone of a [`DragCoordinator`] shares.
struct Shared {
    machine: Machine,
    /// The next source/target id handed out (one counter for both kinds).
    next_id: u64,
    /// Subscribed listeners in subscription order, keyed by the id their
    /// guard removes them by.
    listeners: Vec<(u64, Listener)>,
    /// The id the next [`DragCoordinator::subscribe`] hands out.
    next_listener: u64,
    /// Changes produced and not yet delivered to every subscriber.
    queue: VecDeque<DragStateChange>,
    /// Whether a [`DragCoordinator::dispatch`] loop is running further up
    /// the stack — a re-entrant mutation queues behind it instead of
    /// delivering nested.
    dispatching: bool,
    /// Registered drop targets, keyed by id. An entry exists while the
    /// target is registered.
    targets: HashMap<DragTargetId, TargetEntry>,
    /// The registration stamp the next newly registered target takes.
    next_registration: u64,
    /// The paint pass the latest bounds report belongs to — only targets
    /// stamped with it are resolvable (see the [module docs](super)).
    pass: u64,
    /// The frame time that opened `pass`, when a clocked report
    /// ([`DragCoordinator::report_target_bounds`]) opened it.
    pass_frame: Option<FrameTime>,
}

/// One registered drop target's resolution record.
#[derive(Clone, Copy, Debug)]
struct TargetEntry {
    /// When it registered, relative to every other target: a later stamp wins
    /// an overlap in [`DragCoordinator::target_at`].
    registration: u64,
    /// The payload type it accepts, or `None` for a target registered untyped
    /// ([`DragCoordinator::register_target`]), which accepts any.
    accepts: Option<TypeId>,
    /// Its visible window-space bounds as of its latest report; `None` until
    /// the target first reports them, or when that report was clipped to
    /// nothing.
    bounds: Option<Rect>,
    /// The paint pass of its latest report; `None` until it first reports.
    reported: Option<u64>,
}

impl Default for Shared {
    fn default() -> Self {
        Self {
            machine: Machine::Idle,
            next_id: 1,
            listeners: Vec::new(),
            next_listener: 0,
            queue: VecDeque::new(),
            dispatching: false,
            targets: HashMap::new(),
            next_registration: 0,
            pass: 0,
            pass_frame: None,
        }
    }
}

impl Shared {
    /// Abandon whatever is in flight, landing on `Idle`: a hovered target (or
    /// an unclaimed drop's target) hears `Leave`, then the
    /// `→ Cancelled → Idle` pair. Returns the abandoned session, if one was
    /// in flight (`Dragging`/`Dropping`). A no-op from `Idle`.
    fn cancel(&mut self, changes: &mut Vec<DragStateChange>) -> Option<Session> {
        let previous = self.machine.phase();
        let (leave, session) = match std::mem::replace(&mut self.machine, Machine::Idle) {
            Machine::Idle => return None,
            Machine::Armed { .. } => (None, None),
            Machine::Dragging(session) => (session.hovered, Some(session)),
            Machine::Dropping { session, target } => (Some(target), Some(session)),
        };
        if let Some(target) = leave {
            changes.push(DragStateChange::Leave { target });
        }
        changes.push(DragStateChange::Phase {
            previous,
            next: DragPhase::Cancelled,
        });
        changes.push(DragStateChange::Phase {
            previous: DragPhase::Cancelled,
            next: DragPhase::Idle,
        });
        session
    }

    /// The payload type of the session in flight, if any — what a target's
    /// accepted type is gated against.
    fn live_payload_type(&self) -> Option<TypeId> {
        self.machine.session().map(|session| session.payload_type)
    }

    /// `entry`'s bounds if it may take part in resolution or cycling right
    /// now: reported in the latest paint pass, visible (not clipped to
    /// nothing), and — while a session is in flight — accepting its payload
    /// type (an untyped entry accepts any).
    fn resolvable(&self, entry: &TargetEntry, payload: Option<TypeId>) -> Option<Rect> {
        self.resolvable_as_of(entry, payload, self.pass)
    }

    /// [`Shared::resolvable`], against pass number `pass` rather than
    /// always the current one — the building block
    /// [`Shared::target_at_mid_pass`] uses to also admit the pass
    /// immediately before the current one.
    fn resolvable_as_of(
        &self,
        entry: &TargetEntry,
        payload: Option<TypeId>,
        pass: u64,
    ) -> Option<Rect> {
        if entry.reported != Some(pass) {
            return None;
        }
        if let (Some(accepts), Some(payload)) = (entry.accepts, payload)
            && accepts != payload
        {
            return None;
        }
        entry.bounds
    }

    /// The resolvable target whose bounds contain `point` — the latest
    /// registered among overlapping ones (see the [module docs](super)).
    fn target_at(&self, point: Point) -> Option<DragTargetId> {
        let payload = self.live_payload_type();
        self.targets
            .iter()
            .filter(|(_, entry)| {
                self.resolvable(entry, payload)
                    .is_some_and(|rect| rect.contains(point))
            })
            .max_by_key(|(_, entry)| entry.registration)
            .map(|(&id, _)| id)
    }

    /// [`Shared::target_at`], but also admitting a target stamped with the
    /// pass immediately before the current one — for
    /// [`Shared::resolve_hover_mid_pass`], called mid-paint before every
    /// target sharing the coordinator has necessarily repainted the frame
    /// in progress, so a later-painting sibling that simply has not
    /// reported *yet* this pass is not mistaken for one that stopped
    /// reporting altogether. One pass of tolerance only: a target silent
    /// for a whole pass on top of that is excluded exactly as
    /// [`Shared::target_at`] excludes it. The overlap tie-break is
    /// unchanged — later registration still wins regardless of which of
    /// the two passes a candidate's bounds last came from — so a
    /// later-registered target that simply has not repainted yet this pass
    /// still outranks an earlier-registered one that already has, exactly
    /// as it would once both catch up.
    fn target_at_mid_pass(&self, point: Point) -> Option<DragTargetId> {
        let payload = self.live_payload_type();
        let previous = self.pass.checked_sub(1);
        self.targets
            .iter()
            .filter(|(_, entry)| {
                self.resolvable_as_of(entry, payload, self.pass)
                    .or_else(|| {
                        previous.and_then(|pass| self.resolvable_as_of(entry, payload, pass))
                    })
                    .is_some_and(|rect| rect.contains(point))
            })
            .max_by_key(|(_, entry)| entry.registration)
            .map(|(&id, _)| id)
    }

    /// Record a bounds report for `id`, stamped with the paint pass it
    /// belongs to. A clocked report (`frame` is `Some`) opens a new pass when
    /// its frame time differs from the one that opened the current pass; an
    /// unclocked one opens a new pass when this target already reported in
    /// the current one (it is painting again, so a new pass has begun).
    /// Returns whether `id` is registered.
    fn record_bounds(
        &mut self,
        id: DragTargetId,
        bounds: Option<Rect>,
        frame: Option<FrameTime>,
    ) -> bool {
        let Some(reported) = self.targets.get(&id).map(|entry| entry.reported) else {
            return false;
        };
        let opens = match frame {
            Some(frame) => self.pass_frame != Some(frame),
            None => reported == Some(self.pass),
        };
        if opens {
            self.pass += 1;
            self.pass_frame = frame;
        }
        let pass = self.pass;
        if let Some(entry) = self.targets.get_mut(&id) {
            entry.bounds = bounds;
            entry.reported = Some(pass);
        }
        true
    }

    /// While `Dragging`, make `target` the hovered one: the old one (if any)
    /// hears `Leave`, then the new one (if any) `Enter`. Nothing when
    /// unchanged or not `Dragging`.
    fn set_hovered(&mut self, target: Option<DragTargetId>, changes: &mut Vec<DragStateChange>) {
        if let Machine::Dragging(session) = &mut self.machine
            && session.hovered != target
        {
            if let Some(old) = session.hovered {
                changes.push(DragStateChange::Leave { target: old });
            }
            session.hovered = target;
            if let Some(target) = target {
                changes.push(DragStateChange::Enter { target });
            }
        }
    }

    /// While `Dragging`, re-resolve the hovered target under the session's
    /// current pointer against the registry's current bounds. A no-op for a
    /// keyboard session ([`DragSession::keyboard`]) — there is no pointer to
    /// resolve against, so this never overrides what
    /// [`Shared::move_target`] last set.
    fn resolve_hover(&mut self, changes: &mut Vec<DragStateChange>) {
        let Machine::Dragging(session) = &self.machine else {
            return;
        };
        if session.keyboard {
            return;
        }
        let target = self.target_at(session.pointer);
        self.set_hovered(target, changes);
    }

    /// [`Shared::resolve_hover`]'s twin for a caller mid-paint, before
    /// every target sharing the coordinator has necessarily repainted the
    /// frame in progress — see [`DragCoordinator::resolve_hover`]'s doc for
    /// why that matters and [`Shared::target_at_mid_pass`] for the
    /// tolerance itself. Otherwise identical: a no-op for a keyboard
    /// session or outside `Dragging`.
    fn resolve_hover_mid_pass(&mut self, changes: &mut Vec<DragStateChange>) {
        let Machine::Dragging(session) = &self.machine else {
            return;
        };
        if session.keyboard {
            return;
        }
        let target = self.target_at_mid_pass(session.pointer);
        self.set_hovered(target, changes);
    }

    /// `Idle → Armed`. The caller has already left `Idle` reachable.
    fn arm_from_idle(
        &mut self,
        source: DragSourceId,
        press: Point,
        keyboard: bool,
        changes: &mut Vec<DragStateChange>,
    ) {
        debug_assert!(matches!(self.machine, Machine::Idle));
        self.machine = Machine::Armed {
            source,
            press,
            keyboard,
        };
        changes.push(DragStateChange::Phase {
            previous: DragPhase::Idle,
            next: DragPhase::Armed,
        });
    }

    /// Cycle the hovered target by `step` (`1`/`-1`) through the resolvable
    /// targets ([`Shared::resolvable`]: visible in the latest paint pass and
    /// accepting the session's payload type) in registration ("tree") order —
    /// the [`DragCoordinator::move_to_next_target`]/
    /// [`DragCoordinator::move_to_previous_target`] drive. Starts at the
    /// first (`step > 0`) or last (`step < 0`) target when nothing (or a
    /// target no longer resolvable) is hovered, and wraps around at either
    /// end. Raises the same `Leave`/`Enter` pair pointer resolution does
    /// ([`Shared::set_hovered`]). A no-op outside `Dragging` or with no
    /// resolvable targets.
    ///
    /// Nothing here scrolls an off-screen target into view: only a target
    /// visible in the latest paint pass is resolvable at all, so a list
    /// taller than its viewport is only ever cycled across its currently
    /// visible rows (`drag-keyboard-cycle-visible-targets-only`,
    /// `docs/LIMITATIONS.md`).
    fn move_target(&mut self, step: i64, changes: &mut Vec<DragStateChange>) {
        let Machine::Dragging(session) = &self.machine else {
            return;
        };
        let payload = Some(session.payload_type);
        let mut ordered: Vec<(u64, DragTargetId)> = self
            .targets
            .iter()
            .filter(|(_, entry)| self.resolvable(entry, payload).is_some())
            .map(|(&id, entry)| (entry.registration, id))
            .collect();
        if ordered.is_empty() {
            return;
        }
        ordered.sort_unstable();
        let ids: Vec<DragTargetId> = ordered.into_iter().map(|(_, id)| id).collect();
        let len = ids.len() as i64;
        let next = match session
            .hovered
            .and_then(|current| ids.iter().position(|&id| id == current))
        {
            Some(index) => ids[(index as i64 + step).rem_euclid(len) as usize],
            None if step >= 0 => ids[0],
            None => ids[ids.len() - 1],
        };
        self.set_hovered(Some(next), changes);
    }
}

/// A cloneable handle onto one drag scope's session state: sources
/// [`arm`](Self::arm)/[`begin`](Self::begin) a drag and report its pointer
/// with [`update_pointer`](Self::update_pointer), which resolves the hovered
/// target against the registry ([`set_hovered`](Self::set_hovered) overrides
/// it), and it ends in [`drop`](Self::drop) +
/// [`complete_drop`](Self::complete_drop) or [`cancel`](Self::cancel). Every
/// clone shares one state. See the [module docs](super) for the transition
/// rules.
///
/// ```
/// use frust_widgets::drag::{DragCoordinator, DragPhase};
/// use kurbo::{Point, Rect};
///
/// let drag = DragCoordinator::new();
/// let source = drag.new_source_id();
/// let target = drag.new_target_id();
/// drag.register_target(target);
/// drag.set_target_bounds(target, Rect::new(50.0, 0.0, 150.0, 100.0));
///
/// drag.arm(source, Point::new(10.0, 10.0));
/// drag.begin(42_u32);
/// // Resolution: the pointer is inside the target's reported bounds.
/// drag.update_pointer(Point::new(80.0, 40.0));
/// assert_eq!(drag.state().session().and_then(|s| s.hovered), Some(target));
/// assert_eq!(drag.drop(), Some(target));
///
/// // The target claims the payload, then completes the drop.
/// assert_eq!(drag.take_payload::<u32>().as_deref(), Some(&42));
/// drag.complete_drop();
/// assert_eq!(drag.phase(), DragPhase::Idle);
/// ```
#[derive(Clone, Default)]
pub struct DragCoordinator {
    shared: Rc<RefCell<Shared>>,
}

impl fmt::Debug for DragCoordinator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let shared = self.shared.borrow();
        f.debug_struct("DragCoordinator")
            .field("phase", &shared.machine.phase())
            .field("listeners", &shared.listeners.len())
            .finish()
    }
}

impl DragCoordinator {
    /// A coordinator with no session in flight.
    pub fn new() -> Self {
        Self::default()
    }

    /// Allocate a source id, unique within this coordinator.
    pub fn new_source_id(&self) -> DragSourceId {
        DragSourceId(self.next_id())
    }

    /// Allocate a target id, unique within this coordinator.
    pub fn new_target_id(&self) -> DragTargetId {
        DragTargetId(self.next_id())
    }

    fn next_id(&self) -> u64 {
        let mut shared = self.shared.borrow_mut();
        let id = shared.next_id;
        shared.next_id += 1;
        id
    }

    /// A snapshot of the current state (payload excluded).
    pub fn state(&self) -> DragState {
        match &self.shared.borrow().machine {
            Machine::Idle => DragState::Idle,
            Machine::Armed {
                source,
                press,
                keyboard,
            } => DragState::Armed {
                source: *source,
                press: *press,
                keyboard: *keyboard,
            },
            Machine::Dragging(session) => DragState::Dragging(session.snapshot()),
            Machine::Dropping { session, target } => DragState::Dropping {
                session: session.snapshot(),
                target: *target,
            },
        }
    }

    /// The current phase — never [`DragPhase::Cancelled`], which is transient.
    pub fn phase(&self) -> DragPhase {
        self.shared.borrow().machine.phase()
    }

    /// `source` was pressed at `press`: `Idle → Armed`.
    ///
    /// Re-arming while `Armed`, or while an unclaimed drop is still
    /// `Dropping`, cancels that first (`→ Cancelled → Idle`, the drop target
    /// hearing `Leave`), then arms. Arming while `Dragging` is ignored with a
    /// debug-build log — the session in flight owns the pointer. Returns
    /// whether the coordinator is now armed by this call.
    pub fn arm(&self, source: DragSourceId, press: Point) -> bool {
        self.mutate(|shared, changes| {
            if matches!(shared.machine, Machine::Dragging(_)) {
                log_ignored("arm", "a drag is already in flight");
                return false;
            }
            shared.cancel(changes);
            shared.arm_from_idle(source, press, false, changes);
            true
        })
    }

    /// `source` is lifted by keyboard, with no pointer: `Idle → Armed`,
    /// marked as a keyboard session so the [`begin`](Self::begin) that
    /// follows carries [`DragSession::keyboard`] into `Dragging` — see the
    /// [module docs](self#keyboard-sessions). Same re-arm/ignore rules as
    /// [`arm`](Self::arm): re-arming while `Armed` (or while an unclaimed
    /// drop is still `Dropping`) cancels that first; lifting while
    /// `Dragging` is ignored (debug-build log). Returns whether the
    /// coordinator is now armed by this call.
    pub fn lift(&self, source: DragSourceId) -> bool {
        self.mutate(|shared, changes| {
            if matches!(shared.machine, Machine::Dragging(_)) {
                log_ignored("lift", "a drag is already in flight");
                return false;
            }
            shared.cancel(changes);
            shared.arm_from_idle(source, Point::ZERO, true, changes);
            true
        })
    }

    /// Move the hovered target to the next one registered after it
    /// (registration/tree order, wrapping to the first) — the keyboard
    /// `ArrowRight`/`ArrowDown` drive for a [`lift`](Self::lift)ed session.
    /// Only targets pointer resolution would consider take part: those
    /// accepting the session's payload type and visible in the latest paint
    /// pass. Starts at the first of them when nothing is hovered yet.
    /// Raises the same `Leave`/`Enter` pair pointer resolution does. A
    /// no-op outside `Dragging` or with no such targets — see the
    /// [module docs](self#keyboard-sessions).
    ///
    /// Reaches only a target visible in the latest paint pass, and nothing
    /// scrolls an off-screen one into view on the keyboard's behalf — a
    /// list taller than its viewport cycles only across its currently
    /// visible rows (`drag-keyboard-cycle-visible-targets-only`,
    /// `docs/LIMITATIONS.md`).
    pub fn move_to_next_target(&self) {
        self.mutate(|shared, changes| shared.move_target(1, changes));
    }

    /// The mirror of
    /// [`move_to_next_target`](Self::move_to_next_target) — the keyboard
    /// `ArrowLeft`/`ArrowUp` drive, wrapping to the last eligible target.
    /// Carries the same visible-targets-only reach.
    pub fn move_to_previous_target(&self) {
        self.mutate(|shared, changes| shared.move_target(-1, changes));
    }

    /// The armed source starts dragging `payload`: `Armed → Dragging`, with
    /// the pointer at the press point and nothing hovered.
    ///
    /// `begin` without an arm is an error and is ignored (debug-build log),
    /// as is `begin` while `Dropping`. A second `begin` while `Dragging`
    /// cancels the first session (a hovered target hearing `Leave`) and
    /// restarts from the same source with this payload — re-armed at the
    /// first session's press point, then dragging from its current pointer
    /// and ghost offset, so subscribers hear the full
    /// `Dragging → Cancelled → Idle → Armed → Dragging` walk. An external
    /// session has no source to restart from: it is cancelled and this
    /// `begin` ignored. Returns whether a session is now dragging this
    /// payload.
    pub fn begin<T: Any>(&self, payload: T) -> bool {
        self.mutate(|shared, changes| {
            let (source, press, pointer, ghost_offset, keyboard) = match &shared.machine {
                Machine::Idle => {
                    log_ignored("begin", "nothing is armed");
                    return false;
                }
                Machine::Dropping { .. } => {
                    log_ignored("begin", "a drop is still being completed");
                    return false;
                }
                Machine::Armed {
                    source,
                    press,
                    keyboard,
                } => (*source, *press, *press, Vec2::ZERO, *keyboard),
                Machine::Dragging(_) => {
                    let first = shared
                        .cancel(changes)
                        .expect("a Dragging machine cancels to its session");
                    let Some(source) = first.source else {
                        log_ignored("begin", "the cancelled session had no source to restart");
                        return false;
                    };
                    shared.arm_from_idle(source, first.press, first.keyboard, changes);
                    (
                        source,
                        first.press,
                        first.pointer,
                        first.ghost_offset,
                        first.keyboard,
                    )
                }
            };
            shared.machine = Machine::Dragging(Session {
                kind: DragKind::Internal,
                source: Some(source),
                press,
                pointer,
                ghost_offset,
                hovered: None,
                payload: Some(Box::new(payload)),
                payload_type: TypeId::of::<T>(),
                keyboard,
            });
            changes.push(DragStateChange::Phase {
                previous: DragPhase::Armed,
                next: DragPhase::Dragging,
            });
            true
        })
    }

    /// An OS file drag entered at `pointer`: `Idle → Dragging` with
    /// [`DragKind::ExternalFiles`], no source, and `paths` as the payload (a
    /// `Vec<PathBuf>`, so `payload_is::<Vec<PathBuf>>()` holds). Any session
    /// already in flight — armed, dragging or dropping — is cancelled first.
    pub fn begin_external(&self, paths: Vec<PathBuf>, pointer: Point) {
        self.mutate(|shared, changes| {
            shared.cancel(changes);
            shared.machine = Machine::Dragging(Session {
                kind: DragKind::ExternalFiles(paths.clone()),
                source: None,
                press: pointer,
                pointer,
                ghost_offset: Vec2::ZERO,
                hovered: None,
                payload: Some(Box::new(paths)),
                payload_type: TypeId::of::<Vec<PathBuf>>(),
                keyboard: false,
            });
            changes.push(DragStateChange::Phase {
                previous: DragPhase::Idle,
                next: DragPhase::Dragging,
            });
        });
    }

    /// Replace the held `Vec<PathBuf>` payload of an in-flight
    /// [`DragKind::ExternalFiles`] session with `paths`.
    ///
    /// A hover-phase file-drag notification carries no paths of its own (the
    /// platform source delivers one file per hover with no "this is
    /// everything" signal), so a caller that opens the session on hover via
    /// [`begin_external`](Self::begin_external) starts it with an empty list
    /// and calls this once the real list is known — typically right before
    /// [`drop`](Self::drop), when the platform's drop notification finally
    /// carries every path. Notifies nothing: this replaces payload data, not
    /// phase or hover state, so no subscriber needs telling, and the target
    /// that eventually [`take_payload`](Self::take_payload)s it sees exactly
    /// `paths`. A silent no-op unless `Dragging` with `DragKind::ExternalFiles`
    /// — in particular, never while `Dropping` (too late: the target may have
    /// already taken the old payload).
    pub fn set_external_payload(&self, paths: Vec<PathBuf>) {
        if let Machine::Dragging(session) = &mut self.shared.borrow_mut().machine
            && matches!(session.kind, DragKind::ExternalFiles(_))
        {
            session.kind = DragKind::ExternalFiles(paths.clone());
            session.payload = Some(Box::new(paths));
        }
    }

    /// The dragged pointer is at `pointer` (window space): record it, then
    /// resolve the hovered target under it — the latest-registered target
    /// whose reported bounds contain it ([`target_at`](Self::target_at)), or
    /// none. A hover change is reported as `Leave` (the old target) then
    /// `Enter` (the new one), and a changed pointer then as a
    /// [`DragStateChange::Move`], so a newly entered target's first `Move` is
    /// already inside it. Called with an unchanged pointer it still
    /// re-resolves, which is how bounds that moved under a stationary pointer
    /// are picked up (see also [`resolve_hover`](Self::resolve_hover)). A
    /// silent no-op unless `Dragging`.
    ///
    /// Resolution reads the registry only: it never hit-tests the widget tree
    /// (the ghost floats in a transparent overlay pod above it), and a hover
    /// set explicitly with [`set_hovered`](Self::set_hovered) stands only
    /// until the next call.
    ///
    /// A silent no-op for a keyboard session ([`DragSession::keyboard`]) —
    /// nothing drives a real pointer during one, and a stray call must not
    /// fight the hover [`move_to_next_target`](Self::move_to_next_target)/
    /// [`move_to_previous_target`](Self::move_to_previous_target) last set
    /// (see the [module docs](self#keyboard-sessions)).
    pub fn update_pointer(&self, pointer: Point) {
        self.mutate(|shared, changes| {
            let Machine::Dragging(session) = &mut shared.machine else {
                return;
            };
            if session.keyboard {
                return;
            }
            let moved = session.pointer != pointer;
            session.pointer = pointer;
            shared.resolve_hover(changes);
            if moved {
                changes.push(DragStateChange::Move { pointer });
            }
        });
    }

    /// Re-resolve the hovered target under the current pointer against the
    /// registry's current bounds, without moving the pointer — for a pass
    /// that moved targets under a stationary pointer (an auto-scrolled list
    /// re-reporting its rows' bounds). Raises the same `Leave`/`Enter` pair
    /// [`update_pointer`](Self::update_pointer) does, and nothing when the
    /// hover is unchanged. A silent no-op unless `Dragging`.
    ///
    /// Unlike [`update_pointer`](Self::update_pointer), this one tolerates
    /// a target stamped with the pass immediately before the current one:
    /// [`mod@super::auto_scroll`]'s zone calls it right after its own child
    /// paints, which can be *before* a later sibling sharing this
    /// coordinator gets its own turn to repaint in the same frame (a later
    /// column, a `Stack` layer above, an overlay). Without that one-pass
    /// tolerance, the sibling's still-current bounds would read as culled
    /// for the moment between the two, flipping the hover away and back
    /// for no visible reason. A target silent for a whole pass on top of
    /// that one is excluded exactly as `update_pointer` excludes it — the
    /// tolerance never masks a target that has genuinely stopped painting.
    /// `update_pointer`/[`target_at`](Self::target_at) and keyboard cycling
    /// stay strict to the latest pass; a pointer or keyboard event is never
    /// dispatched mid-paint, so they never race a sibling's own turn.
    pub fn resolve_hover(&self) {
        self.mutate(|shared, changes| shared.resolve_hover_mid_pass(changes));
    }

    /// Set where the ghost's origin sits relative to the pointer (see
    /// [`DragSession::ghost_origin`]). Notifies nothing — a source sets it
    /// right after [`begin`](Self::begin), before the ghost first paints. A
    /// silent no-op unless `Dragging`.
    pub fn set_ghost_offset(&self, offset: Vec2) {
        if let Machine::Dragging(session) = &mut self.shared.borrow_mut().machine {
            session.ghost_offset = offset;
        }
    }

    /// Override the hovered target with `target`, bypassing resolution: the
    /// old one (if any) hears `Leave`, then the new one (if any) hears
    /// `Enter`. Nothing when unchanged; a silent no-op unless `Dragging`. The
    /// override stands until the next [`update_pointer`](Self::update_pointer)
    /// or [`resolve_hover`](Self::resolve_hover) re-resolves against the
    /// registry.
    pub fn set_hovered(&self, target: Option<DragTargetId>) {
        self.mutate(|shared, changes| shared.set_hovered(target, changes));
    }

    /// Register an untyped drop target for bounds tracking and resolution:
    /// it accepts a session of any payload type. A target that accepts one
    /// payload type registers with
    /// [`register_target_for`](Self::register_target_for) instead, so
    /// resolution and keyboard cycling skip it for every other type.
    ///
    /// The target is stamped after every target already registered — a later
    /// registration wins an overlap in [`target_at`](Self::target_at).
    /// Idempotent: re-registering an already-registered target is a no-op and
    /// keeps its original stamp and accepted type.
    pub fn register_target(&self, id: DragTargetId) {
        self.register(id, None);
    }

    /// Register a drop target that accepts payloads of type `T` only:
    /// [`target_at`](Self::target_at), pointer resolution and
    /// [`move_to_next_target`](Self::move_to_next_target)/
    /// [`move_to_previous_target`](Self::move_to_previous_target) consider it
    /// only while the session in flight carries a `T` (an
    /// [`DragKind::ExternalFiles`] session carries a `Vec<PathBuf>`).
    /// Otherwise exactly [`register_target`](Self::register_target), same
    /// stamping and idempotence.
    pub fn register_target_for<T: Any>(&self, id: DragTargetId) {
        self.register(id, Some(TypeId::of::<T>()));
    }

    fn register(&self, id: DragTargetId, accepts: Option<TypeId>) {
        let mut shared = self.shared.borrow_mut();
        if shared.targets.contains_key(&id) {
            return;
        }
        let registration = shared.next_registration;
        shared.next_registration += 1;
        shared.targets.insert(
            id,
            TargetEntry {
                registration,
                accepts,
                bounds: None,
                reported: None,
            },
        );
    }

    /// Unregister a drop target. A hovered target is un-hovered and hears
    /// `Leave`; the pending target of an unclaimed drop ends the session
    /// instead — exactly a [`cancel`](Self::cancel): one `Leave`, then
    /// `Dropping → Cancelled → Idle`, the payload discarded — since no one is
    /// left to claim it. A silent no-op for an unregistered target.
    pub fn unregister_target(&self, id: DragTargetId) {
        self.mutate(|shared, changes| {
            shared.targets.remove(&id);
            match &mut shared.machine {
                Machine::Dragging(session) if session.hovered == Some(id) => {
                    session.hovered = None;
                    changes.push(DragStateChange::Leave { target: id });
                }
                Machine::Dropping { target, .. } if *target == id => {
                    shared.cancel(changes);
                }
                _ => {}
            }
        });
    }

    /// Record the window-space bounds of a registered target, unclocked —
    /// see [`report_target_bounds`](Self::report_target_bounds), which a
    /// painted target uses instead. The report is stamped into the current
    /// paint pass, opening a new one when this target already reported in
    /// the current pass. Updates persist across drag sessions. Ignored (with
    /// a debug-build log) if the target is not registered.
    pub fn set_target_bounds(&self, id: DragTargetId, bounds: Rect) {
        if !self
            .shared
            .borrow_mut()
            .record_bounds(id, Some(bounds), None)
        {
            log_ignored("set_target_bounds", "the target is not registered");
        }
    }

    /// Record what a registered target painted at frame `frame`: its visible
    /// window-space `bounds`, already clipped to its ancestors' visible
    /// region — `None` when clipped to nothing, which leaves it resolvable
    /// nowhere. Every report is stamped with a paint pass: a report whose
    /// `frame` differs from the one that opened the current pass opens a new
    /// pass, and only targets that reported in the latest pass resolve or
    /// cycle, so a target that stopped painting (culled, or scrolled out of a
    /// culling container) cannot resolve against stale bounds. A
    /// [`FrameTime::ZERO`] `frame` (no shell clock) falls back to
    /// [`set_target_bounds`](Self::set_target_bounds)'s unclocked stamping.
    /// See the [module docs](super) for the pass contract and its limit.
    /// Ignored (with a debug-build log) if the target is not registered.
    pub fn report_target_bounds(&self, id: DragTargetId, bounds: Option<Rect>, frame: FrameTime) {
        let frame = (frame != FrameTime::ZERO).then_some(frame);
        if !self.shared.borrow_mut().record_bounds(id, bounds, frame) {
            log_ignored("report_target_bounds", "the target is not registered");
        }
    }

    /// Query the latest reported window-space bounds of a registered target,
    /// or `None` if the target is not registered, has not reported yet, or
    /// last reported itself clipped to nothing. Reads the record as-is: it
    /// does not check that the report belongs to the latest paint pass.
    pub fn target_bounds(&self, id: DragTargetId) -> Option<Rect> {
        self.shared
            .borrow()
            .targets
            .get(&id)
            .and_then(|entry| entry.bounds)
    }

    /// The registered target whose reported bounds contain `point` (window
    /// space); where several overlap, the one registered **last** wins — see
    /// the [module docs](super) for why registration order stands in for
    /// paint order. Only targets that reported visible bounds in the latest
    /// paint pass are considered, and — while a session is in flight — only
    /// those accepting its payload type ([`register_target_for`](Self::register_target_for)).
    /// Returns `None` if no such target contains the point.
    pub fn target_at(&self, point: Point) -> Option<DragTargetId> {
        self.shared.borrow().target_at(point)
    }

    /// Whether the session in flight (`Dragging`/`Dropping`) is an OS file
    /// drag ([`DragKind::ExternalFiles`]). `false` with no session in flight.
    pub fn is_external(&self) -> bool {
        self.shared
            .borrow()
            .machine
            .session()
            .is_some_and(|session| matches!(session.kind, DragKind::ExternalFiles(_)))
    }

    /// All registered drop targets, in registration order.
    pub fn registered_targets(&self) -> Vec<DragTargetId> {
        let shared = self.shared.borrow();
        let mut targets: Vec<(u64, DragTargetId)> = shared
            .targets
            .iter()
            .map(|(&id, entry)| (entry.registration, id))
            .collect();
        targets.sort_unstable();
        targets.into_iter().map(|(_, id)| id).collect()
    }

    /// Release the drag: over a hovered target, `Dragging → Dropping` (the
    /// target hears no `Leave` — it is the drop target) and the target is
    /// returned; with nothing hovered, or from `Armed`, exactly
    /// [`cancel`](Self::cancel) and `None`. A no-op (`None`) from `Idle` or
    /// an already-`Dropping` session.
    pub fn drop(&self) -> Option<DragTargetId> {
        self.mutate(|shared, changes| match &shared.machine {
            Machine::Idle | Machine::Dropping { .. } => None,
            Machine::Armed { .. } => {
                shared.cancel(changes);
                None
            }
            Machine::Dragging(session) => {
                let Some(target) = session.hovered else {
                    shared.cancel(changes);
                    return None;
                };
                let Machine::Dragging(session) =
                    std::mem::replace(&mut shared.machine, Machine::Idle)
                else {
                    unreachable!("matched Dragging above");
                };
                shared.machine = Machine::Dropping { session, target };
                changes.push(DragStateChange::Phase {
                    previous: DragPhase::Dragging,
                    next: DragPhase::Dropping,
                });
                Some(target)
            }
        })
    }

    /// The drop target finished: `Dropping → Idle`, discarding the payload
    /// if it was never taken. A silent no-op unless `Dropping`.
    pub fn complete_drop(&self) {
        self.mutate(|shared, changes| {
            if matches!(shared.machine, Machine::Dropping { .. }) {
                shared.machine = Machine::Idle;
                changes.push(DragStateChange::Phase {
                    previous: DragPhase::Dropping,
                    next: DragPhase::Idle,
                });
            }
        });
    }

    /// Abandon whatever is in flight: from any non-`Idle` phase, a hovered
    /// target (or an unclaimed drop's target) hears `Leave`, then
    /// `→ Cancelled → Idle`; the payload is discarded. A no-op from `Idle`.
    pub fn cancel(&self) {
        self.mutate(|shared, changes| {
            shared.cancel(changes);
        });
    }

    /// The OS file drag is over: end a [`DragKind::ExternalFiles`] session
    /// still `Dragging`, exactly as [`cancel`](Self::cancel) would (a hovered
    /// target hears `Leave`, then `→ Cancelled → Idle`), and report whether
    /// one was ended.
    ///
    /// Idempotent and narrow, so every drop target can call it on the same
    /// end-of-drag broadcast and exactly one call does anything: a no-op
    /// (`false`) from `Idle`, from `Armed`, for any internal session (pointer
    /// or keyboard — an OS drag ending says nothing about it), and for an
    /// external session already `Dropping` — that one belongs to the target
    /// it was released over, which claims or cancels it on its own poll.
    pub fn end_external(&self) -> bool {
        self.mutate(|shared, changes| {
            let ends = matches!(
                &shared.machine,
                Machine::Dragging(session) if matches!(session.kind, DragKind::ExternalFiles(_))
            );
            if ends {
                shared.cancel(changes);
            }
            ends
        })
    }

    /// Whether a payload of type `T` is held (`Dragging`/`Dropping`, not yet
    /// taken).
    pub fn payload_is<T: Any>(&self) -> bool {
        self.shared
            .borrow()
            .machine
            .session()
            .is_some_and(|session| {
                session.payload.is_some() && session.payload_type == TypeId::of::<T>()
            })
    }

    /// Borrow the held payload as a `T`, or `None` (no session, payload
    /// taken, or a different type).
    ///
    /// The returned guard borrows the coordinator's shared state: calling any
    /// method that mutates the coordinator (on this or any clone) while it is
    /// alive panics on the borrow. Prefer [`with_payload`](Self::with_payload)
    /// when the read can be scoped to a closure.
    pub fn payload_ref<T: Any>(&self) -> Option<Ref<'_, T>> {
        Ref::filter_map(self.shared.borrow(), |shared| {
            shared
                .machine
                .session()?
                .payload
                .as_ref()?
                .downcast_ref::<T>()
        })
        .ok()
    }

    /// Run `f` over the held payload as a `T`, returning its result, or
    /// `None` (no session, payload taken, or a different type). The shared
    /// state stays borrowed only for the duration of `f`, which must not
    /// mutate the coordinator.
    pub fn with_payload<T: Any, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
        self.payload_ref::<T>().map(|payload| f(&payload))
    }

    /// Move the held payload out as a `T` — only while `Dragging` or
    /// `Dropping`, and only when it is a `T`; otherwise `None` and the
    /// payload stays put. A second take returns `None`.
    pub fn take_payload<T: Any>(&self) -> Option<Box<T>> {
        let mut shared = self.shared.borrow_mut();
        let session = shared.machine.session_mut()?;
        if session.payload_type != TypeId::of::<T>() {
            return None;
        }
        session.payload.take()?.downcast::<T>().ok()
    }

    /// Hear every [`DragStateChange`], in order, until the returned guard is
    /// dropped. Listeners run in subscription order with the coordinator's
    /// state released, so a listener may read or drive the coordinator; see
    /// the [module docs](super) for the ordering guarantee under re-entrancy.
    pub fn subscribe<F: Fn(DragStateChange) + 'static>(&self, listener: F) -> DragSubscription {
        let mut shared = self.shared.borrow_mut();
        let id = shared.next_listener;
        shared.next_listener += 1;
        shared.listeners.push((id, Rc::new(listener)));
        DragSubscription {
            shared: Rc::downgrade(&self.shared),
            id,
        }
    }

    /// Run one mutation against the shared state, then deliver the changes
    /// it produced. The borrow ends before any listener runs.
    fn mutate<R>(&self, f: impl FnOnce(&mut Shared, &mut Vec<DragStateChange>) -> R) -> R {
        let mut changes = Vec::new();
        let result = {
            let mut shared = self.shared.borrow_mut();
            let result = f(&mut shared, &mut changes);
            shared.queue.extend(changes.iter().copied());
            result
        };
        if !changes.is_empty() {
            frust_core::mark_pending_result_flush();
            self.dispatch();
        }
        result
    }

    /// Deliver every queued change to every live listener, in order. A call
    /// made while an outer dispatch is running returns at once: the outer
    /// loop picks up whatever the re-entrant mutation queued, so every
    /// listener hears every change in the order it happened.
    fn dispatch(&self) {
        {
            let mut shared = self.shared.borrow_mut();
            if shared.dispatching {
                return;
            }
            shared.dispatching = true;
        }
        let _guard = DispatchGuard(&self.shared);
        loop {
            let (change, listeners) = {
                let mut shared = self.shared.borrow_mut();
                let Some(change) = shared.queue.pop_front() else {
                    break;
                };
                (change, shared.listeners.clone())
            };
            for (id, listener) in listeners {
                // A listener unsubscribed by an earlier one hears nothing more.
                let live = self
                    .shared
                    .borrow()
                    .listeners
                    .iter()
                    .any(|(other, _)| *other == id);
                if live {
                    listener(change);
                }
            }
        }
    }
}

/// Clears the dispatching flag when a [`DragCoordinator::dispatch`] loop
/// ends — including by a listener's panic, which also drops the undelivered
/// changes rather than replaying them late on the next mutation.
struct DispatchGuard<'a>(&'a RefCell<Shared>);

impl Drop for DispatchGuard<'_> {
    fn drop(&mut self) {
        if let Ok(mut shared) = self.0.try_borrow_mut() {
            shared.dispatching = false;
            if std::thread::panicking() {
                shared.queue.clear();
            }
        }
    }
}

/// The guard [`DragCoordinator::subscribe`] returns: dropping it unsubscribes
/// the listener. Holds the coordinator weakly, so it never keeps it alive.
#[must_use = "dropping a DragSubscription unsubscribes its listener at once"]
pub struct DragSubscription {
    shared: Weak<RefCell<Shared>>,
    id: u64,
}

impl fmt::Debug for DragSubscription {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DragSubscription")
            .field("id", &self.id)
            .finish()
    }
}

impl Drop for DragSubscription {
    fn drop(&mut self) {
        if let Some(shared) = self.shared.upgrade() {
            shared
                .borrow_mut()
                .listeners
                .retain(|(id, _)| *id != self.id);
        }
    }
}

/// Report an ignored call in debug builds; a no-op in release.
fn log_ignored(_call: &str, _why: &str) {
    #[cfg(debug_assertions)]
    eprintln!("frust-widgets: DragCoordinator::{_call} ignored: {_why}");
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use super::*;

    const PRESS: Point = Point::new(10.0, 10.0);
    const MOVED: Point = Point::new(20.0, 30.0);
    const OTHER_PRESS: Point = Point::new(5.0, 5.0);
    const FILE_ENTRY: Point = Point::new(1.0, 2.0);

    /// A coordinator with two sources, two targets and a change log.
    struct Fixture {
        drag: DragCoordinator,
        source: DragSourceId,
        other_source: DragSourceId,
        first: DragTargetId,
        second: DragTargetId,
        log: Rc<RefCell<Vec<DragStateChange>>>,
        _subscription: DragSubscription,
    }

    impl Fixture {
        fn new() -> Self {
            let drag = DragCoordinator::new();
            let log = Rc::new(RefCell::new(Vec::new()));
            let sink = Rc::clone(&log);
            let subscription = drag.subscribe(move |change| sink.borrow_mut().push(change));
            Self {
                source: drag.new_source_id(),
                other_source: drag.new_source_id(),
                first: drag.new_target_id(),
                second: drag.new_target_id(),
                drag,
                log,
                _subscription: subscription,
            }
        }

        fn take_log(&self) -> Vec<DragStateChange> {
            std::mem::take(&mut *self.log.borrow_mut())
        }
    }

    /// The phase a table row starts from.
    #[derive(Clone, Copy, Debug)]
    enum Start {
        Idle,
        Armed,
        /// Dragging an internal payload, nothing hovered.
        Dragging,
        /// Dragging an internal payload over the first target.
        Hovering,
        /// Dropped on the first target, not yet completed.
        Dropping,
        /// Dragging an OS file drop, nothing hovered.
        External,
    }

    impl Start {
        fn reach(self, f: &Fixture) {
            match self {
                Start::Idle => {}
                Start::Armed => {
                    f.drag.arm(f.source, PRESS);
                }
                Start::Dragging => {
                    f.drag.arm(f.source, PRESS);
                    f.drag.begin(7_i32);
                }
                Start::Hovering => {
                    Start::Dragging.reach(f);
                    f.drag.set_hovered(Some(f.first));
                }
                Start::Dropping => {
                    Start::Hovering.reach(f);
                    f.drag.drop();
                }
                Start::External => {
                    f.drag
                        .begin_external(vec![PathBuf::from("/tmp/a.txt")], FILE_ENTRY);
                }
            }
        }
    }

    /// The operation a table row applies.
    #[derive(Clone, Copy, Debug)]
    enum Op {
        Arm,
        Begin,
        BeginExternal,
        Move,
        HoverSecond,
        HoverNone,
        Drop,
        Complete,
        Cancel,
    }

    impl Op {
        fn apply(self, f: &Fixture) {
            match self {
                Op::Arm => {
                    f.drag.arm(f.other_source, OTHER_PRESS);
                }
                Op::Begin => {
                    f.drag.begin("second");
                }
                Op::BeginExternal => {
                    f.drag
                        .begin_external(vec![PathBuf::from("/tmp/b.txt")], FILE_ENTRY);
                }
                Op::Move => f.drag.update_pointer(MOVED),
                Op::HoverSecond => f.drag.set_hovered(Some(f.second)),
                Op::HoverNone => f.drag.set_hovered(None),
                Op::Drop => {
                    f.drag.drop();
                }
                Op::Complete => f.drag.complete_drop(),
                Op::Cancel => f.drag.cancel(),
            }
        }
    }

    /// Symbolic expected changes, resolved against a fixture's ids.
    #[derive(Clone, Copy, Debug)]
    enum Expect {
        Phase(DragPhase, DragPhase),
        EnterSecond,
        LeaveFirst,
        Moved,
    }

    impl Expect {
        fn resolve(self, f: &Fixture) -> DragStateChange {
            match self {
                Expect::Phase(previous, next) => DragStateChange::Phase { previous, next },
                Expect::EnterSecond => DragStateChange::Enter { target: f.second },
                Expect::LeaveFirst => DragStateChange::Leave { target: f.first },
                Expect::Moved => DragStateChange::Move { pointer: MOVED },
            }
        }
    }

    use DragPhase::{Armed, Cancelled, Dragging, Dropping, Idle};

    const CANCEL_FROM_ARMED: &[Expect] = &[
        Expect::Phase(Armed, Cancelled),
        Expect::Phase(Cancelled, Idle),
    ];
    const CANCEL_FROM_DRAGGING: &[Expect] = &[
        Expect::Phase(Dragging, Cancelled),
        Expect::Phase(Cancelled, Idle),
    ];

    /// Every (start phase, operation) pair: the phase it lands on and the
    /// exact change sequence subscribers hear.
    fn table() -> Vec<(Start, Op, DragPhase, Vec<Expect>)> {
        use Expect::{EnterSecond, LeaveFirst, Moved, Phase};
        let cat = |parts: &[&[Expect]]| parts.concat();
        vec![
            // From Idle: only arm and begin_external leave it.
            (Start::Idle, Op::Arm, Armed, vec![Phase(Idle, Armed)]),
            (Start::Idle, Op::Begin, Idle, vec![]),
            (
                Start::Idle,
                Op::BeginExternal,
                Dragging,
                vec![Phase(Idle, Dragging)],
            ),
            (Start::Idle, Op::Move, Idle, vec![]),
            (Start::Idle, Op::HoverSecond, Idle, vec![]),
            (Start::Idle, Op::HoverNone, Idle, vec![]),
            (Start::Idle, Op::Drop, Idle, vec![]),
            (Start::Idle, Op::Complete, Idle, vec![]),
            (Start::Idle, Op::Cancel, Idle, vec![]),
            // From Armed.
            (
                Start::Armed,
                Op::Arm,
                Armed,
                cat(&[CANCEL_FROM_ARMED, &[Phase(Idle, Armed)]]),
            ),
            (
                Start::Armed,
                Op::Begin,
                Dragging,
                vec![Phase(Armed, Dragging)],
            ),
            (
                Start::Armed,
                Op::BeginExternal,
                Dragging,
                cat(&[CANCEL_FROM_ARMED, &[Phase(Idle, Dragging)]]),
            ),
            (Start::Armed, Op::Move, Armed, vec![]),
            (Start::Armed, Op::HoverSecond, Armed, vec![]),
            (Start::Armed, Op::HoverNone, Armed, vec![]),
            (Start::Armed, Op::Drop, Idle, CANCEL_FROM_ARMED.to_vec()),
            (Start::Armed, Op::Complete, Armed, vec![]),
            (Start::Armed, Op::Cancel, Idle, CANCEL_FROM_ARMED.to_vec()),
            // From Dragging with nothing hovered.
            (Start::Dragging, Op::Arm, Dragging, vec![]),
            (
                Start::Dragging,
                Op::Begin,
                Dragging,
                cat(&[
                    CANCEL_FROM_DRAGGING,
                    &[Phase(Idle, Armed), Phase(Armed, Dragging)],
                ]),
            ),
            (
                Start::Dragging,
                Op::BeginExternal,
                Dragging,
                cat(&[CANCEL_FROM_DRAGGING, &[Phase(Idle, Dragging)]]),
            ),
            (Start::Dragging, Op::Move, Dragging, vec![Moved]),
            (
                Start::Dragging,
                Op::HoverSecond,
                Dragging,
                vec![EnterSecond],
            ),
            (Start::Dragging, Op::HoverNone, Dragging, vec![]),
            (
                Start::Dragging,
                Op::Drop,
                Idle,
                CANCEL_FROM_DRAGGING.to_vec(),
            ),
            (Start::Dragging, Op::Complete, Dragging, vec![]),
            (
                Start::Dragging,
                Op::Cancel,
                Idle,
                CANCEL_FROM_DRAGGING.to_vec(),
            ),
            // From Dragging over the first target.
            (Start::Hovering, Op::Arm, Dragging, vec![]),
            (
                Start::Hovering,
                Op::Begin,
                Dragging,
                cat(&[
                    &[LeaveFirst],
                    CANCEL_FROM_DRAGGING,
                    &[Phase(Idle, Armed), Phase(Armed, Dragging)],
                ]),
            ),
            (
                Start::Hovering,
                Op::BeginExternal,
                Dragging,
                cat(&[
                    &[LeaveFirst],
                    CANCEL_FROM_DRAGGING,
                    &[Phase(Idle, Dragging)],
                ]),
            ),
            // The first target was hovered by override and never registered,
            // so resolving under the moved pointer finds nothing.
            (Start::Hovering, Op::Move, Dragging, vec![LeaveFirst, Moved]),
            (
                Start::Hovering,
                Op::HoverSecond,
                Dragging,
                vec![LeaveFirst, EnterSecond],
            ),
            (Start::Hovering, Op::HoverNone, Dragging, vec![LeaveFirst]),
            (
                Start::Hovering,
                Op::Drop,
                Dropping,
                vec![Phase(Dragging, Dropping)],
            ),
            (Start::Hovering, Op::Complete, Dragging, vec![]),
            (
                Start::Hovering,
                Op::Cancel,
                Idle,
                cat(&[&[LeaveFirst], CANCEL_FROM_DRAGGING]),
            ),
            // From Dropping on the first target.
            (
                Start::Dropping,
                Op::Arm,
                Armed,
                vec![
                    LeaveFirst,
                    Phase(Dropping, Cancelled),
                    Phase(Cancelled, Idle),
                    Phase(Idle, Armed),
                ],
            ),
            (Start::Dropping, Op::Begin, Dropping, vec![]),
            (
                Start::Dropping,
                Op::BeginExternal,
                Dragging,
                vec![
                    LeaveFirst,
                    Phase(Dropping, Cancelled),
                    Phase(Cancelled, Idle),
                    Phase(Idle, Dragging),
                ],
            ),
            (Start::Dropping, Op::Move, Dropping, vec![]),
            (Start::Dropping, Op::HoverSecond, Dropping, vec![]),
            (Start::Dropping, Op::HoverNone, Dropping, vec![]),
            (Start::Dropping, Op::Drop, Dropping, vec![]),
            (
                Start::Dropping,
                Op::Complete,
                Idle,
                vec![Phase(Dropping, Idle)],
            ),
            (
                Start::Dropping,
                Op::Cancel,
                Idle,
                vec![
                    LeaveFirst,
                    Phase(Dropping, Cancelled),
                    Phase(Cancelled, Idle),
                ],
            ),
            // From an external (OS file) drag with nothing hovered.
            (Start::External, Op::Arm, Dragging, vec![]),
            // The first is cancelled; with no source to restart from, the
            // second begin is ignored.
            (
                Start::External,
                Op::Begin,
                Idle,
                CANCEL_FROM_DRAGGING.to_vec(),
            ),
            (
                Start::External,
                Op::BeginExternal,
                Dragging,
                cat(&[CANCEL_FROM_DRAGGING, &[Phase(Idle, Dragging)]]),
            ),
            (Start::External, Op::Move, Dragging, vec![Moved]),
            (
                Start::External,
                Op::HoverSecond,
                Dragging,
                vec![EnterSecond],
            ),
            (Start::External, Op::HoverNone, Dragging, vec![]),
            (
                Start::External,
                Op::Drop,
                Idle,
                CANCEL_FROM_DRAGGING.to_vec(),
            ),
            (Start::External, Op::Complete, Dragging, vec![]),
            (
                Start::External,
                Op::Cancel,
                Idle,
                CANCEL_FROM_DRAGGING.to_vec(),
            ),
        ]
    }

    #[test]
    fn every_transition_lands_on_the_tabled_phase_with_the_tabled_changes() {
        let rows = table();
        assert_eq!(rows.len(), 6 * 9, "every start phase x every operation");
        for (start, op, phase, expect) in rows {
            let f = Fixture::new();
            start.reach(&f);
            f.take_log();
            op.apply(&f);
            let expected: Vec<DragStateChange> = expect.iter().map(|e| e.resolve(&f)).collect();
            assert_eq!(f.take_log(), expected, "{start:?} + {op:?}: changes");
            assert_eq!(f.drag.phase(), phase, "{start:?} + {op:?}: phase");
            assert_eq!(
                f.drag.state().phase(),
                phase,
                "{start:?} + {op:?}: state snapshot agrees with phase"
            );
            assert!(
                f.drag.phase() != Cancelled,
                "{start:?} + {op:?}: Cancelled is never a resting phase"
            );
        }
    }

    #[test]
    fn setup_paths_report_their_own_changes() {
        let f = Fixture::new();
        Start::Dropping.reach(&f);
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Phase {
                    previous: Idle,
                    next: Armed
                },
                DragStateChange::Phase {
                    previous: Armed,
                    next: Dragging
                },
                DragStateChange::Enter { target: f.first },
                DragStateChange::Phase {
                    previous: Dragging,
                    next: Dropping
                },
            ]
        );
    }

    #[test]
    fn set_external_payload_replaces_the_held_paths_and_notifies_nothing() {
        let f = Fixture::new();
        f.drag.begin_external(Vec::new(), FILE_ENTRY);
        f.take_log();

        let real_paths = vec![PathBuf::from("/tmp/a.txt"), PathBuf::from("/tmp/b.txt")];
        f.drag.set_external_payload(real_paths.clone());
        assert_eq!(
            f.take_log(),
            Vec::<DragStateChange>::new(),
            "replacing the payload notifies no subscriber"
        );
        assert_eq!(
            f.drag.with_payload::<Vec<PathBuf>, _>(Clone::clone),
            Some(real_paths.clone())
        );

        f.drag.set_hovered(Some(f.first));
        f.take_log();
        assert_eq!(f.drag.drop(), Some(f.first));
        assert_eq!(
            f.drag.take_payload::<Vec<PathBuf>>().map(|b| *b),
            Some(real_paths),
            "the drop target receives the replaced paths, not the empty hover list"
        );
    }

    #[test]
    fn set_external_payload_is_a_no_op_outside_an_external_dragging_session() {
        let f = Fixture::new();
        // Idle: no session at all.
        f.drag
            .set_external_payload(vec![PathBuf::from("/tmp/a.txt")]);
        assert_eq!(f.drag.phase(), DragPhase::Idle);

        // An internal session's payload must never be mistaken for a file list.
        f.drag.arm(f.source, PRESS);
        f.drag.begin(7_i32);
        f.drag
            .set_external_payload(vec![PathBuf::from("/tmp/a.txt")]);
        assert_eq!(f.drag.with_payload::<i32, _>(|v| *v), Some(7));
    }

    #[test]
    fn a_session_snapshot_tracks_source_pointer_hover_and_drop_target() {
        let f = Fixture::new();
        f.drag.arm(f.source, PRESS);
        assert_eq!(
            f.drag.state(),
            DragState::Armed {
                source: f.source,
                press: PRESS,
                keyboard: false,
            }
        );
        f.drag.begin(7_i32);
        f.drag.set_ghost_offset(Vec2::new(-4.0, -6.0));
        f.drag.update_pointer(MOVED);
        f.drag.set_hovered(Some(f.first));
        let DragState::Dragging(session) = f.drag.state() else {
            panic!("expected Dragging");
        };
        assert_eq!(session.kind, DragKind::Internal);
        assert_eq!(session.source, Some(f.source));
        assert_eq!(session.press, PRESS);
        assert_eq!(session.pointer, MOVED);
        assert_eq!(session.ghost_origin(), Point::new(16.0, 24.0));
        assert_eq!(session.hovered, Some(f.first));
        assert_eq!(session.payload_type, Some(TypeId::of::<i32>()));

        assert_eq!(f.drag.drop(), Some(f.first));
        let DragState::Dropping { session, target } = f.drag.state() else {
            panic!("expected Dropping");
        };
        assert_eq!(target, f.first);
        assert_eq!(session.pointer, MOVED);
    }

    #[test]
    fn a_second_begin_restarts_from_the_same_source_at_the_current_pointer() {
        let f = Fixture::new();
        f.drag.arm(f.source, PRESS);
        assert!(f.drag.begin(1_u8));
        f.drag.set_ghost_offset(Vec2::new(-2.0, -2.0));
        f.drag.update_pointer(MOVED);
        assert!(f.drag.begin("replacement"));
        let DragState::Dragging(session) = f.drag.state() else {
            panic!("expected Dragging");
        };
        assert_eq!(session.source, Some(f.source));
        assert_eq!(session.press, PRESS);
        assert_eq!(session.pointer, MOVED);
        assert_eq!(session.ghost_offset, Vec2::new(-2.0, -2.0));
        assert_eq!(session.hovered, None);
        assert!(f.drag.payload_is::<&str>());
        assert!(
            !f.drag.payload_is::<u8>(),
            "the first payload was discarded"
        );
    }

    #[test]
    fn begin_without_arm_and_arm_while_dragging_report_failure() {
        let f = Fixture::new();
        assert!(!f.drag.begin(1_u8), "begin from Idle is ignored");
        assert!(f.drag.arm(f.source, PRESS));
        assert!(f.drag.begin(1_u8));
        assert!(
            !f.drag.arm(f.other_source, OTHER_PRESS),
            "arm while dragging is ignored"
        );
        assert_eq!(
            f.drag.state().session().and_then(|s| s.source),
            Some(f.source)
        );
    }

    #[test]
    fn a_typed_payload_round_trips_and_moves_out_once() {
        #[derive(Debug, PartialEq)]
        struct Card {
            id: u32,
            title: String,
        }
        let f = Fixture::new();
        assert!(!f.drag.payload_is::<Card>(), "no payload while Idle");
        assert!(f.drag.take_payload::<Card>().is_none());
        f.drag.arm(f.source, PRESS);
        assert!(
            f.drag.payload_ref::<Card>().is_none(),
            "no payload while Armed"
        );
        f.drag.begin(Card {
            id: 3,
            title: "three".into(),
        });

        assert!(f.drag.payload_is::<Card>());
        assert!(!f.drag.payload_is::<u32>());
        assert_eq!(f.drag.payload_ref::<Card>().map(|card| card.id), Some(3));
        assert!(
            f.drag.payload_ref::<String>().is_none(),
            "wrong type reads None"
        );
        assert_eq!(
            f.drag
                .with_payload(|card: &Card| card.title.clone())
                .as_deref(),
            Some("three")
        );
        assert_eq!(f.drag.with_payload(|n: &u32| *n), None);
        assert!(
            f.drag.take_payload::<u32>().is_none(),
            "a wrong-type take leaves the payload in place"
        );
        assert!(f.drag.payload_is::<Card>());

        // Still held into Dropping, and taken there.
        f.drag.set_hovered(Some(f.first));
        f.drag.drop();
        let taken = f
            .drag
            .take_payload::<Card>()
            .expect("the drop target claims it");
        assert_eq!(
            *taken,
            Card {
                id: 3,
                title: "three".into()
            }
        );
        assert!(
            f.drag.take_payload::<Card>().is_none(),
            "a second take is None"
        );
        assert!(!f.drag.payload_is::<Card>());
        assert_eq!(
            f.drag.state().session().and_then(|s| s.payload_type),
            None,
            "the snapshot reports the payload gone"
        );
        f.drag.complete_drop();
        assert_eq!(f.drag.phase(), Idle);
    }

    #[test]
    fn a_payload_is_discarded_by_cancel_and_by_an_unclaimed_completion() {
        let f = Fixture::new();
        let probe = Rc::new(());
        f.drag.arm(f.source, PRESS);
        f.drag.begin(Rc::clone(&probe));
        assert_eq!(Rc::strong_count(&probe), 2);
        f.drag.cancel();
        assert_eq!(Rc::strong_count(&probe), 1, "cancel drops the payload");

        f.drag.arm(f.source, PRESS);
        f.drag.begin(Rc::clone(&probe));
        f.drag.set_hovered(Some(f.first));
        f.drag.drop();
        assert_eq!(Rc::strong_count(&probe), 2, "still held while Dropping");
        f.drag.complete_drop();
        assert_eq!(
            Rc::strong_count(&probe),
            1,
            "an unclaimed payload is dropped on completion"
        );
    }

    #[test]
    fn subscribers_hear_every_change_in_subscription_order() {
        let drag = DragCoordinator::new();
        let source = drag.new_source_id();
        let log = Rc::new(RefCell::new(Vec::new()));
        let subscriptions: Vec<DragSubscription> = (0..3)
            .map(|index| {
                let sink = Rc::clone(&log);
                drag.subscribe(move |change| sink.borrow_mut().push((index, change)))
            })
            .collect();
        drag.arm(source, PRESS);
        let armed = DragStateChange::Phase {
            previous: Idle,
            next: Armed,
        };
        assert_eq!(*log.borrow(), vec![(0, armed), (1, armed), (2, armed)]);

        // Dropping a guard unsubscribes that listener only.
        log.borrow_mut().clear();
        let mut subscriptions = subscriptions;
        drop(subscriptions.remove(1));
        drag.cancel();
        let to_cancelled = DragStateChange::Phase {
            previous: Armed,
            next: Cancelled,
        };
        let to_idle = DragStateChange::Phase {
            previous: Cancelled,
            next: Idle,
        };
        assert_eq!(
            *log.borrow(),
            vec![
                (0, to_cancelled),
                (2, to_cancelled),
                (0, to_idle),
                (2, to_idle),
            ]
        );
    }

    #[test]
    fn a_reentrant_listener_keeps_the_global_order_for_every_subscriber() {
        let drag = DragCoordinator::new();
        let source = drag.new_source_id();
        let target = drag.new_target_id();
        let log = Rc::new(RefCell::new(Vec::new()));

        // The first listener cancels as soon as it hears the drop, reading
        // the state while it is at it.
        let handle = drag.clone();
        let sink = Rc::clone(&log);
        let _first = drag.subscribe(move |change| {
            sink.borrow_mut().push(("first", change));
            if change
                == (DragStateChange::Phase {
                    previous: Dragging,
                    next: Dropping,
                })
            {
                assert_eq!(handle.phase(), Dropping);
                handle.cancel();
                assert_eq!(
                    handle.phase(),
                    Idle,
                    "the re-entrant cancel applied at once"
                );
            }
        });
        let sink = Rc::clone(&log);
        let _second = drag.subscribe(move |change| sink.borrow_mut().push(("second", change)));

        drag.arm(source, PRESS);
        drag.begin(());
        drag.set_hovered(Some(target));
        log.borrow_mut().clear();
        drag.drop();

        let dropping = DragStateChange::Phase {
            previous: Dragging,
            next: Dropping,
        };
        let leave = DragStateChange::Leave { target };
        let to_cancelled = DragStateChange::Phase {
            previous: Dropping,
            next: Cancelled,
        };
        let to_idle = DragStateChange::Phase {
            previous: Cancelled,
            next: Idle,
        };
        assert_eq!(
            *log.borrow(),
            vec![
                ("first", dropping),
                ("second", dropping),
                ("first", leave),
                ("second", leave),
                ("first", to_cancelled),
                ("second", to_cancelled),
                ("first", to_idle),
                ("second", to_idle),
            ],
            "the second subscriber hears the drop before the cancel it triggered"
        );
    }

    #[test]
    fn a_listener_unsubscribed_mid_dispatch_hears_nothing_more() {
        let drag = DragCoordinator::new();
        let source = drag.new_source_id();
        let heard = Rc::new(RefCell::new(0_u32));
        let victim: Rc<RefCell<Option<DragSubscription>>> = Rc::new(RefCell::new(None));

        let slot = Rc::clone(&victim);
        let _killer = drag.subscribe(move |_| {
            slot.borrow_mut().take();
        });
        let count = Rc::clone(&heard);
        *victim.borrow_mut() = Some(drag.subscribe(move |_| *count.borrow_mut() += 1));

        drag.arm(source, PRESS);
        assert_eq!(*heard.borrow(), 0);
    }

    #[test]
    fn a_subscription_outliving_its_coordinator_drops_cleanly() {
        let drag = DragCoordinator::new();
        let subscription = drag.subscribe(|_| {});
        drop(drag);
        drop(subscription);
    }

    #[test]
    fn a_panicking_listener_does_not_wedge_dispatch() {
        let drag = DragCoordinator::new();
        let source = drag.new_source_id();
        let heard = Rc::new(RefCell::new(Vec::new()));
        let sink = Rc::clone(&heard);
        let armed = Rc::new(std::cell::Cell::new(true));
        let trip = Rc::clone(&armed);
        let _panicky = drag.subscribe(move |_| {
            if trip.replace(false) {
                panic!("listener failure");
            }
        });
        let _recorder = drag.subscribe(move |change| sink.borrow_mut().push(change));

        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            drag.arm(source, PRESS);
        }));
        assert!(outcome.is_err());
        assert_eq!(drag.phase(), Armed, "the transition itself applied");
        heard.borrow_mut().clear();
        drag.cancel();
        assert_eq!(
            *heard.borrow(),
            vec![
                DragStateChange::Phase {
                    previous: Armed,
                    next: Cancelled
                },
                DragStateChange::Phase {
                    previous: Cancelled,
                    next: Idle
                },
            ],
            "later changes are delivered, the undelivered one is not replayed"
        );
    }

    #[test]
    fn an_external_file_session_runs_its_whole_lifecycle() {
        let f = Fixture::new();
        let paths = vec![PathBuf::from("/tmp/a.txt"), PathBuf::from("/tmp/b.png")];
        f.drag.begin_external(paths.clone(), FILE_ENTRY);
        let DragState::Dragging(session) = f.drag.state() else {
            panic!("expected Dragging");
        };
        assert_eq!(session.kind, DragKind::ExternalFiles(paths.clone()));
        assert_eq!(session.source, None, "an OS drag has no source");
        assert_eq!(session.press, FILE_ENTRY);
        assert_eq!(session.pointer, FILE_ENTRY);
        assert!(f.drag.payload_is::<Vec<PathBuf>>());

        f.drag.update_pointer(MOVED);
        f.drag.set_hovered(Some(f.first));
        f.drag.set_hovered(Some(f.second));
        assert_eq!(f.drag.drop(), Some(f.second));
        assert_eq!(
            f.drag.take_payload::<Vec<PathBuf>>().map(|paths| *paths),
            Some(paths)
        );
        f.drag.complete_drop();
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Phase {
                    previous: Idle,
                    next: Dragging
                },
                DragStateChange::Move { pointer: MOVED },
                DragStateChange::Enter { target: f.first },
                DragStateChange::Leave { target: f.first },
                DragStateChange::Enter { target: f.second },
                DragStateChange::Phase {
                    previous: Dragging,
                    next: Dropping
                },
                DragStateChange::Phase {
                    previous: Dropping,
                    next: Idle
                },
            ]
        );
        assert_eq!(f.drag.state(), DragState::Idle);
    }

    #[test]
    fn an_external_session_cancelled_by_the_os_leaves_its_hovered_target() {
        let f = Fixture::new();
        f.drag
            .begin_external(vec![PathBuf::from("/tmp/a.txt")], FILE_ENTRY);
        f.drag.set_hovered(Some(f.first));
        f.take_log();
        f.drag.cancel();
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Leave { target: f.first },
                DragStateChange::Phase {
                    previous: Dragging,
                    next: Cancelled
                },
                DragStateChange::Phase {
                    previous: Cancelled,
                    next: Idle
                },
            ]
        );
        assert!(!f.drag.payload_is::<Vec<PathBuf>>());
    }

    #[test]
    fn unchanged_pointer_and_hover_notify_nothing() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag
            .set_target_bounds(f.first, Rect::from_center_size(PRESS, (20.0, 20.0)));
        Start::Hovering.reach(&f);
        f.take_log();
        f.drag.update_pointer(PRESS);
        f.drag.set_hovered(Some(f.first));
        assert!(f.take_log().is_empty());
    }

    #[test]
    fn ids_are_unique_and_every_change_raises_a_flush() {
        let f = Fixture::new();
        let mut ids = vec![
            f.source.get(),
            f.other_source.get(),
            f.first.get(),
            f.second.get(),
        ];
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), 4);

        frust_core::take_pending_result_flush();
        f.drag.update_pointer(MOVED); // Idle: no change, no flush
        assert!(!frust_core::take_pending_result_flush());
        f.drag.arm(f.source, PRESS);
        assert!(frust_core::take_pending_result_flush());
    }

    #[test]
    fn clones_share_one_session() {
        let f = Fixture::new();
        let other = f.drag.clone();
        other.arm(f.source, PRESS);
        assert_eq!(f.drag.phase(), Armed);
        assert_eq!(
            f.take_log().len(),
            1,
            "a clone's change reaches the original's subscriber"
        );
    }

    #[test]
    fn register_and_unregister_targets() {
        let f = Fixture::new();
        assert_eq!(f.drag.registered_targets().len(), 0);
        f.drag.register_target(f.first);
        assert_eq!(f.drag.registered_targets().len(), 1);
        assert!(f.drag.registered_targets().contains(&f.first));
        // Re-registering is idempotent.
        f.drag.register_target(f.first);
        assert_eq!(f.drag.registered_targets().len(), 1);
        f.drag.register_target(f.second);
        assert_eq!(f.drag.registered_targets().len(), 2);
        f.drag.unregister_target(f.first);
        assert_eq!(f.drag.registered_targets().len(), 1);
        assert!(!f.drag.registered_targets().contains(&f.first));
        assert!(f.drag.registered_targets().contains(&f.second));
    }

    #[test]
    fn unregister_while_hovered_emits_leave_and_clears_hover() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag.arm(f.source, PRESS);
        f.drag.begin(7_i32);
        f.drag.set_hovered(Some(f.first));
        f.take_log();
        // Unregistering the hovered target emits Leave.
        f.drag.unregister_target(f.first);
        let changes = f.take_log();
        assert_eq!(
            changes,
            vec![DragStateChange::Leave { target: f.first }],
            "unregister while hovered emits Leave"
        );
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            None,
            "hover is cleared after unregister"
        );
    }

    #[test]
    fn unregistering_the_pending_drop_target_ends_the_session() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.arm(f.source, PRESS);
        f.drag.begin(7_i32);
        f.drag.set_hovered(Some(f.first));
        f.drag.drop();
        f.take_log();
        f.drag.unregister_target(f.first);
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Leave { target: f.first },
                DragStateChange::Phase {
                    previous: DragPhase::Dropping,
                    next: DragPhase::Cancelled,
                },
                DragStateChange::Phase {
                    previous: DragPhase::Cancelled,
                    next: DragPhase::Idle,
                },
            ],
            "one Leave, then the session is cancelled"
        );
        assert_eq!(f.drag.state(), DragState::Idle);
        assert!(
            !f.drag.payload_is::<i32>(),
            "the unclaimed payload is discarded"
        );
        // Nothing is left to leave a second time.
        f.drag.complete_drop();
        f.drag.cancel();
        assert!(f.take_log().is_empty());
    }

    #[test]
    fn unregistering_another_target_while_dropping_changes_nothing() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag.arm(f.source, PRESS);
        f.drag.begin(7_i32);
        f.drag.set_hovered(Some(f.first));
        f.drag.drop();
        f.take_log();
        f.drag.unregister_target(f.second);
        assert!(f.take_log().is_empty());
        assert_eq!(f.drag.phase(), DragPhase::Dropping);
    }

    #[test]
    fn set_and_query_target_bounds() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        assert_eq!(f.drag.target_bounds(f.first), None, "unset bounds are None");
        let rect = Rect::from_origin_size(Point::new(10.0, 20.0), (100.0, 50.0));
        f.drag.set_target_bounds(f.first, rect);
        assert_eq!(f.drag.target_bounds(f.first), Some(rect));
        let new_rect = Rect::from_origin_size(Point::new(5.0, 10.0), (200.0, 100.0));
        f.drag.set_target_bounds(f.first, new_rect);
        assert_eq!(f.drag.target_bounds(f.first), Some(new_rect));
    }

    #[test]
    fn set_target_bounds_on_unknown_id_is_ignored() {
        let f = Fixture::new();
        let unregistered = f.drag.new_target_id();
        let rect = Rect::from_origin_size(Point::new(10.0, 20.0), (100.0, 50.0));
        // Should not panic, and should be logged in debug builds.
        f.drag.set_target_bounds(unregistered, rect);
        assert_eq!(f.drag.target_bounds(unregistered), None);
    }

    #[test]
    fn target_at_finds_single_containing_target() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        let rect = Rect::from_origin_size(Point::new(10.0, 10.0), (100.0, 100.0));
        f.drag.set_target_bounds(f.first, rect);
        let point = Point::new(50.0, 50.0);
        assert_eq!(
            f.drag.target_at(point),
            Some(f.first),
            "point inside bounds returns the target"
        );
        let outside = Point::new(200.0, 200.0);
        assert_eq!(
            f.drag.target_at(outside),
            None,
            "point outside all bounds returns None"
        );
    }

    #[test]
    fn a_nested_target_registered_after_its_container_wins() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        // The container, registered first.
        let large = Rect::from_origin_size(Point::new(0.0, 0.0), (200.0, 200.0));
        f.drag.set_target_bounds(f.first, large);
        // A target nested inside it, registered after it.
        let small = Rect::from_origin_size(Point::new(50.0, 50.0), (100.0, 100.0));
        f.drag.set_target_bounds(f.second, small);
        assert_eq!(f.drag.target_at(Point::new(100.0, 100.0)), Some(f.second));
        assert_eq!(
            f.drag.target_at(Point::new(10.0, 10.0)),
            Some(f.first),
            "outside the nested target the container still resolves"
        );
    }

    #[test]
    fn two_overlapping_targets_resolve_to_the_later_registration() {
        let f = Fixture::new();
        // Registered in the opposite order to their ids, and the later one is
        // the larger: registration order alone decides, not id or area.
        f.drag.register_target(f.second);
        f.drag.register_target(f.first);
        f.drag
            .set_target_bounds(f.second, Rect::new(0.0, 0.0, 100.0, 100.0));
        f.drag
            .set_target_bounds(f.first, Rect::new(50.0, 50.0, 300.0, 300.0));
        let overlap = Point::new(75.0, 75.0);
        assert_eq!(f.drag.target_at(overlap), Some(f.first));
        assert_eq!(f.drag.registered_targets(), vec![f.second, f.first]);

        // A drag resolves the same way.
        f.drag.arm(f.source, PRESS);
        f.drag.begin(1_u8);
        f.take_log();
        f.drag.update_pointer(overlap);
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Enter { target: f.first },
                DragStateChange::Move { pointer: overlap },
            ]
        );

        // Re-registering keeps the original stamp; registering anew after an
        // unregister moves the target to the end.
        f.drag.register_target(f.second);
        assert_eq!(f.drag.target_at(overlap), Some(f.first));
        f.drag.unregister_target(f.second);
        f.drag.register_target(f.second);
        f.drag
            .set_target_bounds(f.second, Rect::new(0.0, 0.0, 100.0, 100.0));
        assert_eq!(f.drag.target_at(overlap), Some(f.second));
    }

    #[test]
    fn moving_across_three_targets_enters_and_leaves_each_in_turn() {
        let f = Fixture::new();
        let third = f.drag.new_target_id();
        // Three side-by-side columns with a gap between the second and third.
        let columns = [
            (f.first, Rect::new(0.0, 0.0, 100.0, 300.0)),
            (f.second, Rect::new(100.0, 0.0, 200.0, 300.0)),
            (third, Rect::new(220.0, 0.0, 320.0, 300.0)),
        ];
        for (id, rect) in columns {
            f.drag.register_target(id);
            f.drag.set_target_bounds(id, rect);
        }
        f.drag.arm(f.source, Point::new(50.0, 10.0));
        f.drag.begin(1_u8);
        f.take_log();

        let path = [
            Point::new(50.0, 50.0),   // first
            Point::new(60.0, 60.0),   // still first
            Point::new(150.0, 60.0),  // second
            Point::new(210.0, 60.0),  // the gap
            Point::new(250.0, 60.0),  // third
            Point::new(250.0, 400.0), // below everything
        ];
        for point in path {
            f.drag.update_pointer(point);
        }
        let mv = |pointer: Point| DragStateChange::Move { pointer };
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Enter { target: f.first },
                mv(path[0]),
                mv(path[1]),
                DragStateChange::Leave { target: f.first },
                DragStateChange::Enter { target: f.second },
                mv(path[2]),
                DragStateChange::Leave { target: f.second },
                mv(path[3]),
                DragStateChange::Enter { target: third },
                mv(path[4]),
                DragStateChange::Leave { target: third },
                mv(path[5]),
            ]
        );
        assert_eq!(
            f.drag.drop(),
            None,
            "released outside every target: a cancel"
        );
        assert_eq!(f.drag.phase(), Idle);
    }

    #[test]
    fn an_explicit_hover_stands_until_the_next_resolution() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag
            .set_target_bounds(f.first, Rect::new(0.0, 0.0, 100.0, 100.0));
        Start::Dragging.reach(&f);
        f.drag.set_hovered(Some(f.second));
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second),
            "the override applies at once"
        );
        f.take_log();
        f.drag.update_pointer(Point::new(40.0, 40.0));
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Leave { target: f.second },
                DragStateChange::Enter { target: f.first },
                DragStateChange::Move {
                    pointer: Point::new(40.0, 40.0)
                },
            ]
        );
    }

    #[test]
    fn resolve_hover_follows_bounds_that_move_under_a_still_pointer() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag
            .set_target_bounds(f.first, Rect::new(0.0, 0.0, 100.0, 50.0));
        f.drag
            .set_target_bounds(f.second, Rect::new(0.0, 50.0, 100.0, 100.0));
        f.drag.arm(f.source, PRESS);
        f.drag.begin(1_u8);
        f.drag.update_pointer(Point::new(10.0, 40.0));
        f.take_log();

        // The list scrolls up by 20 px: the second row now sits under the
        // pointer, which has not moved.
        f.drag
            .set_target_bounds(f.first, Rect::new(0.0, -20.0, 100.0, 30.0));
        f.drag
            .set_target_bounds(f.second, Rect::new(0.0, 30.0, 100.0, 80.0));
        assert!(f.take_log().is_empty(), "reporting bounds notifies nothing");
        f.drag.resolve_hover();
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Leave { target: f.first },
                DragStateChange::Enter { target: f.second },
            ]
        );
        f.drag.resolve_hover();
        assert!(f.take_log().is_empty(), "an unchanged hover is silent");

        // Outside `Dragging` it is a no-op.
        f.drag.drop();
        f.take_log();
        f.drag.resolve_hover();
        assert!(f.take_log().is_empty());
    }

    #[test]
    fn target_at_ignores_targets_without_bounds() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        // Only set bounds for the second target.
        let rect = Rect::from_origin_size(Point::new(0.0, 0.0), (100.0, 100.0));
        f.drag.set_target_bounds(f.second, rect);
        let point = Point::new(50.0, 50.0);
        assert_eq!(
            f.drag.target_at(point),
            Some(f.second),
            "ignores registered targets without bounds set"
        );
    }

    #[test]
    fn target_bounds_persist_across_drag_sessions() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        let rect = Rect::from_origin_size(Point::new(10.0, 10.0), (100.0, 100.0));
        f.drag.set_target_bounds(f.first, rect);
        // Start and complete a drag session.
        f.drag.arm(f.source, PRESS);
        f.drag.begin(7_i32);
        f.drag.update_pointer(MOVED);
        f.drag.drop();
        f.drag.complete_drop();
        // Bounds should still be there after the session.
        assert_eq!(f.drag.target_bounds(f.first), Some(rect));
    }

    #[test]
    fn lift_begins_a_keyboard_session_with_no_pointer_resolution() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag
            .set_target_bounds(f.first, Rect::new(0.0, 0.0, 100.0, 100.0));
        assert!(f.drag.lift(f.source));
        assert_eq!(
            f.drag.state(),
            DragState::Armed {
                source: f.source,
                press: Point::ZERO,
                keyboard: true,
            }
        );
        assert!(f.drag.begin(9_u8));
        let DragState::Dragging(session) = f.drag.state() else {
            panic!("expected Dragging");
        };
        assert!(session.keyboard, "begin carries the keyboard flag over");
        assert_eq!(session.hovered, None);

        // A stray pointer report never fights the keyboard session: it
        // resolves nothing even though the pointer lands inside a
        // registered target's bounds.
        f.take_log();
        f.drag.update_pointer(Point::new(50.0, 50.0));
        assert!(f.take_log().is_empty());
        assert_eq!(f.drag.state().session().and_then(|s| s.hovered), None);
        f.drag.resolve_hover();
        assert!(f.take_log().is_empty());
    }

    #[test]
    fn move_to_next_and_previous_target_cycle_in_registration_order_and_wrap() {
        let f = Fixture::new();
        let third = f.drag.new_target_id();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag.register_target(third);
        for id in [f.first, f.second, third] {
            f.drag
                .set_target_bounds(id, Rect::new(0.0, 0.0, 10.0, 10.0));
        }
        f.drag.lift(f.source);
        f.drag.begin(1_u8);
        f.take_log();

        f.drag.move_to_next_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.first),
            "starts at the first registered target"
        );
        f.drag.move_to_next_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second)
        );
        f.drag.move_to_next_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(third)
        );
        f.drag.move_to_next_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.first),
            "wraps back to the first"
        );
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Enter { target: f.first },
                DragStateChange::Leave { target: f.first },
                DragStateChange::Enter { target: f.second },
                DragStateChange::Leave { target: f.second },
                DragStateChange::Enter { target: third },
                DragStateChange::Leave { target: third },
                DragStateChange::Enter { target: f.first },
            ]
        );

        f.drag.move_to_previous_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(third),
            "wraps back to the last going the other way"
        );
    }

    #[test]
    fn move_to_previous_target_starts_at_the_last_when_nothing_is_hovered() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag
            .set_target_bounds(f.first, Rect::new(0.0, 0.0, 10.0, 10.0));
        f.drag
            .set_target_bounds(f.second, Rect::new(0.0, 0.0, 10.0, 10.0));
        f.drag.lift(f.source);
        f.drag.begin(1_u8);
        f.drag.move_to_previous_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second)
        );
    }

    #[test]
    fn move_target_is_a_no_op_outside_dragging_or_with_no_targets() {
        let f = Fixture::new();
        f.drag.move_to_next_target();
        assert_eq!(f.drag.phase(), DragPhase::Idle);
        f.drag.lift(f.source);
        f.take_log();
        f.drag.move_to_next_target();
        assert!(
            f.take_log().is_empty(),
            "Armed is not Dragging yet — still a no-op"
        );
        f.drag.begin(1_u8);
        f.take_log();
        f.drag.move_to_next_target();
        assert!(f.take_log().is_empty(), "no registered targets to cycle");
    }

    #[test]
    fn lift_while_dragging_is_ignored() {
        let f = Fixture::new();
        f.drag.arm(f.source, PRESS);
        f.drag.begin(1_u8);
        assert!(!f.drag.lift(f.other_source));
        assert_eq!(
            f.drag.state().session().and_then(|s| s.source),
            Some(f.source)
        );
    }

    /// A frame time for a clocked bounds report in pass `n`.
    fn frame(n: u64) -> FrameTime {
        FrameTime::from_nanos(n * 16_000_000)
    }

    #[test]
    fn resolution_skips_a_later_registered_target_of_another_payload_type() {
        let f = Fixture::new();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        f.drag.register_target_for::<u8>(f.first);
        f.drag.register_target_for::<u32>(f.second);
        f.drag.set_target_bounds(f.first, rect);
        f.drag.set_target_bounds(f.second, rect);
        let inside = Point::new(50.0, 50.0);
        assert_eq!(
            f.drag.target_at(inside),
            Some(f.second),
            "with no session, the later registration wins as before"
        );

        f.drag.arm(f.source, PRESS);
        f.drag.begin(3_u8);
        assert_eq!(f.drag.target_at(inside), Some(f.first));
        f.take_log();
        f.drag.update_pointer(inside);
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Enter { target: f.first },
                DragStateChange::Move { pointer: inside },
            ],
            "the u8 session resolves onto the u8 target under the u32 one"
        );
        f.drag.resolve_hover();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.first)
        );
    }

    #[test]
    fn resolution_finds_nothing_when_only_other_types_are_under_the_pointer() {
        let f = Fixture::new();
        f.drag.register_target_for::<u32>(f.first);
        f.drag
            .set_target_bounds(f.first, Rect::new(0.0, 0.0, 100.0, 100.0));
        f.drag.arm(f.source, PRESS);
        f.drag.begin("text");
        f.drag.update_pointer(Point::new(50.0, 50.0));
        assert_eq!(f.drag.state().session().and_then(|s| s.hovered), None);
        assert_eq!(f.drag.drop(), None, "released over nothing: a cancel");
        assert_eq!(f.drag.phase(), DragPhase::Idle);
    }

    #[test]
    fn an_external_session_resolves_only_path_list_targets() {
        let f = Fixture::new();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        f.drag.register_target_for::<Vec<PathBuf>>(f.first);
        f.drag.register_target_for::<u32>(f.second);
        f.drag.set_target_bounds(f.first, rect);
        f.drag.set_target_bounds(f.second, rect);
        f.drag
            .begin_external(vec![PathBuf::from("/tmp/a.txt")], FILE_ENTRY);
        f.drag.update_pointer(Point::new(50.0, 50.0));
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.first)
        );
    }

    #[test]
    fn keyboard_cycling_skips_targets_of_another_payload_type() {
        let f = Fixture::new();
        let third = f.drag.new_target_id();
        let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
        f.drag.register_target_for::<u32>(f.first);
        f.drag.register_target_for::<u8>(f.second);
        f.drag.register_target(third);
        for id in [f.first, f.second, third] {
            f.drag.set_target_bounds(id, rect);
        }
        f.drag.lift(f.source);
        f.drag.begin(1_u8);
        let hovered = || f.drag.state().session().and_then(|s| s.hovered);
        f.drag.move_to_next_target();
        assert_eq!(hovered(), Some(f.second), "the u32 target is skipped");
        f.drag.move_to_next_target();
        assert_eq!(hovered(), Some(third), "an untyped target accepts any");
        f.drag.move_to_next_target();
        assert_eq!(hovered(), Some(f.second), "wraps past the u32 target again");
        f.drag.move_to_previous_target();
        assert_eq!(hovered(), Some(third));
    }

    #[test]
    fn a_target_clipped_to_nothing_is_not_resolved_or_cycled() {
        let f = Fixture::new();
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag
            .report_target_bounds(f.first, Some(Rect::new(0.0, 0.0, 100.0, 100.0)), frame(1));
        f.drag.report_target_bounds(f.second, None, frame(1));
        assert_eq!(f.drag.target_bounds(f.second), None);
        assert_eq!(f.drag.target_at(Point::new(50.0, 50.0)), Some(f.first));

        f.drag.lift(f.source);
        f.drag.begin(1_u8);
        f.drag.move_to_next_target();
        f.drag.move_to_next_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.first),
            "the clipped target is never cycled to"
        );
    }

    #[test]
    fn a_target_that_stopped_reporting_is_not_resolved() {
        let f = Fixture::new();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        let inside = Point::new(50.0, 50.0);
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag.report_target_bounds(f.first, Some(rect), frame(1));
        f.drag.report_target_bounds(
            f.second,
            Some(Rect::new(200.0, 0.0, 300.0, 100.0)),
            frame(1),
        );
        assert_eq!(f.drag.target_at(inside), Some(f.first));

        // The next frame paints only the second target: the first keeps its
        // old bounds on record but no longer resolves.
        f.drag.report_target_bounds(
            f.second,
            Some(Rect::new(200.0, 0.0, 300.0, 100.0)),
            frame(2),
        );
        assert_eq!(f.drag.target_bounds(f.first), Some(rect));
        assert_eq!(f.drag.target_at(inside), None);

        f.drag.arm(f.source, PRESS);
        f.drag.begin(1_u8);
        f.drag.update_pointer(inside);
        assert_eq!(f.drag.state().session().and_then(|s| s.hovered), None);

        // Painting again restores it.
        f.drag.report_target_bounds(f.first, Some(rect), frame(3));
        f.drag.resolve_hover();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.first)
        );
    }

    #[test]
    fn resolve_hover_tolerates_a_target_one_pass_behind_but_not_two() {
        let f = Fixture::new();
        let hovered_rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        let elsewhere = Rect::new(200.0, 0.0, 300.0, 100.0);
        let point = Point::new(50.0, 50.0);
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag
            .report_target_bounds(f.first, Some(elsewhere), frame(1));
        f.drag
            .report_target_bounds(f.second, Some(hovered_rect), frame(1));
        f.drag.arm(f.source, PRESS);
        f.drag.begin(1_u8);
        f.drag.update_pointer(point);
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second)
        );
        f.take_log();

        // The next pass: only the first has repainted so far, as if an
        // auto-scroll zone enclosing it called `resolve_hover` right after
        // its own child painted, before a later sibling got its own turn.
        // The second's bounds are one pass behind, not stale, so the hover
        // does not flicker.
        f.drag
            .report_target_bounds(f.first, Some(elsewhere), frame(2));
        f.drag.resolve_hover();
        assert!(
            f.take_log().is_empty(),
            "a target one pass behind is tolerated, not treated as culled"
        );
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second)
        );

        // A further pass with the second still silent: it is now two full
        // passes behind — genuinely stale, the tolerance window has
        // expired, and the culled-target guarantee holds exactly as
        // before.
        f.drag
            .report_target_bounds(f.first, Some(elsewhere), frame(3));
        f.drag.resolve_hover();
        assert_eq!(
            f.take_log(),
            vec![DragStateChange::Leave { target: f.second }],
            "two full passes without repainting is culled, not tolerated"
        );
    }

    #[test]
    fn a_stale_target_is_not_cycled_to() {
        let f = Fixture::new();
        let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag.report_target_bounds(f.first, Some(rect), frame(1));
        f.drag.report_target_bounds(f.second, Some(rect), frame(1));
        f.drag.report_target_bounds(f.second, Some(rect), frame(2));
        f.drag.lift(f.source);
        f.drag.begin(1_u8);
        f.drag.move_to_next_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second)
        );
        f.drag.move_to_next_target();
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second),
            "only the target painted in the latest pass is cycled"
        );
    }

    #[test]
    fn painting_twice_in_one_frame_keeps_the_pass_open() {
        let f = Fixture::new();
        let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag.report_target_bounds(f.first, Some(rect), frame(1));
        f.drag.report_target_bounds(f.second, Some(rect), frame(1));
        f.drag.report_target_bounds(f.second, Some(rect), frame(1));
        assert_eq!(
            f.drag.target_at(Point::new(5.0, 5.0)),
            Some(f.second),
            "same frame time, same pass: both still resolve"
        );
        f.drag.unregister_target(f.second);
        assert_eq!(f.drag.target_at(Point::new(5.0, 5.0)), Some(f.first));
    }

    #[test]
    fn an_unclocked_repeat_report_opens_the_next_pass() {
        let f = Fixture::new();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        let inside = Point::new(50.0, 50.0);
        f.drag.register_target(f.first);
        f.drag.register_target(f.second);
        f.drag.set_target_bounds(f.first, rect);
        f.drag
            .set_target_bounds(f.second, Rect::new(200.0, 0.0, 300.0, 100.0));
        assert_eq!(f.drag.target_at(inside), Some(f.first));
        // The second reports again: a new pass, which the first missed.
        f.drag
            .set_target_bounds(f.second, Rect::new(200.0, 0.0, 300.0, 100.0));
        assert_eq!(f.drag.target_at(inside), None);
        // A zero frame time counts as unclocked.
        f.drag
            .report_target_bounds(f.first, Some(rect), FrameTime::ZERO);
        assert_eq!(f.drag.target_at(inside), Some(f.first));
    }

    #[test]
    fn later_registration_still_wins_among_visible_type_matching_overlaps() {
        let f = Fixture::new();
        let third = f.drag.new_target_id();
        let fourth = f.drag.new_target_id();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        let inside = Point::new(50.0, 50.0);
        f.drag.register_target_for::<u8>(f.first);
        f.drag.register_target_for::<u8>(f.second);
        // Registered later still, but stale and of another type respectively.
        f.drag.register_target_for::<u8>(third);
        f.drag.register_target_for::<u32>(fourth);
        f.drag.report_target_bounds(third, Some(rect), frame(1));
        for id in [f.first, f.second, fourth] {
            f.drag.report_target_bounds(id, Some(rect), frame(2));
        }
        f.drag.arm(f.source, PRESS);
        f.drag.begin(1_u8);
        f.drag.update_pointer(inside);
        assert_eq!(
            f.drag.state().session().and_then(|s| s.hovered),
            Some(f.second)
        );
    }

    #[test]
    fn is_external_reports_the_kind_of_the_session_in_flight() {
        let f = Fixture::new();
        assert!(!f.drag.is_external());
        f.drag.arm(f.source, PRESS);
        assert!(!f.drag.is_external());
        f.drag.begin(1_u8);
        assert!(!f.drag.is_external());
        f.drag.cancel();
        f.drag.register_target(f.first);
        f.drag
            .begin_external(vec![PathBuf::from("/tmp/a.txt")], FILE_ENTRY);
        assert!(f.drag.is_external());
        f.drag.set_hovered(Some(f.first));
        f.drag.drop();
        assert!(f.drag.is_external(), "still external while Dropping");
        f.drag.complete_drop();
        assert!(!f.drag.is_external());
    }

    #[test]
    fn end_external_ends_a_hovering_external_session_once() {
        let f = Fixture::new();
        f.drag
            .begin_external(vec![PathBuf::from("/tmp/a.txt")], FILE_ENTRY);
        f.drag.set_hovered(Some(f.first));
        f.take_log();

        assert!(f.drag.end_external(), "the first call ends it");
        assert_eq!(
            f.take_log(),
            vec![
                DragStateChange::Leave { target: f.first },
                DragStateChange::Phase {
                    previous: Dragging,
                    next: Cancelled
                },
                DragStateChange::Phase {
                    previous: Cancelled,
                    next: Idle
                },
            ]
        );
        assert_eq!(f.drag.state(), DragState::Idle);

        assert!(!f.drag.end_external(), "every later call is a no-op");
        assert!(f.take_log().is_empty());
    }

    #[test]
    fn end_external_leaves_internal_armed_and_dropping_sessions_alone() {
        let f = Fixture::new();
        assert!(!f.drag.end_external(), "nothing in flight");

        f.drag.arm(f.source, PRESS);
        assert!(!f.drag.end_external());
        assert_eq!(f.drag.phase(), DragPhase::Armed);

        f.drag.begin(1_u8);
        assert!(!f.drag.end_external());
        assert_eq!(f.drag.phase(), DragPhase::Dragging);
        f.drag.cancel();

        assert!(f.drag.lift(f.source), "a keyboard session");
        f.drag.begin(2_u8);
        assert!(!f.drag.end_external());
        assert!(
            f.drag.payload_is::<u8>(),
            "the keyboard session is untouched"
        );
        f.drag.cancel();

        f.drag
            .begin_external(vec![PathBuf::from("/tmp/a.txt")], FILE_ENTRY);
        f.drag.set_hovered(Some(f.first));
        assert_eq!(f.drag.drop(), Some(f.first));
        f.take_log();
        assert!(
            !f.drag.end_external(),
            "a released drop is its target's to claim"
        );
        assert!(f.take_log().is_empty());
        assert_eq!(f.drag.phase(), DragPhase::Dropping);
    }
}