pdfrum-form 0.1.0

Form interaction: events, focus, the edit control, the commit cascade
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
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
//! Applying one event to a session: the function the whole crate exists to
//! provide.
//!
//! Every decision here is already a pure function elsewhere — `hit`,
//! `field::text`, `edit::ops`. Routing sequences those answers, and owns one
//! thing: **when a field's interaction state comes into being, and when it is
//! written back to an appearance.**
//!
//! **State is built lazily, once.** The first event to touch a field reads its
//! value, options and flags out of the file; every later event finds it there.
//!
//! **The appearance is produced on the way out, not stored.** A [`Response`]
//! carries what a changed field should draw; nothing is cached, because the
//! appearance is a pure function of the state and the file.

use pdfrum_doc::ap::{self, TextFont};
use pdfrum_doc::vt;
use pdfrum_object::{Dict, Resolve};

use crate::cascade::{Cascade, FieldRef, Keystroke, KeystrokeOutcome, PointerTrigger};
use crate::commit;
use crate::edit::ops::{self, TextEdit};
use crate::event::{Button, Event, Key, Modifiers, Point};
use crate::field::text::{Disposition, Motion, TextAction};
use crate::field::{self, ChoiceState, FieldState, ToggleKind, ToggleState};
use crate::hit::{self, Permissions};
use crate::page::{PageForm, WidgetInfo};

/// `/A` — the action an annotation performs when it is activated.
const ACTION: &pdfrum_object::Name = &pdfrum_object::Name::from_static(b"A");
use crate::session::{AnnotId, DragAnchor, FieldId, FocusTarget, FormSession};
use crate::update::{AppearanceUpdate, Response, UpdateKind};
use crate::{focus, tab};

/// Everything routing needs that is not the session or the event.
///
/// A borrowed view rather than an owned context object: it is assembled at
/// the call site from things the caller already has, and it owns nothing.
/// # Examples
///
/// Everything here is read from the file before any event is applied; the
/// context borrows it and owns nothing:
///
/// ```
/// use pdfrum_doc::ap;
/// use pdfrum_form::route::Context;
/// use pdfrum_form::{FormSession, NoScripts, Permissions, read_page};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// // The page's widgets, read once.
/// let page = read_page(0, &page_dict, &catalog, &resolve);
/// let mut build = pdfrum_page::BuildContext::new();
/// // The fonts the form's `/DR` declares.
/// let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
///
/// let ctx = Context {
///     page: &page,
///     catalog: &catalog,
///     resolve: &resolve,
///     fonts: &fonts,
///     permissions: Permissions::ALL,
/// };
/// assert_eq!(ctx.page.widgets.len(), 1);
///
/// // The session and the cascade are the caller's; the context is rebuilt
/// // per page, the session outlives every event.
/// let mut session = FormSession::new();
/// let mut cascade = NoScripts;
/// # let _ = (&mut session, &mut cascade);
/// ```
pub struct Context<'a, R: Resolve> {
    /// The page the event happened on, already read.
    pub page: &'a PageForm,
    /// The document catalog, for the form's default resources.
    pub catalog: &'a Dict,
    /// The object resolver.
    pub resolve: &'a R,
    /// The fonts the form's `/DR` declares.
    pub fonts: &'a ap::FormFonts,
    /// What the document permits.
    pub permissions: Permissions,
}

impl<R: Resolve> Context<'_, R> {
    /// The widget at a raw `/Annots` index, if there is one.
    fn widget(&self, id: AnnotId) -> Option<&WidgetInfo> {
        self.page.widgets.iter().find(|w| w.id == id)
    }

    /// The widget a field's state was built from — its first control.
    fn widget_of_field(&self, field: FieldId) -> Option<&WidgetInfo> {
        self.page.widgets.iter().find(|w| w.field == field)
    }

    /// The page-local field a document-wide field position names, when one of
    /// its widgets is on this page.
    ///
    /// The two spaces are different and only this converts between them: see
    /// `page`'s module documentation, and [`PageForm::field_of_index`].
    fn field_of_index(&self, index: u32) -> Option<FieldId> {
        self.page.field_of_index(index)
    }
}

/// Applies one event to a session.
///
/// The single entry point, and a total function: every event has an answer,
/// including "nothing here", which is [`Response::ignored`].
///
/// # Where the `f64` stops
///
/// An [`Event`]'s point is a [`kurbo::Point`], and **this function is the one
/// place it is narrowed** to `f32`, before any comparison. Every geometric
/// query below here compares `f32` against widget edges already rounded the
/// same way; letting an `f64` reach one of them would move an inclusive edge,
/// or a caret across a glyph boundary.
/// # Examples
///
/// A click is three events, and the field's interaction state comes into
/// being on the first one that touches it:
///
/// ```
/// # use kurbo::Point;
/// # use pdfrum_form::field::FieldState;
/// # use pdfrum_form::{Button, Event, FieldId, Modifiers};
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// let at = Point { x: 100.0, y: 115.0 };
/// for event in [
///     Event::MouseMove { at, modifiers: Modifiers::NONE },
///     Event::MouseDown { button: Button::Left, at, modifiers: Modifiers::NONE },
///     Event::MouseUp { button: Button::Left, at, modifiers: Modifiers::NONE },
/// ] {
///     route::apply(&mut session, &ctx, &mut cascade, event);
/// }
///
/// // Typing goes to whatever the click focused.
/// let response = route::apply(&mut session, &ctx, &mut cascade,
///     Event::Char { ch: 'X', modifiers: Modifiers::NONE });
/// assert!(response.consumed);
/// // Every changed field arrives as an appearance the caller re-renders.
/// for update in &response.updates {
///     let _ = update.annot;
/// }
///
/// let Some(FieldState::Text(state)) = session.fields.get(&FieldId(0)) else {
///     unreachable!("the click built the field's state")
/// };
/// assert_eq!(state.edit.text, "oldX");
///
/// // A click that lands on no widget is still this session's business while
/// // a field holds the keyboard: it drops focus, which commits the edit.
/// let miss = route::apply(&mut session, &ctx, &mut cascade,
///     Event::MouseDown { button: Button::Left, at: Point { x: 5.0, y: 5.0 },
///         modifiers: Modifiers::NONE });
/// assert!(miss.consumed);
/// assert!(route::focus_of(&session, &ctx).is_none());
///
/// // With nothing focused, the same click is answered rather than dropped —
/// // every event has an answer, and this one is "nothing here".
/// let again = route::apply(&mut session, &ctx, &mut cascade,
///     Event::MouseDown { button: Button::Left, at: Point { x: 5.0, y: 5.0 },
///         modifiers: Modifiers::NONE });
/// assert!(!again.consumed);
/// ```
pub fn apply<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    event: Event,
) -> Response {
    let mut response = route(session, ctx, cascade, event);
    // A script the event ran may have called `Field.setFocus`, which records
    // a request rather than moving the keyboard itself. Spending it here is
    // what `SetFocusAnnot` does at the end of the native call, and it is
    // spent *after* the event's own routing so the field the event was about
    // has already committed.
    response.absorb(honour_focus_requests(session, ctx, cascade));
    response
}

/// Spends every `Field.setFocus` a script left, until none is left.
///
/// A loop rather than one drain because the `/AA /Bl` and `/AA /Fo` this
/// runs are themselves scripts that may call `setFocus` again. The bound is
/// [`MAX_SCRIPTED_FOCUS_MOVES`], because two fields whose focus scripts each
/// name the other would otherwise never stop.
fn honour_focus_requests<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
) -> Response {
    let mut response = Response::ignored();
    for _ in 0..MAX_SCRIPTED_FOCUS_MOVES {
        let Some(index) = cascade.take_focus_request() else {
            return response;
        };
        response.absorb(focus_field(session, ctx, cascade, index));
    }
    // The budget is spent. Whatever is still queued is dropped rather than
    // followed, and the keyboard stays where the last honoured move left it.
    cascade.take_focus_request();
    response
}

/// How many times one event may move the keyboard through `Field.setFocus`.
///
/// Two fields whose `/AA /Fo` scripts each call `setFocus` on the other are a
/// live-lock, and upstream has no counter for it — `SetFocusAnnot` recurses
/// through `OnSetFocus` until the stack runs out. A bound is the refusing
/// answer, and eight is past anything a document does on purpose.
const MAX_SCRIPTED_FOCUS_MOVES: u32 = 8;

/// The event's own routing, with no focus request spent.
fn route<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    event: Event,
) -> Response {
    match event {
        Event::MouseMove { at, modifiers } => {
            mouse_move(session, ctx, cascade, Point::narrow(at), modifiers)
        }
        Event::MouseDown {
            button: Button::Left,
            at,
            modifiers,
        } => mouse_down(session, ctx, cascade, Point::narrow(at), modifiers),
        Event::MouseUp {
            button: Button::Left,
            at,
            modifiers,
        } => mouse_up(session, ctx, cascade, Point::narrow(at), modifiers),
        // The right button reaches a widget but changes nothing and — the
        // asymmetry `focus::miss_drops_focus` records — does not drop focus
        // when it misses.
        Event::MouseDown {
            button: Button::Right,
            ..
        }
        | Event::MouseUp {
            button: Button::Right,
            ..
        } => Response::ignored(),
        Event::DoubleClick { at, modifiers } => {
            double_click(session, ctx, cascade, Point::narrow(at), modifiers)
        }
        Event::MouseWheel {
            at,
            delta,
            modifiers,
        } => wheel(session, ctx, Point::narrow(at), delta, modifiers),
        Event::Focus { at, modifiers } => {
            focus_at(session, ctx, cascade, Point::narrow(at), modifiers)
        }
        Event::KeyDown { key, modifiers } => key_down(session, ctx, cascade, key, modifiers),
        Event::Char { ch, modifiers } => char_typed(session, ctx, cascade, ch, modifiers),
    }
}

/// A pointer move. Drives hover, and extends a drag when one is live.
fn mouse_move<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    at: Point,
    modifiers: Modifiers,
) -> Response {
    let over = hit::annot_at_point(
        &ctx.page.candidates,
        session.focus.map(FocusTarget::annot),
        at.x,
        at.y,
    );
    let moved = session.hover != over;
    let left = session.hover;
    session.hover = over;

    // **The hover *edge* is what fires `/AA /X` and `/AA /E`**, in that
    // order: `CPDFSDK_PageView::OnMouseMove` sends `OnMouseExit` to the
    // annotation the pointer left and `OnMouseEnter` to the one it arrived
    // at, and a move within one widget sends neither. Two calls rather than
    // one, because a move from one widget straight onto another is both.
    if moved {
        if let Some(annot) = left {
            fire_pointer(
                session,
                ctx,
                cascade,
                annot,
                PointerTrigger::Exit,
                modifiers,
            );
        }
        if let Some(annot) = over {
            fire_pointer(
                session,
                ctx,
                cascade,
                annot,
                PointerTrigger::Enter,
                modifiers,
            );
        }
    }

    // An open dropdown carries `Styles::kListboxHoverSel`
    // (`cpwl_combo_box.cpp:210-211`), whose whole effect in
    // `CPWL_ListBox::OnMouseMove` (`cpwl_list_box.cpp:167-181`) is to select
    // the row under the pointer. It is recorded as *hover* rather than folded
    // into the selection because dismissing the list must leave the stored
    // value alone — which is exactly what `bug_736695_4` renders.
    if let Some(response) = hover_in_popup(session, ctx, at) {
        return response;
    }

    // A drag in progress extends the selection, which is the one thing a
    // bare move can change about a field's appearance.
    if let Some(anchor) = session.drag {
        return match drag_to(session, ctx, anchor, at) {
            Some(update) => Response::with(vec![update]),
            None => Response::consumed(),
        };
    }
    if moved && over.is_some() {
        return Response::consumed();
    }
    Response::ignored()
}

/// The primary button going down: focus, and place the caret.
fn mouse_down<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    at: Point,
    modifiers: Modifiers,
) -> Response {
    // An open dropdown is a **window in front of the page**, so it is tested
    // before the annotations under it. Upstream this is not a special case at
    // all — `CPWL_Wnd::OnLButtonDown` walks its children first, and the list
    // is a child — but here the widget hit test is containment over
    // `/Annots`, which the list is not in. Without this the same click read
    // as a miss and killed focus (see `popup_hit`).
    if let Some((field, annot, index)) = popup_hit(session, ctx, at) {
        return press_in_popup(session, ctx, field, annot, index);
    }
    let hit = hit::widget_at_point(
        &ctx.page.candidates,
        session.focus.map(FocusTarget::annot),
        ctx.permissions,
        at.x,
        at.y,
    );
    let Some(id) = hit else {
        // A left click on nothing drops focus, and committing the field that
        // held it is what turns its live editor state back into a generated
        // appearance.
        return if focus::miss_drops_focus(Button::Left) {
            kill_focus(session, ctx, cascade)
        } else {
            Response::ignored()
        };
    };
    let Some(widget) = ctx.widget(id) else {
        return Response::ignored();
    };
    let field = widget.field;

    // `/AA /D` runs **before** focus moves: `CFFL_InteractiveFormFiller::
    // OnLButtonDown` fires the action and only then hands the click to the
    // form field, which is where focus is taken. So a document with all six
    // scripts alerts `down` and then `focus`, in that order.
    fire_pointer(session, ctx, cascade, id, PointerTrigger::Down, modifiers);

    let mut response = take_focus(session, ctx, cascade, FocusTarget::Widget(field, id));
    ensure_state(session, ctx, field);

    // Where the click lands inside the widget is the field kind's business.
    match session.fields.get(&field) {
        Some(FieldState::Text(_)) => {
            let point = to_plate(widget, at);
            with_edit(session, ctx, field, |edit, config, metrics| {
                ops::click_at(edit, config, metrics, point);
            });
            session.drag = caret_anchor(session, field);
        }
        Some(FieldState::Choice(_)) => {
            // `CPWL_CBButton::OnLButtonDown` (`cpwl_cbbutton.cpp:65-75`)
            // notifies its parent, and `CPWL_ComboBox::NotifyLButtonDown`
            // (`cpwl_combo_box.cpp:497-503`) is `SetPopup(!is_popup_)` — a
            // **toggle**, so a second click on the button shuts the list it
            // opened. A click anywhere else in the box does not.
            if toggle_popup_at(session, ctx, field, id, at) {
                response.absorb(redraw(session, ctx, field, id));
                return response;
            }
            if let Some(update) = choice_click(session, ctx, field, id, at, modifiers) {
                response.push(update);
                return response;
            }
        }
        // A toggle acts on the *up* edge, not this one, which is what makes
        // dragging off a check box before releasing leave it alone; a push
        // button and an unclassifiable widget take a click and do nothing.
        Some(FieldState::Toggle(_) | FieldState::Button(_)) | None => {}
    }

    response.absorb(redraw(session, ctx, field, id));
    response
}

/// The primary button coming up: activate a toggle, end a drag.
fn mouse_up<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    at: Point,
    modifiers: Modifiers,
) -> Response {
    // The release **finishes** the drag before ending it. Dropping the anchor
    // first loses the last leg of the selection, which is the whole of it
    // when the pointer never moved between the intermediate positions and the
    // release — and a drag whose only move is the release point is exactly
    // what the upstream `SelectTextWithMouse` sends.
    let finished = session
        .drag
        .and_then(|anchor| drag_to(session, ctx, anchor, at));
    session.drag = None;

    // **The two `/AA` entries fire whether or not a drag ended here**, and
    // before the drag's own answer is returned: upstream's `OnLButtonUp` runs
    // `SetFocusAnnot` and `OnButtonUp` on every release that lands on a
    // widget, and the selection the drag left is not something either of them
    // consults. Firing them only on the no-drag path would make a click that
    // moved one pixel run no script.
    if let Some(id) = hit::widget_at_point(
        &ctx.page.candidates,
        session.focus.map(FocusTarget::annot),
        ctx.permissions,
        at.x,
        at.y,
    ) {
        // `SetFocusAnnot` first, `OnButtonUp` second
        // (`cffl_interactiveformfiller.cpp:213-250`) — so a document with
        // both scripts alerts `focus` and then `up`.
        fire_pointer(session, ctx, cascade, id, PointerTrigger::Focus, modifiers);
        fire_pointer(session, ctx, cascade, id, PointerTrigger::Up, modifiers);
    }

    if let Some(update) = finished {
        return Response::with(vec![update]);
    }
    // The release inside an open dropdown is what *commits* the row — see
    // `release_in_popup` for why the press only hovers it.
    if let Some((field, annot, index)) = popup_hit(session, ctx, at) {
        return release_in_popup(session, ctx, field, annot, index);
    }
    let hit = hit::widget_at_point(
        &ctx.page.candidates,
        session.focus.map(FocusTarget::annot),
        ctx.permissions,
        at.x,
        at.y,
    );
    let Some(id) = hit else {
        return Response::ignored();
    };
    let Some(widget) = ctx.widget(id) else {
        return Response::ignored();
    };
    let field = widget.field;
    let read_only = widget.flags.is_read_only();
    let kind = toggle_kind(widget);

    if let (Some(kind), Some(FieldState::Toggle(state))) = (kind, session.fields.get_mut(&field)) {
        let moved = field::activate(state, kind, read_only);
        if moved {
            // A radio button clears its siblings, which are the other
            // controls of the same field on this page.
            clear_siblings(session, ctx, field, id);
            session.dirty.insert(field);
            let mut response = Response::consumed();
            for other in ctx.page.widgets.iter().filter(|w| w.field == field) {
                response.absorb(redraw(session, ctx, field, other.id));
            }
            return response;
        }
        // Read-only: consumed, and nothing moved.
        return Response::consumed();
    }
    Response::consumed()
}

/// A double click selects the whole line under the pointer.
fn double_click<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    at: Point,
    modifiers: Modifiers,
) -> Response {
    // A double click is an `OnLButtonDblClk`, which the form filler routes
    // through `SetFocusAnnot` exactly as a release does — so `/AA /Fo` runs
    // again even on the field that already holds focus, which is what
    // `mouse_events`'s second `focus` alert records.
    if let Some(annot) = session.focus.map(FocusTarget::annot) {
        fire_pointer(
            session,
            ctx,
            cascade,
            annot,
            PointerTrigger::Focus,
            modifiers,
        );
    }
    let Some(field) = session.focused_field() else {
        return Response::ignored();
    };
    if !matches!(session.fields.get(&field), Some(FieldState::Text(_))) {
        return Response::ignored();
    }
    // A double click selects the **whole field**, not the line under the
    // pointer. `CPWL_Edit::OnLButtonDblClk` (`cpwl_edit.cpp:636-644`) calls
    // `edit_impl_->SelectAll()`; the embeddertest's comment says "the entire
    // line" and its field is single-line, so the two agree there and only
    // there. A multiline field is where the wrong reading shows.
    //
    // The point is still needed: upstream selects only when the click is
    // inside the client area (or the field overflows), so a double click on
    // the border selects nothing.
    let Some(widget) = ctx.widget_of_field(field) else {
        return Response::consumed();
    };
    let point = to_plate(widget, at);
    let client =
        pdfrum_doc::geom::normalize(ap::field_body::client_rect(&widget.dict, ctx.resolve));
    // `CFX_FloatRect::Contains` (`fx_coordinates.cpp:229-234`) is inclusive on
    // all four edges, where `kurbo::Rect::contains` is half-open — a click
    // exactly on the client's top or right edge selects upstream and would
    // not here.
    let inside = point.x >= client.x0
        && point.x <= client.x1
        && point.y >= client.y0
        && point.y <= client.y1;
    if !inside {
        return Response::consumed();
    }
    with_edit(session, ctx, field, |edit, _config, _metrics| {
        edit.select_all();
    });
    let Some(id) = session.focus.map(FocusTarget::annot) else {
        return Response::consumed();
    };
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, id));
    response
}

/// The wheel scrolls whatever is under the pointer, focused or not.
///
/// A **list box** moves its selection rather than its view, with the wheel's
/// own Shift and Control passed through: the wheel and the arrow keys are one
/// operation, and those flags change what a multi-select list does with the
/// row it lands on.
///
/// A **combo box** does nothing. Treating it as a list would let a wheel notch
/// silently change a committed value.
fn wheel<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    at: Point,
    delta: (i32, i32),
    modifiers: Modifiers,
) -> Response {
    let hit = hit::widget_at_point(
        &ctx.page.candidates,
        session.focus.map(FocusTarget::annot),
        ctx.permissions,
        at.x,
        at.y,
    );
    let Some(id) = hit else {
        return Response::ignored();
    };
    let Some(widget) = ctx.widget(id) else {
        return Response::ignored();
    };
    let field = widget.field;
    ensure_state(session, ctx, field);
    // Read against the state that already exists: a row's height is measured
    // from an option's label, so the count cannot be taken before the field
    // has options.
    let rows = match session.fields.get(&field) {
        Some(FieldState::Choice(choice)) => visible_rows(ctx, widget, choice),
        _ => 0,
    };

    let moved = match session.fields.get_mut(&field) {
        // A combo box is not a list under the wheel; see this function's docs.
        Some(FieldState::Choice(state)) if state.config.combo => false,
        Some(FieldState::Choice(state)) => scroll_choice(state, delta.1, rows, modifiers),
        Some(FieldState::Text(_)) => scroll_text(session, ctx, field, delta.1),
        Some(FieldState::Toggle(_) | FieldState::Button(_)) | None => false,
    };
    if !moved {
        return Response::consumed();
    }
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, id));
    response
}

/// Focus requested at a point, without a click.
fn focus_at<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    at: Point,
    modifiers: Modifiers,
) -> Response {
    let hit = hit::widget_at_point(
        &ctx.page.candidates,
        session.focus.map(FocusTarget::annot),
        ctx.permissions,
        at.x,
        at.y,
    );
    let Some(id) = hit else {
        return Response::ignored();
    };
    let Some(widget) = ctx.widget(id) else {
        return Response::ignored();
    };
    let field = widget.field;
    // The explicit focus verb is `SetFocusAnnot` directly, so `/AA /Fo` runs
    // here for the same reason it runs on a release.
    fire_pointer(session, ctx, cascade, id, PointerTrigger::Focus, modifiers);
    let mut response = take_focus(session, ctx, cascade, FocusTarget::Widget(field, id));
    ensure_state(session, ctx, field);
    response.absorb(redraw(session, ctx, field, id));
    response
}

/// A key going down, to whatever holds focus.
fn key_down<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    key: Key,
    modifiers: Modifiers,
) -> Response {
    // Tab moves focus, and it does so whether or not anything holds it.
    if key == Key::Tab {
        return tab_to_next(session, ctx, cascade, modifiers);
    }
    let Some(target) = session.focus else {
        return Response::ignored();
    };
    let Some(field) = target.field() else {
        // A focused annotation that is not a widget — a link, once a caller
        // has put links in the focus ring — fires its action on Return.
        return annot_key(session, ctx, target.annot(), key, modifiers);
    };
    let annot = target.annot();

    match session.fields.get(&field) {
        Some(FieldState::Text(_)) => text_key(session, ctx, cascade, field, annot, key, modifiers),
        Some(FieldState::Choice(_)) => choice_key(session, ctx, field, annot, key, modifiers),
        Some(FieldState::Toggle(_)) => {
            // Return and Space activate; a read-only control consumes them
            // and does nothing, which is a different answer from ignoring.
            if matches!(key, Key::Return | Key::Space) {
                Response::consumed()
            } else {
                Response::ignored()
            }
        }
        // `[oracle-bug]` a focused push button fires its `/A` on Return, the
        // same activation a focused link gets. `CFFL_PushButton` has no
        // `OnChar` override (where `CFFL_TextField` does, at
        // `cffl_textfield.cpp:116-140`), so
        // `fpdf_formfill_embeddertest.cpp:3658-3667` asserts `DoURIAction`
        // `.Times(0)` and `ASSERT_FALSE(FORM_OnChar(…, kReturn, 0))` — both
        // marked `TODO(crbug.com/1028991)` saying they should be one and
        // true — while the adjacent `LinkActionInvokeTest` (`:3670-3690`)
        // asserts `.Times(4)` and `ASSERT_TRUE` for a link. §12.6.3 table 196
        // performs an annotation's `/A` when it is *activated*, and a keyboard
        // activation of a tab-focused button is one. pdf.js gets it free by
        // rendering push buttons as `<a>` (`annotation_layer.js:2129-2137`).
        Some(FieldState::Button(_)) => annot_key(session, ctx, annot, key, modifiers),
        None => Response::ignored(),
    }
}

/// A typed character, to whatever holds focus.
fn char_typed<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    ch: char,
    modifiers: Modifiers,
) -> Response {
    let Some(target) = session.focus else {
        return Response::ignored();
    };
    let Some(field) = target.field() else {
        return Response::ignored();
    };
    let annot = target.annot();
    let accelerator = session.config.accelerator;

    match session.fields.get(&field) {
        Some(FieldState::Text(state)) => {
            let (read_only, multi_line) = (state.config.read_only, state.config.multi_line);
            let action = field::text::route_char(ch, modifiers, accelerator, read_only, multi_line);
            perform_text(session, ctx, cascade, field, annot, action)
        }
        Some(FieldState::Choice(_)) => choice_char(session, ctx, cascade, field, annot, ch),
        Some(FieldState::Toggle(_)) => {
            // A check box takes Return and Space as activation, and consumes
            // them read-only or not.
            if matches!(ch, '\r' | ' ') {
                let widget = ctx.widget(annot);
                let read_only = widget.is_some_and(|w| w.flags.is_read_only());
                let kind = widget.and_then(toggle_kind);
                if let (Some(kind), Some(FieldState::Toggle(state))) =
                    (kind, session.fields.get_mut(&field))
                    && field::activate(state, kind, read_only)
                {
                    clear_siblings(session, ctx, field, annot);
                    session.dirty.insert(field);
                    let mut response = Response::consumed();
                    response.absorb(redraw(session, ctx, field, annot));
                    return response;
                }
                return Response::consumed();
            }
            Response::ignored()
        }
        // `[oracle-bug]` The char path too: the upstream assertion is on
        // `FORM_OnChar(…, kReturn, 0)` (`fpdf_formfill_embeddertest.cpp:3667`),
        // so a typed Return activates a focused push button exactly as the
        // key path does. See `key_down`.
        Some(FieldState::Button(_)) if ch == '\r' => {
            annot_key(session, ctx, annot, Key::Return, modifiers)
        }
        Some(FieldState::Button(_)) | None => Response::ignored(),
    }
}

/// A key for a focused annotation that is not a form widget.
///
/// **Return fires its action, and nothing else does.** Shift, Space and the
/// accelerator are each explicitly *not* an activation — the ported
/// assertions check those rejections as specifically as they check the
/// acceptance, because "any key activates a link" is the plausible wrong
/// implementation.
///
/// The action comes back as a **request** the caller may inspect, ignore or
/// perform, with the modifiers that were held riding along: a link's action
/// is expected to see them, which is how a control-click opens in a new
/// window. Nothing is followed here — this crate navigates nothing.
fn annot_key<R: Resolve>(
    session: &FormSession,
    ctx: &Context<'_, R>,
    annot: AnnotId,
    key: Key,
    modifiers: Modifiers,
) -> Response {
    let _ = session;
    if key != Key::Return {
        return Response::ignored();
    }
    let Some(action) = action_of(ctx, annot) else {
        return Response::ignored();
    };
    Response::with(vec![AppearanceUpdate::new(
        annot,
        UpdateKind::ActionRequested {
            action: Box::new(action),
            modifiers,
        },
    )])
}

/// The action an annotation carries, from its `/A`.
fn action_of<R: Resolve>(ctx: &Context<'_, R>, annot: AnnotId) -> Option<pdfrum_doc::nav::Action> {
    let dict = ctx.page.dicts.get(&annot.index)?;
    let action = dict.dict(ACTION, ctx.resolve)?;
    Some(pdfrum_doc::nav::Action::new(action))
}

/// A key for a focused text field.
fn text_key<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    field: FieldId,
    annot: AnnotId,
    key: Key,
    modifiers: Modifiers,
) -> Response {
    let has_selection = match session.fields.get(&field) {
        Some(FieldState::Text(state)) => state.edit.has_selection(),
        _ => false,
    };
    let action = field::text::route_key(
        key,
        modifiers,
        session.config.accelerator,
        session.config.redo_on_ctrl_y,
        has_selection,
    );
    perform_text(session, ctx, cascade, field, annot, action)
}

/// Performs a routed text action.
fn perform_text<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    field: FieldId,
    annot: AnnotId,
    action: Disposition,
) -> Response {
    let action = match action {
        Disposition::Do(action) => action,
        Disposition::Consume => return Response::consumed(),
        Disposition::Ignore => return Response::ignored(),
    };

    // Commit and escape leave the field rather than editing it.
    match action {
        TextAction::Commit | TextAction::Escape => {
            let mut response = Response::consumed();
            response.absorb(kill_focus(session, ctx, cascade));
            return response;
        }
        _ => {}
    }

    // The per-character keystroke hook, before the edit is applied.
    //
    // `CFFL_InteractiveFormFiller::OnChar` gathers the field action and runs
    // `/AA /K` with `willCommit` false (`cffl_interactiveformfiller.cpp:1020`)
    // ahead of the insertion, then applies `SetSelection` and
    // `ReplaceSelection` from what the script left behind
    // (`cffl_textfield.cpp:216-222`). A refusal is "do nothing": the character
    // is dropped and the field is unchanged, which is `:1052`'s
    // `RecreatePWLWindowFromSavedState` restated.
    let action = match keystroke_hook(session, ctx, cascade, field, action) {
        Keyed::Perform(action) => action,
        Keyed::Refused => return Response::consumed(),
        Keyed::Rewrote => {
            session.dirty.insert(field);
            let mut response = Response::consumed();
            response.absorb(redraw(session, ctx, field, annot));
            return response;
        }
    };

    let max_len = match session.fields.get(&field) {
        Some(FieldState::Text(state)) => state.config.max_len.map(std::num::NonZeroU32::get),
        _ => None,
    };
    let mut changed = false;
    with_edit(session, ctx, field, |edit, config, metrics| {
        changed = perform_on_edit(edit, config, metrics, action, max_len);
    });
    if changed {
        session.dirty.insert(field);
    }

    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    response
}

/// What the per-character keystroke hook left for routing to do.
enum Keyed {
    /// Go ahead with this action, unchanged.
    Perform(TextAction),
    /// The hook rewrote the text; it is already applied, so edit nothing more.
    Rewrote,
    /// The hook refused. The character is dropped and the field is unchanged.
    Refused,
}

/// Offers a text action to the per-character keystroke hook.
///
/// # Which actions reach a script, and which do not
///
/// Only the ones that **change the text**: an insertion, a return, and the
/// two deletions. Caret movement, selection, undo, redo and scrolling build no
/// action at all — a script that saw arrow keys would be seeing keystrokes the
/// specification says a keystroke event is not about.
///
/// A hook that rewrites `change` is answered by *replacing the selection* with
/// what it returned, rather than by re-running the original action.
fn keystroke_hook<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    field: FieldId,
    action: TextAction,
) -> Keyed {
    let change = match action {
        TextAction::Insert(ch) => ch.to_string(),
        TextAction::InsertReturn => "\n".to_string(),
        // A deletion is a keystroke whose change is empty; the selection it
        // replaces is what the edit control already holds.
        TextAction::Backspace | TextAction::Delete => String::new(),
        _ => return Keyed::Perform(action),
    };
    let Some(reference) = field_ref(ctx, field) else {
        return Keyed::Perform(action);
    };
    let Some(FieldState::Text(state)) = session.fields.get(&field) else {
        return Keyed::Perform(action);
    };
    let offered = Keystroke::of(&state.edit, change);

    match cascade.keystroke(&reference, offered.clone()) {
        KeystrokeOutcome::Reject => Keyed::Refused,
        KeystrokeOutcome::Accept(back) if back == offered => Keyed::Perform(action),
        KeystrokeOutcome::Accept(back) => {
            // The script moved the caret, rewrote the text, or both. Apply
            // what it left rather than what was offered.
            set_field_text(session, field, &back.applied());
            Keyed::Rewrote
        }
    }
}

/// One text action against a live edit control.
fn perform_on_edit(
    edit: &mut TextEdit,
    config: &vt::Config,
    metrics: &vt::Metrics<'_>,
    action: TextAction,
    max_len: Option<u32>,
) -> bool {
    match action {
        TextAction::Insert(ch) => ops::insert_char(edit, config, metrics, ch, max_len),
        TextAction::InsertReturn => ops::insert_char(edit, config, metrics, '\n', max_len),
        TextAction::Backspace => ops::backspace(edit, config, metrics),
        TextAction::Delete => ops::delete(edit, config, metrics),
        TextAction::ClearSelection => {
            edit.select_none();
            true
        }
        TextAction::SelectAll => {
            edit.select_all();
            true
        }
        TextAction::Undo => ops::undo(edit, config, metrics),
        TextAction::Redo => ops::redo(edit, config, metrics),
        TextAction::Move { motion, extend } => move_caret(edit, config, metrics, motion, extend),
        // Handled by the caller, which leaves the field rather than editing.
        TextAction::Commit | TextAction::Escape => false,
    }
}

/// Moves the caret, extending the selection when asked.
fn move_caret(
    edit: &mut TextEdit,
    config: &vt::Config,
    metrics: &vt::Metrics<'_>,
    motion: Motion,
    extend: bool,
) -> bool {
    let len = edit.len_chars();
    let at = edit.caret_index();
    let to = match motion {
        Motion::Left => at.saturating_sub(1),
        Motion::Right => (at + 1).min(len),
        Motion::DocStart | Motion::LineStart => 0,
        Motion::DocEnd | Motion::LineEnd => len,
        // A single-line field has nowhere to go vertically, and a multiline
        // one moves by the layout's own line breaks.
        Motion::Up => line_step(edit, config, metrics, at, -1),
        Motion::Down => line_step(edit, config, metrics, at, 1),
    };
    if extend {
        edit.move_caret_keeping_selection(to);
    } else {
        edit.set_caret_index(to);
    }
    // Upstream runs `ScrollToCaret` after every one of these, which is what
    // lets an arrow key walk off the visible end of a long value and bring
    // the view with it.
    ops::scroll_to_caret(edit, config, metrics);
    true
}

/// The index one line up or down from `at`, staying in the sticky column.
fn line_step(
    edit: &TextEdit,
    config: &vt::Config,
    metrics: &vt::Metrics<'_>,
    at: usize,
    direction: i32,
) -> usize {
    let place = vt::hit::place_of_word_index(&edit.layout, at);
    let line = i64::from(place.line) + i64::from(direction);
    if line < 0 {
        return 0;
    }
    let target = vt::hit::place_at_point(
        &edit.layout,
        config.plate,
        config,
        metrics,
        edit.offset,
        kurbo::Point::new(
            f64::from(edit.sticky_x),
            f64::from(line_y(edit, place.section, line)),
        ),
    );
    let _ = metrics;
    vt::hit::word_index_of_place(&edit.layout, target)
}

/// The page-space y of a line, for a vertical move.
fn line_y(edit: &TextEdit, section: u32, line: i64) -> f32 {
    edit.layout
        .sections
        .get(usize::try_from(section).unwrap_or(0))
        .and_then(|section| section.lines.get(usize::try_from(line).unwrap_or(0)))
        .map_or(0.0, |line| line.y)
}

/// A key for a focused choice field.
///
/// The arrow keys carry their modifiers for the same reason the wheel does:
/// the two gestures are one operation and must not diverge here.
fn choice_key<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    annot: AnnotId,
    key: Key,
    modifiers: Modifiers,
) -> Response {
    let rows = match (ctx.widget(annot), session.fields.get(&field)) {
        (Some(widget), Some(FieldState::Choice(choice))) => visible_rows(ctx, widget, choice),
        _ => 0,
    };
    let moved = match session.fields.get_mut(&field) {
        Some(FieldState::Choice(state)) => {
            let (shift, ctrl) = (
                modifiers.contains(Modifiers::SHIFT),
                modifiers.contains(Modifiers::CONTROL),
            );
            let moved = match key {
                Key::Up => field::choice::move_caret_by(state, -1, shift, ctrl),
                Key::Down => field::choice::move_caret_by(state, 1, shift, ctrl),
                Key::Return | Key::Space => return Response::consumed(),
                _ => return Response::ignored(),
            };
            // The view follows the caret only when it would otherwise leave
            // the box — the same rule the wheel obeys, because upstream they
            // are the same operation.
            let caret = state.caret_index.unwrap_or(0);
            moved | field::choice::scroll_into_view(state, caret, rows)
        }
        _ => return Response::ignored(),
    };
    if !moved {
        return Response::consumed();
    }
    session.dirty.insert(field);
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    response
}

/// A character for a focused choice field: type-ahead, or text in an
/// editable combo.
fn choice_char<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    field: FieldId,
    annot: AnnotId,
    ch: char,
) -> Response {
    let (combo, editable) = match session.fields.get(&field) {
        Some(FieldState::Choice(state)) => (state.config.combo, state.config.editable),
        _ => (false, false),
    };
    // `CPWL_ComboBox::OnChar` (`cpwl_combo_box.cpp:441-497`) reads two
    // characters before anything else, and they are **not** symmetric:
    //
    // - `Return` **toggles** the list, editable or not, and then re-reads the
    //   current row into the edit half — so a second Return shuts what the
    //   first opened;
    // - `Space` opens it, only on a **gated** combo, and only when it is
    //   shut. An editable combo's Space falls through and types a space.
    //
    // Both return `true` whatever happened, which is why the responses below
    // are consumed even where the list refused to move.
    if combo && matches!(ch, '\r' | '\n') {
        return toggle_popup_by_key(session, ctx, field, annot);
    }
    if combo && !editable && ch == ' ' {
        let shut = matches!(
            session.fields.get(&field),
            Some(FieldState::Choice(state)) if !state.popup_open
        );
        if shut {
            return toggle_popup_by_key(session, ctx, field, annot);
        }
        return Response::consumed();
    }
    if editable {
        // The keystroke hook sees an editable combo's typing exactly as it
        // sees a text field's: `CFFL_ComboBox` builds the same
        // `CFFL_FieldAction` from its edit half
        // (`fpdfsdk/formfiller/cffl_combobox.cpp:180-196`).
        if let Some(reference) = field_ref(ctx, field)
            && let Some(FieldState::Choice(state)) = session.fields.get(&field)
            && let Some(edit) = state.edit.as_ref()
        {
            let offered = Keystroke::of(edit, ch.to_string());
            match cascade.keystroke(&reference, offered.clone()) {
                KeystrokeOutcome::Reject => return Response::consumed(),
                KeystrokeOutcome::Accept(back) if back != offered => {
                    set_field_text(session, field, &back.applied());
                    if let Some(FieldState::Choice(state)) = session.fields.get_mut(&field) {
                        state.selected.clear();
                        state.caret_index = None;
                        state.edit = None;
                    }
                    session.dirty.insert(field);
                    let mut response = Response::consumed();
                    response.absorb(redraw(session, ctx, field, annot));
                    return response;
                }
                KeystrokeOutcome::Accept(_) => {}
            }
        }
        // An editable combo's typed text goes to its own edit control, and
        // typing clears the index selection.
        let mut changed = false;
        with_combo_edit(session, ctx, field, |edit, config, metrics| {
            changed = ops::insert_char(edit, config, metrics, ch, None);
        });
        if changed {
            if let Some(FieldState::Choice(state)) = session.fields.get_mut(&field) {
                state.selected.clear();
                state.caret_index = None;
            }
            session.dirty.insert(field);
        }
        let mut response = Response::consumed();
        response.absorb(redraw(session, ctx, field, annot));
        return response;
    }

    let moved = match session.fields.get_mut(&field) {
        Some(FieldState::Choice(state)) => field::choice::type_ahead(state, ch),
        _ => false,
    };
    if !moved {
        return Response::consumed();
    }
    session.dirty.insert(field);
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    response
}

/// A click inside a choice field's rows.
fn choice_click<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    id: AnnotId,
    at: Point,
    modifiers: Modifiers,
) -> Option<AppearanceUpdate> {
    let widget = ctx.widget(id)?;
    let row = row_at(ctx, widget, session.fields.get(&field), at)?;
    // A combo box's own box has no rows — `row_at` says so — so the drop
    // button, handled by the caller, is the only thing a click in one does.
    let multi = match session.fields.get(&field) {
        Some(FieldState::Choice(state)) => state.config.multi_select,
        _ => false,
    };
    let Some(FieldState::Choice(state)) = session.fields.get_mut(&field) else {
        return None;
    };
    let moved = if multi && modifiers.contains(Modifiers::SHIFT) {
        field::choice::select_range_to(state, row)
    } else if multi && modifiers.contains(Modifiers::CONTROL) {
        field::choice::toggle_index(state, row)
    } else {
        field::choice::select_only(state, row)
    };
    if moved {
        session.dirty.insert(field);
    }
    appearance_of(session, ctx, field, id)
}

/// Which row of a list box a page-space point falls on.
fn row_at<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    state: Option<&FieldState>,
    at: Point,
) -> Option<usize> {
    let FieldState::Choice(choice) = state? else {
        return None;
    };
    // A combo box's list is not drawn, so a click in the box selects nothing
    // by row; only a list box has rows under the pointer.
    if choice.config.combo {
        return None;
    }
    let client = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    let height = row_height(ctx, widget, choice);
    if height <= 0.0 {
        return None;
    }
    // The point arrives in **page** space and the client rectangle is in the
    // appearance stream's, which is the widget's own box at the origin. They
    // are the same space only for a widget whose `/Rect` happens to start at
    // (0, 0); anywhere else the subtraction below is a difference of two
    // unrelated numbers, and it was — a list box at y 371 produced a large
    // negative quotient, a saturating `usize`, and no row at all, so the
    // click focused the widget and then selected nothing.
    //
    // `CFFL_FormField::OnLButtonDown` (`cffl_formfield.cpp:103`) passes
    // `FFLtoPWL(point)` into the list for exactly this reason.
    let point = to_plate(widget, at);
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "the quotient is bounded by the option count immediately below"
    )]
    let offset = ((client.y1 - point.y) / f64::from(height)) as usize;
    let row = choice.top_visible.checked_add(offset)?;
    (row < choice.options.len()).then_some(row)
}

/// How many rows of a list box fit in its client area.
///
/// The count the no-overscroll clamp is stated against: a list scrolls only
/// far enough to put its last row at the bottom of the box.
fn visible_rows<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    choice: &ChoiceState,
) -> usize {
    let client = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    let height = row_height(ctx, widget, choice);
    if height <= 0.0 {
        return 0;
    }
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "a row count is bounded by the widget's height in points"
    )]
    let rows = (pdfrum_doc::geom::height(client) / height) as usize;
    rows
}

/// The width of a combo box's drop button, in PDF units.
///
/// The same constant `ap::shapes::drop_button` draws with. It takes the
/// rightmost slice of the client rectangle, clamped to the client's left edge
/// for a widget narrower than the button — which is why the `max` below is not
/// decoration.
const DROP_BUTTON_WIDTH: f32 = 13.0;

/// Whether a page-space point is inside a combo box's drop button.
///
/// The button is a child window in *plate* space, so the point is mapped
/// through the widget's own rotation before it is compared: a `/MK /R 90`
/// combo has its button on the top edge as drawn, not the right one.
fn on_drop_button<R: Resolve>(ctx: &Context<'_, R>, widget: &WidgetInfo, at: Point) -> bool {
    let client = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    let (left, right) = (
        pdfrum_doc::geom::left(client),
        pdfrum_doc::geom::right(client),
    );
    let edge = (right - DROP_BUTTON_WIDTH).max(left);
    let point = to_plate(widget, at);
    #[expect(
        clippy::cast_possible_truncation,
        reason = "a plate coordinate is a widget-sized number"
    )]
    let (x, y) = (point.x as f32, point.y as f32);
    x >= edge
        && x <= right
        && y >= pdfrum_doc::geom::bottom(client)
        && y <= pdfrum_doc::geom::top(client)
}

/// Where a combo box's dropdown would be, whether or not it is open.
///
/// [`None`] for anything that is not a combo, and for a combo whose list has
/// no room to open — `SetPopup`'s two "refuse, but report success" exits.
fn popup_geometry<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    choice: &ChoiceState,
) -> Option<crate::popup::PopupGeometry> {
    if !choice.config.combo {
        return None;
    }
    crate::popup::place(
        widget.rect,
        ctx.page.page_height,
        choice.options.len(),
        row_height(ctx, widget, choice),
    )
}

/// Opens or closes a combo box's dropdown, reporting whether the state moved.
///
/// There are **three failure paths**, all of which report success and change
/// nothing:
///
/// - no list at all (a field that is not a combo);
/// - a list whose content rectangle has no height (no options);
/// - a `QueryWherePopup` that comes back with nothing (no room on the page).
///
/// So a click on the drop button of a combo with nowhere to open is still
/// *consumed*; it simply leaves the list shut. That is why this returns
/// "did anything move" rather than "did it succeed": the caller wants to know
/// whether to redraw, and the two questions have different answers here.
fn set_popup<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    choice: &mut ChoiceState,
    open: bool,
) -> bool {
    if !choice.config.combo || open == choice.popup_open {
        return false;
    }
    if !open {
        choice.popup_open = false;
        choice.hovered = None;
        return true;
    }
    if popup_geometry(ctx, widget, choice).is_none() {
        return false;
    }
    choice.popup_open = true;
    // `RepositionChildWnd` (`cpwl_combo_box.cpp:275`) runs
    // `ScrollToListItem(select_item_)` as it opens, so an already-selected
    // row is scrolled into view rather than the list opening at the top.
    // Recomputed *after* the flag is set because the geometry is the same
    // either way — the popup's size does not depend on whether it is showing.
    if let Some(selected) = choice.selected.iter().next().copied() {
        let rows =
            popup_geometry(ctx, widget, choice).map_or(0, |geometry| geometry.visible_rows());
        field::choice::scroll_into_view(choice, selected, rows);
    }
    true
}

/// Shuts every open dropdown on the page.
///
/// A list is closed before focus is dropped, so nothing survives a focus
/// change — and because a session focuses one field at a time, closing *every*
/// one is the same operation stated without a special case for which field it
/// was.
fn close_all_popups(session: &mut FormSession) -> bool {
    let mut closed = false;
    for state in session.fields.values_mut() {
        if let FieldState::Choice(choice) = state
            && choice.popup_open
        {
            choice.popup_open = false;
            choice.hovered = None;
            closed = true;
        }
    }
    closed
}

/// The field whose dropdown is open on this page, if one is.
///
/// At most one, because opening one takes focus and taking focus closes the
/// last. The walk is over the page's widgets rather than over the session's
/// fields so that a field with a control on two pages answers for the page
/// being asked about.
fn open_popup_of(session: &FormSession, page: &PageForm) -> Option<(FieldId, AnnotId)> {
    page.widgets
        .iter()
        .find_map(|widget| match session.fields.get(&widget.field) {
            Some(FieldState::Choice(choice)) if choice.popup_open => {
                Some((widget.field, widget.id))
            }
            _ => None,
        })
}

/// The open dropdown a page-space point falls inside, with the row it names.
///
/// **An open dropdown must be hit-tested before the annotations are.** A
/// mouse-down below an open combo is inside the list, and the list is not in
/// `/Annots` — so plain rect containment over the array reads that click as a
/// miss and drops focus instead of selecting a row.
fn popup_hit<R: Resolve>(
    session: &FormSession,
    ctx: &Context<'_, R>,
    at: Point,
) -> Option<(FieldId, AnnotId, usize)> {
    let (field, annot) = open_popup_of(session, ctx.page)?;
    let widget = ctx.widget(annot)?;
    let FieldState::Choice(choice) = session.fields.get(&field)? else {
        return None;
    };
    let geometry = popup_geometry(ctx, widget, choice)?;
    let offset = geometry.row_at(at.x, at.y)?;
    let index = crate::popup::option_at(choice, offset)?;
    Some((field, annot, index))
}

/// A pointer move over an open dropdown, which hover-selects a row.
///
/// [`None`] when the pointer is not over an open list, which is what lets
/// `mouse_move` fall through to hover and drag as before. A move that stays
/// on the same row answers `Some(consumed)` with no update: the pointer is
/// still inside a window, so the event is not the page's, but nothing was
/// repainted.
fn hover_in_popup<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    at: Point,
) -> Option<Response> {
    let (field, annot, index) = popup_hit(session, ctx, at)?;
    let moved = match session.fields.get_mut(&field) {
        Some(FieldState::Choice(choice)) => {
            let moved = choice.hovered != Some(index);
            choice.hovered = Some(index);
            moved
        }
        _ => false,
    };
    if !moved {
        return Some(Response::consumed());
    }
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    Some(response)
}

/// A left-down on the drop button, reporting whether the list moved.
///
/// Returns `false` for a click that is not on the button, which is what lets
/// the caller fall through to the ordinary click handling; a click that *is*
/// on it but cannot open the list — no options, no room — also answers
/// `false`, because nothing moved and there is nothing to redraw. Either way
/// the click stays consumed: the widget took focus before this ran.
fn toggle_popup_at<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    id: AnnotId,
    at: Point,
) -> bool {
    let Some(widget) = ctx.widget(id) else {
        return false;
    };
    let combo = matches!(
        session.fields.get(&field),
        Some(FieldState::Choice(choice)) if choice.config.combo
    );
    if !combo || !on_drop_button(ctx, widget, at) {
        return false;
    }
    let Some(FieldState::Choice(choice)) = session.fields.get_mut(&field) else {
        return false;
    };
    let open = !choice.popup_open;
    // Split so the immutable `ctx.widget` borrow and the mutable state borrow
    // do not overlap: `set_popup` needs both, and the widget is `ctx`'s.
    let mut taken = std::mem::take(choice);
    let moved = set_popup(ctx, widget, &mut taken, open);
    if let Some(FieldState::Choice(choice)) = session.fields.get_mut(&field) {
        *choice = taken;
    }
    moved
}

/// `Return` (or a gated combo's `Space`) toggling the dropdown.
///
/// The keyboard spelling of `toggle_popup_at`, without a point to test. The
/// response is always consumed, even when the list refused to open, so a
/// combo with nowhere to open still swallows the key rather than letting it
/// type a character.
fn toggle_popup_by_key<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    annot: AnnotId,
) -> Response {
    let Some(widget) = ctx.widget(annot) else {
        return Response::consumed();
    };
    let Some(FieldState::Choice(choice)) = session.fields.get_mut(&field) else {
        return Response::consumed();
    };
    let open = !choice.popup_open;
    let mut taken = std::mem::take(choice);
    let moved = set_popup(ctx, widget, &mut taken, open);
    if let Some(FieldState::Choice(choice)) = session.fields.get_mut(&field) {
        *choice = taken;
    }
    if !moved {
        return Response::consumed();
    }
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    response
}

/// A left-down inside an open dropdown's rows.
///
/// **Down hovers, up selects.** The press moves the list's own selection; the
/// *commit* — copying the row's text into the edit half and shutting the list
/// — happens on release. Splitting them matters because a press that drags off
/// the list before releasing must leave the field alone.
fn press_in_popup<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    annot: AnnotId,
    index: usize,
) -> Response {
    if let Some(FieldState::Choice(choice)) = session.fields.get_mut(&field) {
        choice.hovered = Some(index);
    }
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    response
}

/// A left-up inside an open dropdown's rows: the row is chosen.
///
/// Four steps in order: carry the row's label into the text half, select all
/// of it, focus the edit, shut the list. The first routes through a selection
/// replacement, so **every combo selection is undoable**. The last is why the
/// list shuts on release rather than on press.
fn release_in_popup<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    annot: AnnotId,
    index: usize,
) -> Response {
    let label = match session.fields.get_mut(&field) {
        Some(FieldState::Choice(choice)) => {
            field::choice::select_only(choice, index);
            choice.popup_open = false;
            choice.hovered = None;
            choice
                .options
                .get(index)
                .map(|option| option.label.clone())
                .unwrap_or_default()
        }
        _ => return Response::consumed(),
    };
    // An editable combo shows the chosen row in its text half, which is what
    // `SetSelectText`'s `edit_->ReplaceSelection(list_->GetText())` puts
    // there. A gated one has no text half and reads its label from the
    // selection instead.
    set_combo_text(session, ctx, field, label);
    session.dirty.insert(field);
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    response
}

/// `SetSelectText()` then `SelectAllText()`: the chosen row's label into the
/// combo's text half, **left selected**.
///
/// Both halves matter and the second is the one that shows: after choosing a
/// row the text half holds that row's label with **every character selected**,
/// so it draws as white glyphs on a navy band rather than as black text on
/// white.
///
/// The control is rebuilt from the label rather than edited in place: the
/// whole text is being replaced, so there is nothing of the old one to keep,
/// and `with_combo_edit` is the one place that knows the plate and the face
/// to build it with.
fn set_combo_text<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    label: String,
) {
    let editable = matches!(
        session.fields.get(&field),
        Some(FieldState::Choice(choice)) if choice.config.editable
    );
    if !editable {
        return;
    }
    if let Some(FieldState::Choice(choice)) = session.fields.get_mut(&field) {
        choice.edit_text = label;
        // Dropped rather than rewritten, so `with_combo_edit` below lays the
        // new label out from scratch: one place the text can come from
        // instead of two that must agree.
        choice.edit = None;
    }
    with_combo_edit(session, ctx, field, |edit, _config, _metrics| {
        edit.select_all();
    });
}

/// What a host draws for one page's open dropdown, if one is open.
///
/// State and geometry: the library says where the list is and what is in it,
/// and the host paints it on its own schedule. Nothing here is a callback and
/// nothing is a trait — a viewer that never asks is never told, and one that
/// asks twice gets the same answer.
///
/// [`None`] when nothing on the page has its dropdown open, which is the
/// common case: only a click on a drop button, a `Return` or a `Space` on a
/// gated combo opens one.
#[must_use]
/// # Examples
///
/// ```
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// // Nothing on this page has a dropdown, so a host is told to draw none.
/// assert!(route::popup_view(&session, &ctx).is_none());
/// ```
pub fn popup_view<R: Resolve>(
    session: &FormSession,
    ctx: &Context<'_, R>,
) -> Option<crate::popup::PopupView> {
    let (field, annot) = open_popup_of(session, ctx.page)?;
    let widget = ctx.widget(annot)?;
    let FieldState::Choice(choice) = session.fields.get(&field)? else {
        return None;
    };
    let geometry = popup_geometry(ctx, widget, choice)?;
    Some(crate::popup::PopupView {
        annot,
        anchor: crate::popup::widen(widget.rect),
        geometry,
        options: choice
            .options
            .iter()
            .map(|option| option.label.clone())
            .collect(),
        selected: choice.selected.iter().next().copied(),
        hovered: choice.hovered,
        top_visible: choice.top_visible,
        edit_text: choice.config.editable.then(|| choice.edit_text.clone()),
    })
}

/// How far one scrollable control has scrolled, in rows.
///
/// Keyed by annotation rather than carried on [`popup_view`]: a **list box**
/// scrolls without any dropdown being open, and its scroll bar is the host's
/// to draw for exactly the same reason the dropdown is. The host draws chrome;
/// this crate returns values, not callbacks.
///
/// [`None`] for an annotation that is not a choice widget, or one the session
/// has never built state for.
#[must_use]
/// # Examples
///
/// ```
/// # use pdfrum_form::AnnotId;
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// // The page's one widget is a text field, which has no rows to scroll.
/// assert!(route::scroll_view(&session, &ctx, AnnotId::new(0u32, 0)).is_none());
/// ```
pub fn scroll_view<R: Resolve>(
    session: &FormSession,
    ctx: &Context<'_, R>,
    annot: AnnotId,
) -> Option<crate::popup::ScrollView> {
    let widget = ctx.widget(annot)?;
    let FieldState::Choice(choice) = session.fields.get(&widget.field)? else {
        return None;
    };
    // An open dropdown scrolls in its own window, which is taller than the
    // widget; a closed combo and a list box scroll inside the widget's box.
    let visible = match popup_geometry(ctx, widget, choice).filter(|_| choice.popup_open) {
        Some(geometry) => geometry.visible_rows(),
        None => visible_rows(ctx, widget, choice),
    };
    Some(crate::popup::ScrollView {
        top_visible: choice.top_visible,
        visible_rows: visible,
        total: choice.options.len(),
    })
}

/// The host reporting that the user picked a row of an open dropdown.
///
/// A host that drew the list from [`popup_view`] tells the session what was
/// chosen, and the session does what a click on that row would have done —
/// select it, shut the list, and hand back the widget's new appearance.
/// Exactly `NotifyLButtonUp`'s sequence, reachable without synthesizing a
/// click at coordinates the host would have to compute backwards from the
/// geometry it was given.
///
/// An index past the end of the options is ignored, and the response is
/// [`Response::ignored`] — a host cannot corrupt a field by miscounting.
/// # Examples
///
/// ```
/// # use pdfrum_form::AnnotId;
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// // A host cannot corrupt a field by naming a row that is not there — or,
/// // as here, an annotation that is not a choice widget at all.
/// let response = route::choose(&mut session, &ctx, &mut cascade, AnnotId::new(0u32, 0), 7);
/// assert!(!response.consumed);
/// ```
pub fn choose<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    annot: AnnotId,
    index: usize,
) -> Response {
    // The cascade is taken but not spent here, and that is upstream's shape
    // rather than an omission: `CFFL_ComboBox::SaveData`
    // (`fpdfsdk/formfiller/cffl_combobox.cpp:90`) runs only from
    // `CommitData`, which only `KillFocusForAnnot` calls — so choosing a row
    // changes the selection and the scripts run when the field is left.
    // The parameter is on the signature because this is one of the three
    // entry points that *can* reach a commit , and a
    // caller must not have to discover later that it needs one.
    let _ = &cascade;
    let Some(widget) = ctx.widget(annot) else {
        return Response::ignored();
    };
    let field = widget.field;
    let in_range = matches!(
        session.fields.get(&field),
        Some(FieldState::Choice(choice)) if index < choice.options.len()
    );
    if !in_range {
        return Response::ignored();
    }
    release_in_popup(session, ctx, field, annot, index)
}

/// The host reporting that an open dropdown was dismissed without a choice.
///
/// `SetPopup(false)`, and nothing else: the stored selection is untouched,
/// which is what `bug_736695_4` asserts by hovering a row, clicking away, and
/// rendering a field that never changed.
///
/// [`Response::ignored`] when that annotation had no dropdown open, so a host
/// may call it unconditionally.
/// # Examples
///
/// ```
/// # use pdfrum_form::AnnotId;
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// // Safe to call unconditionally: with no dropdown open it changes nothing
/// // and says so.
/// assert!(!route::close_popup(&mut session, &ctx, AnnotId::new(0u32, 0)).consumed);
/// ```
pub fn close_popup<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    annot: AnnotId,
) -> Response {
    let Some(widget) = ctx.widget(annot) else {
        return Response::ignored();
    };
    let field = widget.field;
    let closed = match session.fields.get_mut(&field) {
        Some(FieldState::Choice(choice)) if choice.popup_open => {
            choice.popup_open = false;
            choice.hovered = None;
            true
        }
        _ => false,
    };
    if !closed {
        return Response::ignored();
    }
    let mut response = Response::consumed();
    response.absorb(redraw(session, ctx, field, annot));
    response
}

/// The height of one list-box row: the **laid-out** line, not the font size.
///
/// A row is one laid-out line: `(ascent - descent) * size / 1000`. At 12
/// points in Arimo that is **13.392** units, not 12, because the pair sums to
/// 1116. Returning the font size instead makes every row an eighth short,
/// which moves the scroll clamp, the wheel's visible-row count and the hit
/// test together.
///
/// The call below is deliberately the **same one** `ap::field_body::list_box`
/// makes per row, into a zero-height plate so the layout reports the row's
/// extent rather than the box's — so the height that is hit-tested and the
/// height that is drawn cannot drift apart. The first option's label is
/// measured because every row shares one font and one size.
fn row_height<R: Resolve>(ctx: &Context<'_, R>, widget: &WidgetInfo, choice: &ChoiceState) -> f32 {
    let client = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    let plate = pdfrum_doc::geom::rect(
        pdfrum_doc::geom::left(client),
        0.0,
        pdfrum_doc::geom::right(client),
        0.0,
    );
    let size = font_size(ctx, widget);
    let config = vt::Config {
        plate,
        font_size: if size > 0.0 {
            size
        } else {
            LIST_ROW_DEFAULT_SIZE
        },
        ..vt::Config::default()
    };
    let label = choice
        .options
        .first()
        .map_or("", |option| option.label.as_str());
    let measured = with_font(ctx, widget, |font, _substitute| {
        let layout = vt::layout(label, &config, &font.metrics);
        pdfrum_doc::geom::height(layout.content_rect_pdf(plate))
    });
    // A widget whose `/DA` names a font the form does not declare has no face
    // to measure with. Falling back to the font size keeps the clamp finite
    // rather than dividing by zero, for the path that cannot do better.
    match measured {
        Some(height) if height > 0.0 => height,
        _ => config.font_size,
    }
}

/// The size a list box's rows are set at when its `/DA` leaves it automatic.
///
/// `ap::field_body`'s own `LIST_ROW_DEFAULT_SIZE`, which is private to that
/// crate; the two must agree, and a test asserts a measured row against a
/// drawn one so they cannot quietly stop agreeing.
const LIST_ROW_DEFAULT_SIZE: f32 = 12.0;

/// The `/DA` font size, zero meaning automatic.
fn font_size<R: Resolve>(ctx: &Context<'_, R>, widget: &WidgetInfo) -> f32 {
    let form = ctx
        .catalog
        .dict(pdfrum_object::names::ACRO_FORM, ctx.resolve)
        .unwrap_or_default();
    ap::freetext::default_appearance(&widget.dict, &form, ctx.resolve)
        .map_or(0.0, |appearance| appearance.size)
}

/// A wheel notch over a list box.
///
/// **It moves the selection, not the view** — the same operation the arrow
/// keys perform — and the view follows only when the newly selected row would
/// otherwise be off screen. Reading the wheel as a scrollbar drag, the obvious
/// guess, leaves the selection behind on a row that has scrolled out of
/// sight.
fn scroll_choice(
    state: &mut ChoiceState,
    delta_y: i32,
    visible_rows: usize,
    modifiers: Modifiers,
) -> bool {
    if delta_y == 0 || state.options.is_empty() {
        return false;
    }
    // A negative delta is downward, which is the *next* row. The wheel's own
    // modifiers are handed on, because `OnMouseWheel` hands them to `OnVK`
    // and they decide what a multi-select list does with the row.
    let moved = field::choice::move_caret_by(
        state,
        if delta_y < 0 { 1 } else { -1 },
        modifiers.contains(Modifiers::SHIFT),
        modifiers.contains(Modifiers::CONTROL),
    );
    let caret = state.caret_index.unwrap_or(0);
    let scrolled = field::choice::scroll_into_view(state, caret, visible_rows);
    moved || scrolled
}

/// Scrolls a text field by a wheel notch.
///
/// A `DoNotScroll` field does not move: [`TextEdit::auto_scroll`] gates every
/// writer of the scroll position, the wheel included, and such a field is
/// drawn no scrollbar to drag either.
fn scroll_text<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    delta_y: i32,
) -> bool {
    if delta_y == 0 {
        return false;
    }
    let mut moved = false;
    with_edit(session, ctx, field, |edit, config, _metrics| {
        moved = ops::scroll_by(edit, config, delta_y);
    });
    moved
}

/// Moves focus to the next or previous ring entry.
fn tab_to_next<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    modifiers: Modifiers,
) -> Response {
    // Every modifier but shift refuses the gesture outright.
    if modifiers.contains(Modifiers::CONTROL)
        || modifiers.contains(Modifiers::ALT)
        || modifiers.contains(Modifiers::META)
    {
        return Response::ignored();
    }
    let backward = modifiers.contains(Modifiers::SHIFT);
    let ring = focus_ring(session, ctx);
    if ring.order.is_empty() {
        return Response::ignored();
    }
    // With nothing focused, forward and backward Tab land on *different*
    // annotations, because the cursor starts between the ends rather than
    // before them.
    let next = match (session.focus.map(FocusTarget::annot), backward) {
        (Some(current), false) => ring.next(current),
        (Some(current), true) => ring.prev(current),
        (None, false) => ring.first(),
        (None, true) => ring.last(),
    };
    let Some(next) = next else {
        return Response::ignored();
    };
    let target = match ctx.widget(next) {
        Some(widget) => FocusTarget::Widget(widget.field, next),
        None => FocusTarget::Annot(next),
    };
    let mut response = take_focus(session, ctx, cascade, target);
    if let Some(field) = target.field() {
        ensure_state(session, ctx, field);
        response.absorb(redraw(session, ctx, field, next));
    }
    response
}

/// The page's focus ring, filtered to the session's focusable subtypes.
///
/// The order is the **page's**, read from its `/Tabs` per page, not a
/// constant: under `/R` the first Tab can land on a different annotation than
/// structure order would answer.
fn focus_ring<R: Resolve>(session: &FormSession, ctx: &Context<'_, R>) -> tab::FocusRing {
    let focusables: Vec<tab::Focusable> = ctx
        .page
        .focusables
        .iter()
        .filter(|(subtype, _)| session.config.focusable.contains(subtype))
        .map(|(_, focusable)| *focusable)
        .collect();
    tab::FocusRing::build(&focusables, ctx.page.tab_order)
}

/// Runs one of the six pointer and focus `/AA` entries for the field an
/// annotation belongs to.
///
/// **Named by annotation rather than by field**, because that is what the
/// hover and hit tests answer with: a field with two widgets fires the
/// trigger for the one the pointer is actually over. A widget the page's
/// field list does not reach fires nothing, which is what `field_ref`
/// answering `None` means.
fn fire_pointer<R: Resolve>(
    session: &FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    annot: AnnotId,
    trigger: PointerTrigger,
    modifiers: Modifiers,
) {
    let _ = session;
    let Some(widget) = ctx.page.widgets.iter().find(|w| w.id == annot) else {
        return;
    };
    let Some(field) = field_ref(ctx, widget.field) else {
        return;
    };
    cascade.pointer(&field, trigger, modifiers);
}

/// How a field a caller is leaving named itself to its scripts.
///
/// `None` for a target that is not a widget, or one this page does not carry
/// — a script cannot be run for a field the routing context cannot see.
fn field_ref<R: Resolve>(ctx: &Context<'_, R>, field: FieldId) -> Option<FieldRef> {
    let widget = ctx.widget_of_field(field)?;
    Some(FieldRef {
        name: widget.name.clone(),
        // The **document-wide** position, not the page-local `FieldId`: a
        // script names fields in the space `/CO`, `Doc.numFields` and
        // `Doc.getNthFieldName` count in, and handing it a page-local id
        // would make a two-page form recalculate the wrong field. See
        // `page`'s module documentation for the two spaces.
        index: widget.field_index,
    })
}

/// The text a field currently holds in the session, for the commit gate.
///
/// Only the two families that carry text have one: a toggle's value is its
/// `/AS` state and a push button has none, and neither reaches the keystroke
/// half of the commit cascade.
fn edited_text(session: &FormSession, field: FieldId) -> Option<String> {
    match session.fields.get(&field)? {
        FieldState::Text(text) => Some(text.edit.text.clone()),
        FieldState::Choice(choice) if choice.config.editable => Some(choice.edit_text.clone()),
        FieldState::Choice(_) | FieldState::Toggle(_) | FieldState::Button(_) => None,
    }
}

/// Runs the commit cascade for a field that is losing focus.
///
/// Losing focus is the *only* point at which the script gates run over a
/// whole field value. The answer says whether focus may proceed: see
/// [`commit::CommitOutcome::keeps_focus`] and `commit`'s module documentation
/// for why a refusal keeps the field here where the oracle drops it.
///
/// `None` when nothing ran — a field with no text, or one whose value has not
/// moved — which is the ordinary case and the one that must cost nothing.
fn commit_field<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    field: FieldId,
) -> Option<commit::CommitOutcome> {
    let reference = field_ref(ctx, field)?;
    let edited = edited_text(session, field)?;
    let stored = ctx.widget_of_field(field)?.value(ctx.resolve);
    let outcome = commit::run(
        &reference,
        &stored,
        &edited,
        cascade,
        session.config.max_calculate_depth,
    );

    if outcome.reverted {
        // The gate refused: the field goes back to what the document holds,
        // and whatever a previous format script asked to be shown goes with
        // it — the value it described is no longer the value.
        set_field_text(session, field, &stored);
        session.formatted.remove(&field);
        return Some(outcome);
    }
    for (index, value) in &outcome.writes {
        // A calculation names fields by their document-wide field id, which
        // is what `FieldRef::index` carries.
        let written = ctx.field_of_index(*index).unwrap_or(FieldId(*index));
        set_field_text(session, written, value);
        session.dirty.insert(written);
        // A calculated field is formatted too: `AfterValueChange` is
        // `OnCalculate` then `ResetFieldAppearance(pField, OnFormat(pField))`
        // (`fpdfsdk/cpdfsdk_interactiveform.cpp:586-588`), and the second
        // half runs for every field the first half wrote.
        let display = field_ref(ctx, written)
            .and_then(|reference| cascade.format(&reference, value))
            .filter(|display| display != value);
        record_display(session, written, display);
    }
    // `ResetFieldAppearance(pField, OnFormat(pField))` — the formatting
    // script's answer is what the regenerated appearance draws, and `None`
    // puts the raw value back rather than leaving a stale display string.
    // Only when the commit actually ran: see `CommitOutcome::formats`.
    if outcome.formats() {
        record_display(session, field, outcome.display.clone());
    }
    Some(outcome)
}

/// Remembers — or forgets — what a field is to *show* in place of what it
/// stores.
///
/// `None` is the answer for a field with no format script and for one whose
/// script produced its input unchanged, and it must **erase** any earlier
/// string rather than leaving one: `None` means "draw the raw value", so a
/// stale entry here would keep drawing an answer the document no longer
/// gives.
fn record_display(session: &mut FormSession, field: FieldId, display: Option<String>) {
    match display {
        Some(display) => {
            session.formatted.insert(field, display);
        }
        None => {
            session.formatted.remove(&field);
        }
    }
}

/// Puts a field's text back to `value`, whichever text-bearing family it is.
fn set_field_text(session: &mut FormSession, field: FieldId, value: &str) {
    match session.fields.get_mut(&field) {
        Some(FieldState::Text(text)) => {
            text.edit.text = value.to_string();
            text.edit.undo = crate::edit::UndoStack::default();
        }
        Some(FieldState::Choice(choice)) if choice.config.editable => {
            choice.edit_text = value.to_string();
        }
        _ => {}
    }
}

/// Gives focus to a target, committing whatever held it.
fn take_focus<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    target: FocusTarget,
) -> Response {
    // The outgoing field's scripts run *before* focus moves, because a
    // refusal keeps it — `commit`'s module doc, and A63.
    if let Some(previous) = session.focus.and_then(FocusTarget::field)
        && session.focus != Some(target)
        && let Some(outcome) = commit_field(session, ctx, cascade, previous)
        && outcome.keeps_focus()
    {
        let annot = session.focus.map(FocusTarget::annot);
        let mut response = Response::consumed();
        if let Some(annot) = annot {
            response.absorb(redraw(session, ctx, previous, annot));
        }
        return response;
    }

    let change = focus::set(session, target);
    if !change.moved() {
        return Response::consumed();
    }
    let mut response = Response::consumed();
    // The outgoing field commits on the way out, which is what turns its
    // live editor state back into a generated appearance.
    if let Some(previous) = change.from {
        if change.clear_undo
            && let Some(field) = previous.field()
        {
            clear_undo(session, field);
        }
        if let Some(field) = previous.field() {
            response.absorb(redraw(session, ctx, field, previous.annot()));
        }
    }
    response.push(AppearanceUpdate::new(
        target.annot(),
        UpdateKind::FocusChanged {
            from: change.from.map(FocusTarget::annot),
            to: Some(target.annot()),
        },
    ));
    response
}

/// Gives the keyboard to a field a script named, running the two `/AA`
/// entries a click would.
///
/// `index` is a position in the document-wide field list — what
/// [`Cascade::take_focus_request`] answers and what
/// [`FieldRef::index`](crate::FieldRef::index) carries.
///
/// # The order, which is the whole of what this function is for
///
/// `CJS_Field::setFocus` reaches `CPDFSDK_FormFillEnvironment::SetFocusAnnot`,
/// which does two things in one order and never the other:
///
/// 1. the widget that **held** the keyboard loses it, which runs its
///    `/AA /Bl`;
/// 2. the widget that **takes** it runs its `/AA /Fo`.
///
/// So a document with a script on each alerts the outgoing field's line
/// first. A `setFocus` naming the field that already holds the keyboard is
/// `SetFocusAnnot`'s `focus_annot_ == pAnnot` early return: neither script
/// runs and nothing moves.
///
/// Answers [`Response::ignored`] for an index this page does not carry —
/// a script may name a field on a page nobody has read, and a routing context
/// that cannot see the widget cannot run its scripts.
/// # Examples
///
/// ```
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// // `index` is the document-wide field position a script names, not the
/// // page-local `FieldId`. This page's `/AcroForm` lists no `/Fields`, so no
/// // widget carries that position and the move is ignored rather than
/// // guessed at.
/// assert!(!route::focus_field(&mut session, &ctx, &mut cascade, 0).consumed);
/// assert!(route::focus_of(&session, &ctx).is_none());
/// ```
pub fn focus_field<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
    index: u32,
) -> Response {
    let Some(field) = ctx.field_of_index(index) else {
        return Response::ignored();
    };
    let Some(id) = ctx.widget_of_field(field).map(|widget| widget.id) else {
        return Response::ignored();
    };
    let target = FocusTarget::Widget(field, id);
    if session.focus == Some(target) {
        // `if (focus_annot_ == pAnnot) return true;` — the keyboard is
        // already here, and neither script fires.
        return Response::consumed();
    }
    // (1) The outgoing widget's `/AA /Bl`. `KillFocusAnnot` reaches
    // `CFFL_InteractiveFormFiller::OnKillFocus`, which is the one path that
    // runs the entry — a click that leaves a field does not, which is the
    // upstream bug `mouse_events.evt` names beside its own two "should
    // trigger an On Blur event" comments and which we reproduce.
    if let Some(previous) = session.focus.map(FocusTarget::annot) {
        fire_pointer(
            session,
            ctx,
            cascade,
            previous,
            PointerTrigger::Blur,
            Modifiers::NONE,
        );
    }
    // (2) The incoming widget's `/AA /Fo`, then the move itself — which
    // commits whatever the outgoing field held, exactly as a click does.
    fire_pointer(
        session,
        ctx,
        cascade,
        id,
        PointerTrigger::Focus,
        Modifiers::NONE,
    );
    let mut response = take_focus(session, ctx, cascade, target);
    ensure_state(session, ctx, field);
    response.absorb(redraw(session, ctx, field, id));
    response
}

/// Drops focus, redrawing what held it as a committed appearance.
///
/// Public because it is not only a left click's miss path: the embedder's own
/// `FORM_ForceToKillFocus` is the same operation, and a second implementation
/// of it would be a second chance to forget the redraw. Dropping focus is
/// what turns a field's live editor state back into a generated stream, so a
/// version that only reported `FocusChanged` would leave the caret and the
/// live text on the page.
/// # Examples
///
/// ```
/// # use kurbo::Point;
/// # use pdfrum_form::{Button, Event, Modifiers};
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// let at = Point { x: 100.0, y: 115.0 };
/// for event in [
///     Event::MouseDown { button: Button::Left, at, modifiers: Modifiers::NONE },
///     Event::MouseUp { button: Button::Left, at, modifiers: Modifiers::NONE },
/// ] {
///     route::apply(&mut session, &ctx, &mut cascade, event);
/// }
/// assert!(route::focus_of(&session, &ctx).is_some());
///
/// // Dropping focus turns the live editor back into a generated appearance,
/// // which is why it hands back an update rather than only a flag.
/// let response = route::kill_focus(&mut session, &ctx, &mut cascade);
/// assert!(response.consumed);
/// assert!(!response.updates.is_empty());
/// assert!(route::focus_of(&session, &ctx).is_none());
/// ```
pub fn kill_focus<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
) -> Response {
    let mut response = drop_focus(session, ctx, cascade);
    // The commit this ran is a script, and a script may call
    // `Field.setFocus` — which then puts the keyboard somewhere rather than
    // nowhere. Spent here for the same reason `apply` spends it.
    response.absorb(honour_focus_requests(session, ctx, cascade));
    response
}

/// [`kill_focus`] without spending a focus request.
fn drop_focus<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    cascade: &mut dyn Cascade,
) -> Response {
    // `CPWL_ComboBox::KillFocus` (`cpwl_combo_box.cpp:52-58`) shuts the list
    // *before* the base class drops focus, and returns early if it could not
    // — so a dropdown never outlives the focus that opened it. Run
    // unconditionally, ahead of `focus::kill`, because it must happen even
    // when the outgoing field is not the one that had a list open.
    let closed = close_all_popups(session);
    // The commit runs before focus goes, because a refusal keeps the field
    // (`commit`'s module doc, A63). `FORM_ForceToKillFocus` is the same
    // operation and the same gate: `KillFocusForAnnot` consults `CommitData`
    // first (`fpdfsdk/formfiller/cffl_formfield.cpp:306`).
    if let Some(previous) = session.focus.and_then(FocusTarget::field)
        && let Some(outcome) = commit_field(session, ctx, cascade, previous)
        && outcome.keeps_focus()
    {
        let annot = session.focus.map(FocusTarget::annot);
        let mut response = Response::consumed();
        if let Some(annot) = annot {
            response.absorb(redraw(session, ctx, previous, annot));
        }
        return response;
    }
    let change = focus::kill(session);
    let Some(was) = change.from else {
        // Nothing held focus, but a list may still have been open — a host
        // that opened one through `choose`'s sibling entry points, or a
        // session whose focus was force-killed. Report the redraw rather than
        // leaving a shut list drawn.
        return if closed {
            Response::consumed()
        } else {
            Response::ignored()
        };
    };
    let mut response = Response::consumed();
    if let Some(field) = was.field() {
        if change.clear_undo {
            clear_undo(session, field);
        }
        response.absorb(redraw(session, ctx, field, was.annot()));
    }
    response.push(AppearanceUpdate::new(
        was.annot(),
        UpdateKind::FocusChanged {
            from: Some(was.annot()),
            to: None,
        },
    ));
    response
}

/// Empties a field's undo history, which leaving it for another field does.
fn clear_undo(session: &mut FormSession, field: FieldId) {
    if let Some(FieldState::Text(state)) = session.fields.get_mut(&field) {
        state.edit.undo = crate::edit::UndoStack::default();
    }
}

/// A radio button's siblings on this page lose their state when it is set.
///
/// Every control of the field is walked: the one at the clicked index takes
/// its own on state and **every other one is set to `Off`**. Which control is
/// which matters, because two kids of a radio group carry different on-state
/// names — that is how `/V` names the chosen one.
///
/// A field's controls share one [`ToggleState`] here, so the per-control `/AS`
/// that walk writes cannot be stored control by control. What *is* storable is
/// **which** control is the checked one, and that is what this records: a
/// caller reading [`ToggleState::checked_control`] can tell the chosen kid
/// from its siblings, where before the two were indistinguishable.
///
/// # How the difference is drawn
///
/// A toggle's appearance is its `/AS` state. The generator reads
/// [`ap::widget::LiveInput::appearance_state`] first, filled in from
/// [`ToggleState::state_for_control`]: the chosen kid its own on-state name,
/// every sibling `Off`, and a group nothing has clicked `None`, which is the
/// file's own `/AS` unchanged.
fn clear_siblings<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    chosen: AnnotId,
) {
    let Some(widget) = ctx.widget(chosen) else {
        return;
    };
    if toggle_kind(widget) != Some(ToggleKind::Radio) {
        return;
    }
    if let Some(FieldState::Toggle(state)) = session.fields.get_mut(&field) {
        state.checked_control = Some(chosen);
    }
}

/// Which toggle a widget is, if it is one.
fn toggle_kind(widget: &WidgetInfo) -> Option<ToggleKind> {
    match widget.kind {
        Some(pdfrum_doc::form::FieldKind::Check) => Some(ToggleKind::Check),
        Some(pdfrum_doc::form::FieldKind::Radio) => Some(ToggleKind::Radio),
        _ => None,
    }
}

/// The drag anchor a fresh click drops.
fn caret_anchor(session: &FormSession, field: FieldId) -> Option<DragAnchor> {
    match session.fields.get(&field) {
        Some(FieldState::Text(state)) => Some(DragAnchor {
            field,
            start: state.edit.caret,
        }),
        _ => None,
    }
}

/// Extends a drag to a point.
fn drag_to<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    anchor: DragAnchor,
    at: Point,
) -> Option<AppearanceUpdate> {
    let field = anchor.field;
    let point = ctx
        .widget_of_field(field)
        .map(|widget| to_plate(widget, at))?;
    with_edit(session, ctx, field, |edit, config, metrics| {
        ops::drag_to(edit, config, metrics, point);
    });
    let id = session.focus.map(FocusTarget::annot)?;
    appearance_of(session, ctx, field, id)
}

/// Builds a field's interaction state, if it does not have one yet.
fn ensure_state<R: Resolve>(session: &mut FormSession, ctx: &Context<'_, R>, field: FieldId) {
    if session.fields.contains_key(&field) {
        return;
    }
    let Some(widget) = ctx.widget_of_field(field) else {
        return;
    };
    let Some(state) = build_state(ctx, widget) else {
        return;
    };
    session.fields.insert(field, state);
}

/// Reads one field's interaction state out of the file.
fn build_state<R: Resolve>(ctx: &Context<'_, R>, widget: &WidgetInfo) -> Option<FieldState> {
    let family = field::family_of(widget.kind?)?;
    Some(match family {
        field::Family::Text => {
            let config = widget.text_config(ctx.resolve);
            let value = widget.value(ctx.resolve);
            FieldState::Text(field::TextState {
                edit: build_edit(ctx, widget, &value, &config),
                config,
            })
        }
        field::Family::Choice => {
            let config = widget.choice_config();
            let options = widget.options(ctx.resolve);
            let selected = widget.selected(ctx.resolve);
            let mut state = ChoiceState::new(options, config);
            for index in selected {
                state.selected.insert(index);
            }
            state.caret_index = state.selected.iter().next().copied();
            state.top_visible = widget.top_index(ctx.resolve);
            FieldState::Choice(state)
        }
        field::Family::Toggle => {
            let on_state = on_state_of(ctx, widget);
            let checked = !widget.value(ctx.resolve).is_empty()
                && widget.value(ctx.resolve) != field::toggle::OFF_STATE;
            let mut state = ToggleState::new(field::toggle::OFF_STATE, on_state);
            state.set_checked(checked);
            FieldState::Toggle(state)
        }
        field::Family::Button => FieldState::Button(field::ButtonState::default()),
    })
}

/// The appearance-state name a toggle shows when checked.
fn on_state_of<R: Resolve>(ctx: &Context<'_, R>, widget: &WidgetInfo) -> String {
    // The `/AP /N` dictionary's keys are the states; the one that is not
    // `Off` is the on state.
    widget
        .dict
        .dict(pdfrum_object::names::AP, ctx.resolve)
        .and_then(|ap| ap.dict(pdfrum_object::names::N, ctx.resolve))
        .and_then(|normal| {
            normal
                .keys()
                .find(|key| key.as_bytes() != field::toggle::OFF_STATE.as_bytes())
                .map(|key| String::from_utf8_lossy(key.as_bytes()).into_owned())
        })
        .unwrap_or_default()
}

/// Builds a text field's edit control over a value.
fn build_edit<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    value: &str,
    config: &crate::field::TextConfig,
) -> TextEdit {
    let plate = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    let vt_config = text_config(ctx, widget, plate, config);
    let mut edit = with_font(ctx, widget, |font, _substitute| {
        TextEdit::new(value, &vt_config, &font.metrics, !config.multi_line)
    })
    .unwrap_or_else(|| {
        // No face at all: lay the value out against zero-width metrics, so
        // the text is still stored and every query still answers.
        let width = |_code: u32| 0;
        let metrics = vt::Metrics {
            width: &width,
            ascent: 0,
            descent: 0,
        };
        TextEdit::new(value, &vt_config, &metrics, !config.multi_line)
    });
    // `CFFL_TextField::GetCreateParam` (`cffl_textfield.cpp:54-63`) raises
    // `kEditAutoScroll` for a text field without `DoNotScroll`, multi-line or
    // not, and `CPWL_Edit::OnCreated` (`cpwl_edit.cpp:131`) hands it to the
    // control. This is the one place that knows the flag.
    edit.auto_scroll = config.auto_scroll;
    edit
}

/// The layout configuration a text field's body is set with.
///
/// The **same** configuration `ap::field_body` builds, because a caret
/// computed against a different one lands somewhere the glyphs are not.
fn text_config<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    plate: kurbo::Rect,
    config: &crate::field::TextConfig,
) -> vt::Config {
    let mut vt_config = vt::Config {
        plate,
        alignment: ap::field_body::alignment(&widget.dict, ctx.resolve),
        font_size: font_size(ctx, widget),
        multi_line: config.multi_line,
        auto_return: config.multi_line,
        sub_word: config.password.then_some('*'),
        ..vt::Config::default()
    };
    if let Some(max) = config.max_len {
        let cells = usize::try_from(max.get()).unwrap_or(0);
        if config.comb {
            vt_config.char_array = cells;
        } else {
            vt_config.limit_char = cells;
        }
    }
    vt_config
}

/// Runs `body` with the face a widget's `/DA` names, and the **second face**
/// for the characters that face's charset cannot write.
///
/// Answers `None` only when the form declares no font at all, which is a
/// document with no `/DR` and no fallback — there is no metric to lay text
/// out with, so the caller declines rather than inventing one.
///
/// # Why the width closure has to know about the second face
///
/// This is the same construction `ap::generate_appearances_with_text` makes
/// for the *stored* path, and it is made here rather than borrowed because
/// the closure has to outlive the [`TextFont`] that borrows it.
///
/// The point worth restating is that the substitute enters through the
/// **width closure** and not only through the encoder. A run set in two faces
/// advances by two faces' metrics; measuring it all with the first gives a
/// line the wrong length wherever the second one writes — which is exactly how
/// a Hebrew selection band comes to end ten units short of the glyphs it was
/// supposed to cover. The face is chosen per character, and knows nothing
/// about whether the character was typed or stored, so the typed path takes
/// the same answer as the stored one.
fn with_font<R: Resolve, T>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    body: impl FnOnce(&TextFont<'_>, Option<ap::Substitute<'_>>) -> T,
) -> Option<T> {
    let form = ctx
        .catalog
        .dict(pdfrum_object::names::ACRO_FORM, ctx.resolve)
        .unwrap_or_default();
    let name = ap::freetext::default_appearance(&widget.dict, &form, ctx.resolve)
        .map(|appearance| appearance.font_name)
        .unwrap_or_default();
    // `face` falls back to the last declared face on its own, so a name the
    // form does not declare still lays out rather than declining.
    let font = ctx.fonts.face(&name)?;
    let da_charset = ap::font_map::font_charset(font);
    let substitute = ap::font_map::SUBSTITUTABLE_CHARSETS
        .iter()
        .find(|charset| **charset != da_charset)
        .and_then(|charset| ctx.fonts.substitute(*charset));
    let width = move |code: u32| match substitute {
        Some(sub) if !ap::font_map::da_font_writes(font, da_charset, code) => {
            ap::font_map::substitute_width(sub.font, code)
        }
        _ => TextFont::char_width(font, code),
    };
    let text_font = TextFont {
        metrics: TextFont::metrics_of(font, &width),
        font,
    };
    Some(body(&text_font, substitute))
}

/// Replaces a field's selection with `text`, or deletes it when `text` is
/// empty.
///
/// The embedder's paste, and half of its cut. Answers whether the field
/// changed — which an empty replacement of an empty selection does not, and
/// a read-only field never does.
/// # Examples
///
/// ```
/// # use kurbo::Point;
/// # use pdfrum_form::field::FieldState;
/// # use pdfrum_form::{Button, Event, FieldId, Modifiers};
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// # let at = Point { x: 100.0, y: 115.0 };
/// # for event in [
/// #     Event::MouseDown { button: Button::Left, at, modifiers: Modifiers::NONE },
/// #     Event::MouseUp { button: Button::Left, at, modifiers: Modifiers::NONE },
/// # ] { route::apply(&mut session, &ctx, &mut cascade, event); }
/// // The embedder's paste, at the caret the click left.
/// assert!(route::replace_selection(&mut session, &ctx, FieldId(0), "Hello"));
///
/// let Some(FieldState::Text(state)) = session.fields.get(&FieldId(0)) else {
///     unreachable!("the click built the field's state")
/// };
/// assert_eq!(state.edit.text, "oldHello");
///
/// // A field the session has never built state for has no selection to
/// // replace, and refuses rather than creating one.
/// assert!(!route::replace_selection(&mut session, &ctx, FieldId(9), "x"));
/// ```
pub fn replace_selection<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    text: &str,
) -> bool {
    let max_len = match session.fields.get(&field) {
        Some(FieldState::Text(state)) if !state.config.read_only => {
            state.config.max_len.map(std::num::NonZeroU32::get)
        }
        // A read-only field refuses, and a non-text field has no selection to
        // replace.
        _ => return false,
    };
    let mut changed = false;
    with_edit(session, ctx, field, |edit, config, metrics| {
        if text.is_empty() && !edit.has_selection() {
            return;
        }
        changed = ops::replace_selection(edit, config, metrics, text, max_len);
    });
    if changed {
        session.dirty.insert(field);
    }
    changed
}

/// A page-space point in the widget's **appearance-stream** space, y-up.
///
/// The two spaces differ by two things rather than one.
///
/// The widget's own corner, first: `ap::widget::rotated_rect` places a
/// widget's box at the origin, so a plate is always `(0, 0)`-based while an
/// event's point is wherever the widget sits on the page. Forgetting it is
/// silent rather than loud — it puts every click far to the right of the
/// text, where the hit test clamps it to one end and every caret lands in the
/// same place.
///
/// And the widget's **rotation**: at `/MK /R 90` the appearance stream is set
/// into a box whose axes are exchanged, so a click that is not un-rotated
/// arrives on the wrong axis entirely. [`geom::Plate::to_widget`] carries the
/// table.
///
/// The result stays y-**up**, because that is what every consumer wants:
/// `ap::field_body::client_rect` is y-up, and `vt::hit`'s queries take a y-up
/// point and do their own flip. Handing them a y-down one flips it twice.
fn to_plate(widget: &WidgetInfo, at: Point) -> kurbo::Point {
    let point = plate_of(widget).to_widget(at);
    kurbo::Point::new(f64::from(point.x), f64::from(point.y))
}

/// The widget's page↔plate mapping, rotation included.
fn plate_of(widget: &WidgetInfo) -> crate::geom::Plate {
    crate::geom::Plate::new(widget.rect, widget.rotation)
}

/// Runs `body` against a text field's live edit control.
fn with_edit<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    body: impl FnOnce(&mut TextEdit, &vt::Config, &vt::Metrics<'_>),
) {
    let Some(widget) = ctx.widget_of_field(field).cloned() else {
        return;
    };
    let Some(FieldState::Text(state)) = session.fields.get_mut(&field) else {
        return;
    };
    let plate = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    let config = text_config(ctx, &widget, plate, &state.config);
    with_font(ctx, &widget, |font, _substitute| {
        body(&mut state.edit, &config, &font.metrics);
    });
}

/// Runs `body` against an editable combo box's edit control.
fn with_combo_edit<R: Resolve>(
    session: &mut FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    body: impl FnOnce(&mut TextEdit, &vt::Config, &vt::Metrics<'_>),
) {
    let Some(widget) = ctx.widget_of_field(field).cloned() else {
        return;
    };
    let Some(FieldState::Choice(state)) = session.fields.get_mut(&field) else {
        return;
    };
    let client = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    // A combo box sets its text into the box left of the drop button.
    let plate = kurbo::Rect::new(client.x0, client.y0, client.x1 - 13.0, client.y1);
    let config = vt::Config {
        plate,
        font_size: font_size(ctx, &widget),
        ..vt::Config::default()
    };
    let editable = state.config.editable;
    if !editable {
        return;
    }
    let text = state.edit_text.clone();
    with_font(ctx, &widget, |font, _substitute| {
        let mut edit = state
            .edit
            .take()
            .unwrap_or_else(|| Box::new(TextEdit::new(text, &config, &font.metrics, true)));
        body(&mut edit, &config, &font.metrics);
        state.edit_text.clone_from(&edit.text);
        state.edit = Some(edit);
    });
}

/// The appearance a field should now draw, and the update carrying it.
fn redraw<R: Resolve>(
    session: &FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    id: AnnotId,
) -> Response {
    match appearance_of(session, ctx, field, id) {
        Some(update) => Response::with(vec![update]),
        None => Response::consumed(),
    }
}

/// Builds one widget's appearance from the session's state.
///
/// The focused field takes the live-edit path, with its caret and selection;
/// every other field takes the committed one. That branch is the whole seam
/// between appearance generation and interaction.
fn appearance_of<R: Resolve>(
    session: &FormSession,
    ctx: &Context<'_, R>,
    field: FieldId,
    id: AnnotId,
) -> Option<AppearanceUpdate> {
    let widget = ctx.widget(id)?;
    let state = session.fields.get(&field)?;
    let focused = session.focus.map(FocusTarget::annot) == Some(id);

    // A format script's answer is what an **unfocused** field draws, and the
    // raw value is what a focused one edits — `CFFL_FormField::OnSetFocus`
    // seeds its editor from `GetValue()`, never from the formatted text.
    let display = (!focused)
        .then(|| session.formatted.get(&field))
        .flatten()
        .map(String::as_str);
    let generated = generate(ctx, widget, state, focused, display)?;
    let kind = if focused {
        UpdateKind::LiveEdit(Box::new(generated))
    } else {
        UpdateKind::Regenerated(Box::new(generated))
    };
    Some(AppearanceUpdate::new(id, kind))
}

/// Generates a widget's appearance stream for its current interaction state.
///
/// The whole seam between appearance generation and interaction, and it is
/// one branch: a **focused** field is drawn with its caret or its selection
/// bands over the text the *session* holds, and every other field is drawn
/// from the text the *file* holds. Both go through the same generator, so a
/// committed field and a never-touched one produce the same bytes.
fn generate<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    state: &FieldState,
    focused: bool,
    display: Option<&str>,
) -> Option<pdfrum_doc::GeneratedAp> {
    let selected = selected_rows(state);
    let live = live_state(state, &selected, display);
    let highlight = focused.then(|| highlight_of(ctx, widget, state)).flatten();
    // A radio group's kids each carry a different on-state name, and a click
    // on one sets that kid's `/AS` to its own name and every sibling's to
    // `Off`. A session holds one record per *field*, so this is the per-kid
    // half of `CheckControl` the record can express — see
    // `ToggleState::state_for_control`, and `clear_siblings` for what puts
    // the chosen control there. `None` means "read the widget's own `/AS`",
    // which is every widget nothing has clicked.
    let as_override = match state {
        FieldState::Toggle(toggle) => toggle.state_for_control(widget.id),
        FieldState::Text(_) | FieldState::Choice(_) | FieldState::Button(_) => None,
    };
    // `LiveInput` is **not** `#[non_exhaustive]`, so this literal has to name
    // every field and a new one upstream is a compile error here rather than a
    // silent default. That is a real cost paid once already — `6e87424`'s
    // `appearance_state` broke this construction site and left `pdfrum-form`
    // failing to build for a period — and the fix is not to spell the literal
    // differently but to mark the struct: whoever adds a sixth field should
    // put `#[non_exhaustive]` on it first, and give it a `Default` so callers
    // outside `pdfrum-doc` can still build one.
    with_font(ctx, widget, |font, substitute| {
        ap::widget::generate_with_live_faces(
            &widget.dict,
            ctx.catalog,
            font,
            ctx.resolve,
            ap::widget::LiveInput {
                caret_and_selection: highlight.as_ref(),
                live: live.as_ref(),
                substitute,
                appearance_state: as_override.map(str::as_bytes),
            },
        )
    })
    .flatten()
}

/// Which annotation holds focus, and what its focus rectangle is.
///
/// The two halves are independent and both are needed. The **index** decides
/// the tint: a widget the form filler is editing is never given the
/// form-field highlight, focused or not, and in a single-focus session the
/// focused one is the only widget a live control reaches. The **box** decides
/// what is stroked in the tint's place, which most field types answer with
/// nothing at all.
///
/// The whole table, by control:
///
/// | control | focus box |
/// |---|---|
/// | text field | [`ap::FocusBox::None`] |
/// | **any** combo box | [`ap::FocusBox::None`] |
/// | multi-select list | its caret row |
/// | single-select list, check box, radio | [`ap::FocusBox::Inflated`] |
/// | push button | [`ap::FocusBox::Rect`] of the window **deflated by the border** |
///
/// So "focused" is mostly a *negative* instruction: it suppresses the tint,
/// and only three of the five controls stroke anything in its place.
// Two rows are easy to get wrong in the same direction, by reaching for the
// generic answer where the control overrides it. A combo box gives an empty
// rectangle whatever its custom-text flag says, so the editable and gated
// cases are one row, not two. And a push button deflates where the generic
// answer inflates — the opposite sign on the same number.
#[must_use]
/// # Examples
///
/// ```
/// # use pdfrum_doc::ap;
/// # use pdfrum_form::route::{self, Context};
/// # use pdfrum_form::{FormSession, NoScripts, Permissions};
/// # use pdfrum_object::{Dict, Name, NoResolve, Object, PdfString};
/// # fn dict<const N: usize>(pairs: [(&'static [u8], Object); N]) -> Dict {
/// #     Dict::from_pairs(pairs.into_iter().map(|(k, v)| (Name::from(k), v)))
/// # }
/// # fn nm(b: &'static [u8]) -> Object { Object::Name(Name::from(b)) }
/// # fn rect(l: f32, b: f32, r: f32, t: f32) -> Object {
/// #     Object::Array([l, b, r, t].into_iter().map(Object::Real).collect())
/// # }
/// # let helv = dict([(b"Type", nm(b"Font")), (b"Subtype", nm(b"Type1")),
/// #     (b"BaseFont", nm(b"Helvetica"))]);
/// # let catalog = dict([(b"AcroForm", Object::Dict(dict([
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 0 Tf 0 g"))),
/// #     (b"DR", Object::Dict(dict([(b"Font",
/// #         Object::Dict(dict([(b"Helv", Object::Dict(helv))])))]))),
/// # ])))]);
/// # let widget = dict([(b"Type", nm(b"Annot")), (b"Subtype", nm(b"Widget")),
/// #     (b"FT", nm(b"Tx")), (b"T", Object::Str(PdfString::literal(b"Name"))),
/// #     (b"V", Object::Str(PdfString::literal(b"old"))),
/// #     (b"Rect", rect(20.0, 100.0, 180.0, 130.0)),
/// #     (b"DA", Object::Str(PdfString::literal(b"/Helv 12 Tf 0 g")))]);
/// # let page_dict = dict([(b"MediaBox", rect(0.0, 0.0, 200.0, 200.0)),
/// #     (b"Annots", Object::Array([Object::Dict(widget)].into_iter().collect()))]);
/// # let resolve = NoResolve;
/// # let page = pdfrum_form::read_page(0, &page_dict, &catalog, &resolve);
/// # let mut build = pdfrum_page::BuildContext::new();
/// # let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
/// # let ctx = Context { page: &page, catalog: &catalog, resolve: &resolve,
/// #     fonts: &fonts, permissions: Permissions::ALL };
/// # let mut session = FormSession::new();
/// # let mut cascade = NoScripts;
/// // A fresh session holds no focus, so the page renders with none.
/// assert!(route::focus_of(&session, &ctx).is_none());
/// ```
pub fn focus_of<R: Resolve>(session: &FormSession, ctx: &Context<'_, R>) -> Option<ap::Focus> {
    let target = session.focus?;
    let annot = target.annot();
    if annot.page != ctx.page.page {
        // Focus belongs to the document, not the page, so a page that does
        // not hold it contributes no focus to its own render.
        return None;
    }
    let index = usize::try_from(annot.index).unwrap_or(0);
    let Some(field) = target.field() else {
        return Some(ap::Focus::at(index));
    };
    let box_ = match session.fields.get(&field) {
        // A text field strokes nothing. A field with no state yet has no
        // control to ask, so it strokes nothing either.
        Some(FieldState::Text(_)) | None => ap::FocusBox::None,
        // A combo box strokes nothing whether it is editable or gated:
        // `CPWL_ComboBox::GetFocusRect` returns an empty rectangle
        // unconditionally.
        Some(FieldState::Choice(choice)) if choice.config.combo => ap::FocusBox::None,
        // A single-select list box takes the window rectangle inflated by one
        // — the generic `CPWL_Wnd` answer, which it does not override.
        Some(FieldState::Choice(choice)) if !choice.config.multi_select => ap::FocusBox::Inflated,
        // A multi-select list box strokes its **caret row** rather than its
        // own edges, which is why its dashes trace a band inside the widget.
        Some(FieldState::Choice(choice)) => caret_row_box(ctx, annot, choice),
        // A check box and a radio button take the generic inflation.
        Some(FieldState::Toggle(_)) => ap::FocusBox::Inflated,
        // A push button deflates by its own border instead.
        Some(FieldState::Button(_)) => push_button_box(ctx, annot),
    };
    Some(ap::Focus { annot: index, box_ })
}

/// The rectangle a push button strokes: its window, deflated by the border.
///
/// The deflation is by the border on **each** side — the same `widget_border`
/// width `ap::field_body::client_rect` already reads. Unlike every other row
/// in the table this is a real rectangle rather than a rule, so it is produced
/// in page space, which is what [`ap::FocusBox::Rect`] carries.
fn push_button_box<R: Resolve>(ctx: &Context<'_, R>, annot: AnnotId) -> ap::FocusBox {
    let Some(widget) = ctx.widget(annot) else {
        return ap::FocusBox::None;
    };
    let width = f64::from(ap::widget::widget_border(&widget.dict, ctx.resolve).width);
    let rect = pdfrum_doc::geom::normalize(widget_rect(widget));
    // `CFX_FloatRect::GetDeflated` on a box narrower than twice its border
    // turns it inside out rather than emptying it, and `GetFocusBox` then
    // drops it for not being inside the page. Normalizing keeps the same
    // answer without a second rule.
    ap::FocusBox::Rect(pdfrum_doc::geom::normalize(kurbo::Rect::new(
        rect.x0 + width,
        rect.y0 + width,
        rect.x1 - width,
        rect.y1 - width,
    )))
}

/// The rectangle a multi-select list box strokes: its caret row, clipped to
/// the client area.
fn caret_row_box<R: Resolve>(
    ctx: &Context<'_, R>,
    annot: AnnotId,
    choice: &ChoiceState,
) -> ap::FocusBox {
    let Some(widget) = ctx.widget(annot) else {
        return ap::FocusBox::None;
    };
    let Some(caret) = choice.caret_index else {
        return ap::FocusBox::None;
    };
    let client = ap::field_body::client_rect(&widget.dict, ctx.resolve);
    let height = f64::from(row_height(ctx, widget, choice));
    if height <= 0.0 {
        return ap::FocusBox::None;
    }
    // Rows are drawn from the top down, starting at the first visible one.
    let Some(offset) = caret.checked_sub(choice.top_visible) else {
        return ap::FocusBox::None;
    };
    #[expect(
        clippy::cast_precision_loss,
        reason = "a row offset is bounded by the option count, which a file \
                  cannot make large enough to lose a mantissa bit"
    )]
    let top = client.y1 - height * offset as f64;
    let bottom = top - height;
    // Clipped to the client area, so a caret scrolled out of view strokes
    // nothing rather than a band outside the widget.
    if bottom >= client.y1 || top <= client.y0 {
        return ap::FocusBox::None;
    }
    // `client_rect` is in the appearance stream's own space — `rotated_rect`
    // puts the box at the origin — and a focus box is in **page** space, so
    // the widget's own corner is added back. Skipping this strokes a band at
    // the foot of the page, which is where the widget would be if its
    // rectangle started at zero.
    let origin = pdfrum_doc::geom::normalize(widget_rect(widget));
    ap::FocusBox::Rect(kurbo::Rect::new(
        client.x0 + origin.x0,
        bottom.max(client.y0) + origin.y0,
        client.x1 + origin.x0,
        top.min(client.y1) + origin.y0,
    ))
}

/// A widget's `/Rect` as `kurbo` sees it.
fn widget_rect(widget: &WidgetInfo) -> kurbo::Rect {
    kurbo::Rect::new(
        f64::from(widget.rect.left),
        f64::from(widget.rect.bottom),
        f64::from(widget.rect.right),
        f64::from(widget.rect.top),
    )
}

/// The rows a choice field has selected, as the generator wants them.
///
/// Materialized separately because [`ap::field_body::LiveState`] borrows the
/// slice, so it cannot own one built inside its own constructor.
fn selected_rows(state: &FieldState) -> Vec<usize> {
    match state {
        FieldState::Choice(choice) => choice.selected.iter().copied().collect(),
        FieldState::Text(_) | FieldState::Toggle(_) | FieldState::Button(_) => Vec::new(),
    }
}

/// What the session is showing, in place of what the file stores.
fn live_state<'a>(
    state: &'a FieldState,
    selected: &'a [usize],
    display: Option<&'a str>,
) -> Option<ap::field_body::LiveState<'a>> {
    match state {
        FieldState::Text(text) => Some(ap::field_body::LiveState {
            // `pEdit->SetText(sValue.value_or(pField->GetValue()))` — one
            // line, and the whole of what a format script changes
            // (`fpdfsdk/cpdfsdk_appstream.cpp:1752`). The formatted string is
            // drawn and never stored, which is why the caret still edits the
            // raw value the moment this field takes focus.
            text: display.unwrap_or(&text.edit.text),
            scroll: text.edit.scroll,
            ..ap::field_body::LiveState::default()
        }),
        FieldState::Choice(choice) => Some(ap::field_body::LiveState {
            // An editable combo shows what has been typed into it; every
            // other choice field shows the row it has selected, which the
            // generator resolves from `selected` rather than from text.
            //
            // A format script's answer overrides the typed text and nothing
            // else: `SetAsComboBox(sValue)` is the combo half of the same
            // `ResetAppearance` optional, and a list box is passed
            // `std::nullopt` unconditionally
            // (`cpdfsdk_interactiveform.cpp:611`).
            text: match (display, choice.config.editable) {
                (Some(display), true) => display,
                (_, true) => &choice.edit_text,
                (_, false) => "",
            },
            selected,
            top_visible: choice.top_visible,
            scroll: (0.0, 0.0),
        }),
        // A toggle's appearance is its `/AS` state, not a body, and a push
        // button's caption never changes.
        FieldState::Toggle(_) | FieldState::Button(_) => None,
    }
}

/// The caret or selection bands a focused field draws.
fn highlight_of<R: Resolve>(
    ctx: &Context<'_, R>,
    widget: &WidgetInfo,
    state: &FieldState,
) -> Option<ap::field_body::Highlight> {
    match state {
        FieldState::Text(text) => {
            let plate = ap::field_body::client_rect(&widget.dict, ctx.resolve);
            let config = text_config(ctx, widget, plate, &text.config);
            with_font(ctx, widget, |font, _substitute| {
                ops::highlight(
                    &text.edit,
                    &config,
                    &font.metrics,
                    ap::field_body::CARET_WIDTH,
                )
            })
        }
        // **An editable combo box has a caret and a selection band too**, and
        // for the same reason a text field does: its text half *is* a
        // `CPWL_Edit` (`cpwl_combo_box.cpp:190-203`), read-only only when the
        // box is gated (`:115-118`). Choosing a row leaves that edit holding
        // the row's label with everything selected, which is what draws the
        // navy band under `bug_736695_3`'s `Spain`; clicking into an empty
        // one leaves a caret, which is the 24-pixel bar at columns 166-167 of
        // `bug_736695_2`'s golden.
        //
        // A **gated** combo answers nothing: its edit is read-only and shows
        // neither, which is `CPWL_Edit::GetFocusRect` returning empty for
        // every combo and `SetCaret` forcing the caret invisible on one that
        // is not focused in its own right.
        FieldState::Choice(choice) if choice.config.editable => {
            let edit = choice.edit.as_deref()?;
            let client = ap::field_body::client_rect(&widget.dict, ctx.resolve);
            // The text sits left of the drop button, which is the plate
            // `with_combo_edit` laid it out in — the band has to be measured
            // in the same box or it lands a button's width off.
            let plate = kurbo::Rect::new(
                client.x0,
                client.y0,
                client.x1 - f64::from(DROP_BUTTON_WIDTH),
                client.y1,
            );
            let config = vt::Config {
                plate,
                font_size: font_size(ctx, widget),
                ..vt::Config::default()
            };
            with_font(ctx, widget, |font, _substitute| {
                ops::highlight(edit, &config, &font.metrics, ap::field_body::CARET_WIDTH)
            })
        }
        FieldState::Choice(_) | FieldState::Toggle(_) | FieldState::Button(_) => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pdfrum_object::{Name, NoResolve, Object, PdfString};

    /// A page carrying one `/Tx` widget whose `/DA` names `/Arial`, under a
    /// catalog whose `/AcroForm /DR /Font` declares that name as a bare
    /// non-embedded TrueType — `form_textfield_focused_ltr`'s shape, and the
    /// one that makes the substitution question arise at all.
    fn page_and_catalog() -> (Dict, Dict) {
        let font = Dict::from_pairs([
            (
                pdfrum_object::names::TYPE.clone(),
                Object::Name(Name::from_static(b"Font").clone()),
            ),
            (
                pdfrum_object::names::SUBTYPE.clone(),
                Object::Name(Name::from_static(b"TrueType").clone()),
            ),
            (
                Name::from_static(b"BaseFont").clone(),
                Object::Name(Name::from_static(b"Arial").clone()),
            ),
        ]);
        let catalog = Dict::from_pairs([(
            Name::from_static(b"AcroForm").clone(),
            Object::Dict(Dict::from_pairs([(
                Name::from_static(b"DR").clone(),
                Object::Dict(Dict::from_pairs([(
                    Name::from_static(b"Font").clone(),
                    Object::Dict(Dict::from_pairs([(
                        Name::from_static(b"Arial").clone(),
                        Object::Dict(font),
                    )])),
                )])),
            )])),
        )]);
        let widget = Dict::from_pairs([
            (
                pdfrum_object::names::TYPE.clone(),
                Object::Name(Name::from_static(b"Annot").clone()),
            ),
            (
                pdfrum_object::names::SUBTYPE.clone(),
                Object::Name(Name::from_static(b"Widget").clone()),
            ),
            (
                Name::from_static(b"FT").clone(),
                Object::Name(Name::from_static(b"Tx").clone()),
            ),
            (
                Name::from_static(b"T").clone(),
                Object::Str(PdfString::literal(*b"Text Box")),
            ),
            (
                Name::from_static(b"Rect").clone(),
                Object::Array(
                    [
                        Object::Int(50),
                        Object::Int(40),
                        Object::Int(150),
                        Object::Int(70),
                    ]
                    .into_iter()
                    .collect(),
                ),
            ),
            (
                Name::from_static(b"DA").clone(),
                Object::Str(PdfString::literal(*b"/Arial 12 Tf 0 0 0 rg")),
            ),
        ]);
        let page = Dict::from_pairs([(
            Name::from_static(b"Annots").clone(),
            Object::Array([Object::Dict(widget)].into_iter().collect()),
        )]);
        (page, catalog)
    }

    /// The width closure `with_font` hands the layout **measures a character
    /// the `/DA` font cannot write in the second face**, not in the `/DA`
    /// font's fallback.
    ///
    /// # The defect this pins, which the appearance-stream test cannot
    ///
    /// Reading the emitted stream for `/_B1` catches a regression in the
    /// *encoder* and misses one in the **widths**: a version that puts the
    /// substitute on `LiveInput` and leaves the width closure on the `/DA`
    /// font still writes `/_B1` and still emits the right bytes, while every
    /// advance, caret column and selection band comes out of the wrong table.
    /// That was a real regression: a Hebrew selection band ended at device
    /// column 101 with its glyphs running to 111, ten columns of dark where
    /// the oracle's are white, because Latin advances were measuring a Hebrew
    /// run.
    ///
    /// Layout and encoding share one per-character face index, so a character
    /// written in the second face is measured in it too.
    ///
    /// The numbers are the two faces' own and are asserted as a **relation**
    /// rather than as constants: which face stands in for `/Arial` depends on
    /// the substitution options, and the claim is that the two differ and
    /// that the closure takes the substitute's.
    #[test]
    fn the_width_closure_measures_an_unwritable_character_in_the_second_face() {
        // Bet, which an Ansi `/DA` font cannot write.
        const BET: u32 = 0x05D1;

        let (page, catalog) = page_and_catalog();
        let resolve = NoResolve;
        let form = crate::page::read(0, &page, &catalog, &resolve);
        let widget = form.widgets.first().expect("one /Tx widget");

        let mut build = pdfrum_page::BuildContext::new();
        let fonts = ap::FormFonts::load(&catalog, &resolve, &mut build);
        let ctx = Context {
            page: &form,
            catalog: &catalog,
            resolve: &resolve,
            fonts: &fonts,
            permissions: hit::Permissions::ALL,
        };

        let da = fonts.face(b"Arial").expect("the /DR declares one face");
        let substitute = fonts
            .substitute(pdfrum_font::Charset::Hebrew)
            .expect("the Hebrew second face loads with no font directory at all");
        assert!(
            !ap::font_map::da_font_writes(da, ap::font_map::font_charset(da), BET),
            "the fixture's own font must be unable to write the character, \
             or the substitution never arises"
        );

        let (da_width, substitute_width) = (
            TextFont::char_width(da, BET),
            ap::font_map::substitute_width(substitute.font, BET),
        );
        assert_ne!(
            da_width, substitute_width,
            "the two faces must disagree, or this test cannot tell them apart"
        );

        let measured = with_font(&ctx, widget, |font, _substitute| {
            (
                (font.metrics.width)(BET),
                (font.metrics.width)(u32::from(b'a')),
            )
        })
        .expect("the widget's /DA resolves to a face");

        assert_eq!(
            measured.0, substitute_width,
            "a character the /DA font cannot write is measured in the second face"
        );
        assert_eq!(
            measured.1,
            TextFont::char_width(da, u32::from(b'a')),
            "and one it can is still measured in the /DA font"
        );
    }
}