paperboy 0.6.0

A Rust TUI API tester
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
//! Small shared egui widgets used across the GUI panels.

use eframe::egui::{self, Color32, RichText};

use crate::hurl::KvRow;
use crate::i18n::Strings;

use super::theme::{GuiTheme, method_color};

pub const METHODS: [&str; 8] = [
    "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE",
];

/// Width for the **key** cell of a two-column key/value row so the key grows
/// with the panel instead of staying a fixed sliver next to a filling value.
///
/// A filling value column (the grid's last column, `desired_width(INFINITY)`)
/// otherwise eats *all* free width, so a fixed-width key reads as "tiny key,
/// huge value". Instead we reserve the row's fixed controls (`reserved`:
/// checkbox, remove ✕, column spacing) and split the remaining free width
/// ~40% key / ~60% value — the value still fills whatever is left. The result
/// is clamped so the key never collapses to nothing and never grows past ~half
/// the free space. (The `.min(max_key)` on the lower bound keeps
/// [`f32::clamp`] from panicking when a cramped panel makes `max_key < 90`.)
///
/// Call this **before** building the grid: inside a grid cell `available_width`
/// reports the column width, not the panel width.
pub fn split_key_width(ui: &egui::Ui, reserved: f32) -> f32 {
    let usable = (ui.available_width() - reserved).max(120.0);
    let max_key = usable * 0.5;
    (usable * 0.40).clamp(90.0_f32.min(max_key), max_key)
}

/// Draw `content`'s text fields flat: no outline until the pointer or the
/// keyboard arrives.
///
/// egui frames a `TextEdit` with `widgets.inactive.bg_stroke` when it is idle,
/// `widgets.hovered.bg_stroke` under the pointer and `selection.stroke` while
/// focused. That inactive hairline is shared with buttons, combo boxes and
/// checkboxes — which *should* keep their outline, since an outline is how a
/// control says it is a control — so it is dropped here, scoped to the fields,
/// rather than globally.
///
/// The affordance is not lost, only deferred: the field keeps its wash (see
/// [`GuiTheme::field`]), grows a border under the pointer, and is outlined in
/// the selection colour while it has focus. This is the report editor's chip
/// treatment applied to editable text — read as content, behave as a control.
///
/// Scoped through [`egui::Ui::scope`] because `visuals_mut` edits the `Ui`'s
/// own style: without it the change would leak into every later widget in the
/// same `Ui`, taking the checkbox column of a key/value grid with it.
pub fn flat_fields<R>(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R {
    ui.scope(|ui| {
        ui.visuals_mut().widgets.inactive.bg_stroke = egui::Stroke::NONE;
        content(ui)
    })
    .inner
}

/// One row of a key/value table: its cells side by side, **top**-aligned.
///
/// Not an [`egui::Grid`], which is what this used to be. A grid aligns a cell's
/// contents to the vertical *centre* of its row — and a row's height is only
/// known as its cells are added, so each cell was centred against the tallest
/// of the cells before it and every one sat a fraction lower than the last.
/// A fifth of a pixel is nothing in the model and a whole pixel on screen once
/// a row lands on a fractional y, so a table of them visibly sagged to the
/// right. Every column's width is worked out up front here anyway (see
/// [`kv_widths`]), which was most of what the grid was for.
pub fn table_row<R>(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R {
    ui.horizontal_top(|ui| {
        ui.spacing_mut().item_spacing.x = 8.0;
        content(ui)
    })
    .inner
}

/// The rows of a key/value table, spaced as the grid used to space them.
pub fn table_rows<R>(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R {
    ui.scope(|ui| {
        ui.spacing_mut().item_spacing.y = 4.0;
        content(ui)
    })
    .inner
}

/// Draw a control at the height of the fields around it, by taking its own
/// vertical padding away. A button is otherwise taller than the row it sits in.
pub fn flat_buttons<R>(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R {
    ui.scope(|ui| {
        ui.spacing_mut().button_padding.y = 0.0;
        content(ui)
    })
    .inner
}

/// A key/value row's **key** text field, forced to exactly `key_w` wide.
///
/// The same field as [`wrapping_field`], at a width of its own. It used to be
/// a `TextEdit::singleline` sized with `add_sized` — which laid out a *tenth of
/// a pixel* differently from the wrapping value beside it. That is invisible in
/// the model and a whole pixel on screen whenever the row lands on a fractional
/// y, so the key sat one pixel above the value and the description, and a table
/// of them read as sagging to the right. Two cells that have to line up are
/// better built the same way than adjusted until they agree.
///
/// (The reason neither uses a bare `TextEdit` is width: it clamps
/// `desired_width` to the cell's `available_width`, which stays tiny for a
/// non-last grid column, so the field would render as a ~24px sliver instead of
/// honouring the [`split_key_width`] split.)
pub fn sized_key(
    ui: &mut egui::Ui,
    key_w: f32,
    text: &mut String,
    hint: &str,
    color: Color32,
) -> egui::Response {
    wrapping_field(ui, key_w, text, hint, color)
}

/// The width the [`suggesting_key`] caret button takes out of the key column.
fn suggest_width(ui: &egui::Ui) -> f32 {
    ui.spacing().interact_size.y
}

/// A key field with a caret beside it offering the well-known names for the
/// section — HTTP header names, for instance.
///
/// Deliberately a *visible* button rather than a popup that appears as you
/// type. The terminal UI's Key column offers the same list, and the complaint
/// was that the GUI simply didn't have it; an autocomplete that only shows
/// itself once you have already started typing the name would leave someone who
/// doesn't know the name is on offer exactly where they were.
///
/// It is also not a `ComboBox`, because these lists are shortcuts rather than
/// vocabularies: any header name is legal, and a picker that made the two dozen
/// common ones easy at the cost of making the rest impossible would be a poor
/// trade. The field stays free text; the caret is a way to fill it in.
///
/// The list narrows to what has been typed so far, so the caret stays useful
/// after a few characters instead of making the user scroll past everything.
pub fn suggesting_key(
    ui: &mut egui::Ui,
    key_w: f32,
    text: &mut String,
    hint: &str,
    color: Color32,
    options: &[&'static str],
    empty_label: &str,
) -> egui::Response {
    let caret_w = suggest_width(ui);
    let mut resp = wrapping_field(ui, (key_w - caret_w - 4.0).max(40.0), text, hint, color);
    let row_h = ui.spacing().interact_size.y;
    let mut picked: Option<&'static str> = None;
    flat_buttons(ui, |ui| {
        let button = ui.add_sized(
            [caret_w, row_h],
            egui::Button::new(RichText::new(super::icons::CARET_DOWN).small()),
        );
        egui::Popup::menu(&button).show(|ui| {
            // Narrowed to what has been typed, the same way the terminal UI's
            // Key column narrows its list.
            let typed = text.trim().to_ascii_lowercase();
            let mut any = false;
            egui::ScrollArea::vertical()
                .max_height(240.0)
                .show(ui, |ui| {
                    for opt in options {
                        if !typed.is_empty() && !opt.to_ascii_lowercase().contains(&typed) {
                            continue;
                        }
                        any = true;
                        if ui.button(*opt).clicked() {
                            picked = Some(opt);
                            ui.close();
                        }
                    }
                });
            if !any {
                // "Nothing matches what you typed" is not the same as "there is
                // nothing here", and a silently empty menu reads as broken.
                ui.label(empty_label);
            }
        });
    });
    if let Some(name) = picked {
        *text = name.to_string();
        resp.mark_changed();
    }
    resp
}

/// A value field that shows **all** of its text, wrapping onto as many lines
/// as it needs instead of scrolling the overflow out of sight.
///
/// A single-line field is a viewport onto its value: a bearer token, a long
/// URL or a JSON fragment is a few visible characters and a promise that the
/// rest is in there somewhere, which has to be scrubbed through to read. Since
/// these fields hold the *content* of a request — the thing the screen exists
/// to show — they wrap and the row grows, exactly as the terminal UI does
/// (which edits the Hurl source directly and has always wrapped).
///
/// It is a multiline `TextEdit` for the wrapping, but not a multiline *field*:
/// `return_key(None)` means Enter never inserts a newline, so a header value
/// cannot be broken across lines by a stray keystroke into something that
/// would not survive being written out as Hurl.
pub fn wrapping_field(
    ui: &mut egui::Ui,
    width: f32,
    text: &mut String,
    hint: &str,
    color: Color32,
) -> egui::Response {
    wrapping_field_font(ui, width, text, hint, color, egui::TextStyle::Body)
}

/// A `TextEdit`'s horizontal margin: the field the user sees is this wider than
/// the `desired_width` it is asked for.
const TEXT_EDIT_MARGIN: f32 = 8.0;

/// How many lines a wrapping field grows to before it starts scrolling instead.
///
/// Wrapping exists so a token or a URL can be *read* rather than scrubbed
/// through — but an environment variable holding a JWT is a hundred lines of
/// base64, and a field that tall swallows the panel it lives in, pushing every
/// other variable off the screen. Past this many lines the field stops growing
/// and scrolls within itself: the whole value is still there to scroll or
/// select through, and the rows around it stay where they are.
const FIELD_MAX_LINES: f32 = 6.0;

/// [`wrapping_field`] in a chosen text style — the URL is monospaced, so that
/// the punctuation a URL is mostly made of lines up.
pub fn wrapping_field_font(
    ui: &mut egui::Ui,
    width: f32,
    text: &mut String,
    hint: &str,
    color: Color32,
    font: egui::TextStyle,
) -> egui::Response {
    wrapping_field_font_id(ui, width, text, hint, color, font, None)
}

/// [`wrapping_field_font`] with an explicit widget id.
///
/// A `TextEdit` with no id of its own is identified by where it lands in the
/// layout — which is fine until a *table* of them shuffles: delete a row and
/// the one below slides into its id, inheriting its caret and its undo history
/// (egui keys both by widget id). Rows the user can add, delete and reorder —
/// the `[Gen]` block — pass a stable per-row, per-request id here so a cell's
/// history follows the row, not the slot. Everything else passes `None` and
/// keeps the positional id it always had.
pub fn wrapping_field_font_id(
    ui: &mut egui::Ui,
    width: f32,
    text: &mut String,
    hint: &str,
    color: Color32,
    font: egui::TextStyle,
    id: Option<egui::Id>,
) -> egui::Response {
    // A `TextEdit`'s `desired_width` is the width of the *text*: its margin is
    // added on top. Asking for the caller's width therefore claimed a few
    // pixels more than the column reserved, so a filled table laid its columns
    // out slightly wider than an empty one and the headers stopped lining up
    // with the fields beneath them.
    let text_w = (width - TEXT_EDIT_MARGIN).max(16.0);
    // How tall this value wants to be, measured the way the `TextEdit` will lay
    // it out (same font, same wrap width), and the tallest it is allowed to get
    // (see `FIELD_MAX_LINES`). Measuring up front matters: a field that simply
    // *asked* for the maximum would make its row that tall whatever it holds,
    // which in a horizontal row (the method picker, the URL, Send) pushed the
    // URL onto a line of its own.
    let font_id = font.resolve(ui.style());
    let max_h = ui.ctx().fonts_mut(|f| f.row_height(&font_id)) * FIELD_MAX_LINES + TEXT_EDIT_MARGIN;
    let wanted_h = ui
        .ctx()
        .fonts_mut(|f| f.layout(text.clone(), font_id, color, text_w).size().y)
        + TEXT_EDIT_MARGIN;
    let field = |ui: &mut egui::Ui, text: &mut String| {
        let mut edit = egui::TextEdit::multiline(text)
            .hint_text(hint)
            .text_color(color)
            .desired_width(text_w)
            .desired_rows(1)
            .return_key(None)
            .font(font.clone());
        if let Some(id) = id {
            edit = edit.id(id);
        }
        ui.add(edit)
    };
    flat_fields(ui, |ui| {
        // A value that fits is drawn exactly as it always was: no viewport, no
        // reserved height, so the fields that hold one line — which is nearly
        // all of them — lay out to the pixel as before.
        if wanted_h <= max_h {
            // Allocated at the width the caller worked out, with the height
            // left to the content — `add_sized` would pin the height and undo
            // the growth this exists for.
            return ui
                .allocate_ui(egui::vec2(width, ui.spacing().interact_size.y), |ui| {
                    ui.set_width(width);
                    field(ui, text)
                })
                .inner;
        }
        // Only an over-long value gets the capped, scrolling viewport.
        ui.allocate_ui(egui::vec2(width, max_h), |ui| {
            ui.set_width(width);
            ui.set_height(max_h);
            egui::ScrollArea::vertical()
                .max_height(max_h)
                .auto_shrink([false, false])
                .show(ui, |ui| field(ui, text))
                .inner
        })
        .inner
    })
}

/// [`super::icons::RUNNING`], turning.
///
/// The icon is Phosphor's circle-notch — a ring with a bite out of it, the
/// shape every spinner is drawn from. Standing still it reads as a broken ring
/// rather than as work in progress, and the counter beside it in the report
/// toolbar only moves when a request *finishes*, so a run waiting on one slow
/// endpoint looked stopped at exactly the moment the user wants reassurance.
///
/// **Painted rather than spun as text**, for the same family of reasons as
/// [`status_dot`]. Rotating the real glyph with a `TextShape` looks right in a
/// screenshot but jostles in motion: `epaint` rounds a galley's position to a
/// whole physical pixel before applying the angle (`Tessellator`'s
/// `round_text_to_pixels`, on by default, and not settable per shape). A glyph
/// spun about its own middle has to walk its top-left corner around a circle
/// to stay put, and that circle gets snapped — so the icon hops a pixel at a
/// time instead of turning. A stroked path has no such rounding (only
/// *axis-aligned* line segments are snapped, and an arc has none), so it turns
/// smoothly at sub-pixel precision.
///
/// The arc is Phosphor Light's own geometry, measured off the font so that it
/// sits among the still icons as if it were one of them: the ring's centreline
/// is at [`NOTCH_RADIUS`] of the em, its stroke is [`NOTCH_STROKE`], and the
/// notch spans [`NOTCH_GAP`] radians at the top. The footprint reserved is
/// whatever a label of the real glyph would take, which matters because every
/// Phosphor glyph is exactly one em wide — that is what stops a request row or
/// a results-grid row from shifting sideways as its marker goes scheduled →
/// running → finished. (`egui::Spinner` would allocate a square of its own
/// chosen size instead, and jog the column on every state change.)
///
/// Pumps its own repaints, the way `egui::Spinner` does. An animation that
/// relies on its caller for frames is one refactor away from freezing in
/// place, and every site that draws this is by definition busy.
pub fn spinning_icon(ui: &mut egui::Ui, color: Color32) -> egui::Response {
    /// Radians per second — a shade under a turn and a half, fast enough to
    /// read as motion at a glance without becoming a distraction on a grid
    /// where several rows may be turning at once.
    const SPEED: f32 = 5.0;
    /// How finely the arc is chopped. At body size the ring is only a few
    /// pixels across, so this is already far more than the curve needs; it is
    /// cheap, and it keeps the arc smooth if the icon is ever drawn large.
    const SEGMENTS: usize = 48;

    let font = egui::TextStyle::Body.resolve(ui.style());
    let em = font.size;
    let galley = ui
        .painter()
        .layout_no_wrap(super::icons::RUNNING.to_owned(), font, color);
    // Where the glyph's ink sits inside the space it reserves — the ring is
    // centred in its em box horizontally but not vertically, so anchoring on
    // the reserved rect's middle would float the spinner off the line the
    // still icons sit on.
    let ink = galley
        .rows
        .first()
        .map(|r| r.visuals.mesh_bounds.translate(r.pos.to_vec2()))
        .unwrap_or(galley.rect);
    let (rect, response) = ui.allocate_exact_size(galley.size(), egui::Sense::hover());
    if ui.is_rect_visible(rect) {
        let centre = rect.min + ink.center().to_vec2();
        let radius = em * NOTCH_RADIUS;
        let from = (ui.input(|i| i.time) as f32 * SPEED) % std::f32::consts::TAU + NOTCH_GAP / 2.0;
        let sweep = std::f32::consts::TAU - NOTCH_GAP;
        let arc = (0..=SEGMENTS)
            .map(|i| {
                let t = from + sweep * (i as f32 / SEGMENTS as f32);
                centre + radius * egui::vec2(t.cos(), t.sin())
            })
            .collect();
        ui.painter().add(egui::Shape::line(
            arc,
            egui::Stroke::new(em * NOTCH_STROKE, color),
        ));
        ui.ctx().request_repaint();
    }
    response
}

/// Radius of the circle-notch ring's centreline, as a fraction of the em.
///
/// Measured off Phosphor Light's `CIRCLE_NOTCH` outline rather than guessed:
/// fitting a circle to it gives inner and outer edges at 365.6 and 410.9 of
/// the font's 1024 units, centred 0.5 em across.
const NOTCH_RADIUS: f32 = 388.3 / 1024.0;

/// Stroke width of the ring, likewise as a fraction of the em (45.3/1024).
const NOTCH_STROKE: f32 = 45.3 / 1024.0;

/// The notch: how much of the ring is missing, in radians. The glyph's gap
/// spans 69.2°–110.8°, i.e. 41.6° centred on straight up.
const NOTCH_GAP: f32 = 41.6 * std::f32::consts::PI / 180.0;

/// A small filled circle used as a status marker — the GUI's counterpart to
/// the terminal UI's `●`.
///
/// Painted rather than typed, because the obvious `\u{25cf}` renders as a tofu
/// box here. Of the fonts egui bundles, only **Hack** carries U+25CF, and Hack
/// is in the *monospace* family — the proportional family every label uses is
/// Ubuntu-Light + the two emoji fonts, none of which has the glyph, and egui
/// does not fall back from proportional into monospace. Phosphor (which covers
/// every other icon here, see [`super::icons`]) has no replacement either: in
/// the Light weight the app registers, its `DOT` is a speck 8% of an em across
/// and `CIRCLE` is a thin ring. A disc is a centre and a radius, so drawing it
/// needs no font at all — and it can then be sized to the surrounding text.
pub fn status_dot(ui: &mut egui::Ui, color: Color32) -> egui::Response {
    // Roughly the ink of a `●` at the same text size, and tied to the text so
    // it tracks the app's font scaling rather than pinning to a fixed pixel.
    let d = (ui.text_style_height(&egui::TextStyle::Body) * 0.42).round();
    // A horizontal layout centres a short item vertically, so this sits on the
    // midline of the label beside it.
    let (rect, response) = ui.allocate_exact_size(egui::vec2(d, d), egui::Sense::hover());
    ui.painter().circle_filled(rect.center(), d / 2.0, color);
    response
}

/// A selectable label whose footprint never changes between the
/// unselected, hovered and selected states.
///
/// `egui`'s built-in [`egui::Ui::selectable_label`] omits the button frame
/// while inactive and only adds it on hover/selection, so the extra padding +
/// stroke make the widget (and everything after it) jump by a pixel or two the
/// moment the pointer touches it. We force `frame_when_inactive(true)` so the
/// frame's space is always reserved and hover/selection only *recolour* it in
/// place — matching the terminal UI, where selection never shifts the layout.
pub fn selectable<'a>(
    ui: &mut egui::Ui,
    selected: bool,
    atoms: impl egui::IntoAtoms<'a>,
) -> egui::Response {
    ui.add(egui::Button::selectable(selected, atoms).frame_when_inactive(true))
}

/// [`selectable`] for a row of a list or tree: no frame unless it is the
/// selected one.
///
/// A segmented control (section tabs, the Raw body / Form fields switch) wants
/// every option framed, because the frames are what make it read as one control
/// with several settings. A list is the opposite: framing every row paints a
/// grey chip behind every name, and a list of chips reads as a list of disabled
/// things — which is exactly how the request tree looked once the theme gave
/// the raised surface a colour of its own to be seen in.
///
/// The border is drawn *inside* the row rather than around it, so no row ever
/// changes size. `Button::selectable` drops the frame entirely while the row
/// is neither selected nor hovered, and egui compensates a frame's stroke
/// inside the frame's own margin (`inner_margin = button_padding -
/// stroke.width`, with the stroke drawn back around it) — so a frameless row
/// comes out `2 * stroke.width` narrower and shorter than the same row
/// selected, and picking a request grew its name and nudged the rows after it.
/// Reserving the frame in every state instead would fix the movement by
/// padding *every* row out to the selected one's size, which just spaces the
/// whole list out; the button therefore keeps the compact, frameless geometry
/// (its own stroke is suppressed so the framed states can't claim the extra
/// pixels either) and the border is painted over the edge of the row we
/// already have.
pub fn selectable_row<'a>(
    ui: &mut egui::Ui,
    selected: bool,
    atoms: impl egui::IntoAtoms<'a>,
) -> egui::Response {
    // The state is read the way `Button` itself reads it (last frame's response
    // for the id this widget is about to take), so hover still lights the row
    // up rather than being flattened along with the resting state.
    let state = ui
        .ctx()
        .read_response(ui.next_auto_id())
        .map(|r| r.widget_state())
        .unwrap_or_default();
    // Exactly when egui would have framed the row: hovered/held, or selected.
    let framed = selected || state != egui::widget_style::WidgetState::Inactive;
    let visuals = *ui.visuals().widgets.state(state);
    let response = ui.add(egui::Button::selectable(selected, atoms).stroke(egui::Stroke::NONE));
    if framed && visuals.bg_stroke.width > 0.0 {
        ui.painter().rect_stroke(
            response.rect,
            visuals.corner_radius,
            visuals.bg_stroke,
            egui::StrokeKind::Inside,
        );
    }
    response
}

/// A panel header: a bold, **truncating** title on the left and right-aligned
/// action buttons that stay fully visible.
///
/// The title yields space to the buttons and truncates rather than growing, so
/// the header never demands more width than the panel's `min_size`. That
/// matters because the left column's headers sit outside its scroll area: if
/// one forced the content wider than a dragged-narrow panel, `egui` would clip
/// the content to the drag width while still placing the neighbouring panel at
/// the wider content edge — leaving an unpainted strip during the drag.
pub fn panel_header(
    ui: &mut egui::Ui,
    theme: &GuiTheme,
    title: impl Into<String>,
    add_buttons: impl FnOnce(&mut egui::Ui),
) {
    let title = title.into();
    ui.horizontal(|ui| {
        // Buttons are laid out from the right first (so they always fit), then
        // the title fills whatever space is left and truncates within it.
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            add_buttons(ui);
            ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
                ui.add(
                    egui::Label::new(RichText::new(title).strong().color(theme.text)).truncate(),
                );
            });
        });
    });
}

/// Vertical gap between two tree rows, in pixels.
///
/// The app-wide `item_spacing` (see `theme.rs`) is the gap between *controls*,
/// and a tree is not a stack of controls: a row is one line of a list, and the
/// air meant to keep two buttons apart reads as a list that has been spaced
/// out. Rows are separated by their own, tighter rhythm so a folder of
/// requests can be scanned as one block — and so more of it fits on screen,
/// which is most of the point of a tree.
pub const TREE_ROW_SPACING: f32 = 3.0;

/// Padding above and below a tree row's label, in pixels.
///
/// Same argument as [`TREE_ROW_SPACING`], applied to the row itself: the
/// app-wide `button_padding` is what makes a *button* comfortable to hit, and
/// a row of a list doesn't need that much air around its one line of text.
/// Left at 2px rather than nothing so the selection border doesn't sit on the
/// letters, and egui's `interact_size` still keeps the row a sane click
/// target.
pub const TREE_ROW_PADDING: f32 = 2.0;

/// Put a `Ui` on the trees' denser rhythm: every list of rows in the app (the
/// request tree, the workspace tree, the environment list) is spaced the same
/// way, so the panels read as one thing rather than three lists that happen to
/// sit above each other.
pub fn tree_rhythm(ui: &mut egui::Ui) {
    let spacing = ui.spacing_mut();
    spacing.item_spacing.y = TREE_ROW_SPACING;
    spacing.button_padding.y = TREE_ROW_PADDING;
}

/// A collapsible tree row whose header **truncates** to the available width and
/// toggles when clicked anywhere along the row. Returns the header response.
///
/// egui's built-in [`egui::CollapsingHeader`] hardcodes `TextWrapMode::Extend`
/// for its header galley, so a long folder / environment name reports a content
/// width wider than the panel. While the splitter is dragged narrower egui then
/// clips the content to the drag width but still places the neighbouring panel
/// at the wider content edge — the "black strip" (see [`panel_header`]). We
/// build the header by hand from a [`egui::collapsing_header::CollapsingState`]
/// so the label can truncate, with the same explicit Phosphor carets the
/// workspace tree uses and click-anywhere-to-toggle behaviour. Reused by the
/// request tree, the environment list and (later) the workspace tree.
pub fn tree_header<R>(
    ui: &mut egui::Ui,
    id_salt: impl std::hash::Hash + std::fmt::Debug,
    default_open: bool,
    label: RichText,
    add_body: impl FnOnce(&mut egui::Ui) -> R,
) -> egui::Response {
    tree_header_marked(ui, id_salt, default_open, false, label, None, add_body)
}

/// [`tree_header`] with an optional highlight colour painted as a full-width
/// band behind the row and a matching bar down its left edge.
///
/// Colouring the *text* alone (which is all this used to do for the active
/// environment) is easy to miss in a list of similar rows — the terminal UI
/// gets away with less because a terminal list is denser. A filled band reads
/// at a glance from anywhere in the panel.
pub fn tree_header_marked<R>(
    ui: &mut egui::Ui,
    id_salt: impl std::hash::Hash + std::fmt::Debug,
    default_open: bool,
    force_open: bool,
    label: RichText,
    highlight: Option<egui::Color32>,
    add_body: impl FnOnce(&mut egui::Ui) -> R,
) -> egui::Response {
    // The caller supplies a namespaced, model-derived salt; do not mix in the
    // current Ui id, because filtered trees can move the same model row between
    // containers and should still keep its own expansion state.
    let id = egui::Id::new(id_salt);
    let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(
        ui.ctx(),
        id,
        default_open,
    );
    // `force_open` is how something *outside* this row (opening an environment
    // from the workspace tree, say) says "reveal this one". It only ever opens:
    // a caller asking to reveal a row the user has already opened must not
    // toggle it shut.
    if force_open && !state.is_open() {
        state.set_open(true);
    }
    let open = state.is_open();

    // The band has to be painted *under* the row's contents, so reserve a slot
    // in the paint order now and fill it once the row's rect is known. The
    // hover wash shares the slot: a tree row is a click target, and without it
    // the environment list was the one tree in the app that gave no sign the
    // pointer was over a row at all.
    let band = ui.painter().add(egui::Shape::Noop);

    let header = ui
        .horizontal(|ui| {
            // Reserve the full row width so short names still toggle across the
            // whole row, then draw the triangle + a truncating label.
            ui.set_min_width(ui.available_width());
            let caret = if open {
                super::icons::CARET_DOWN
            } else {
                super::icons::CARET_RIGHT
            };
            // egui's built-in painted triangle is a tiny vector shape, so the
            // closed state could read as "no affordance" beside the Phosphor
            // glyphs used by the workspace tree. Text carets keep both trees
            // visually consistent and use the icon font PaperBoy installs.
            ui.add_sized(
                egui::vec2(ui.spacing().icon_width, ui.spacing().interact_size.y),
                egui::Label::new(caret).selectable(false),
            );
            ui.add(egui::Label::new(label).truncate().selectable(false));
        })
        .response
        .interact(egui::Sense::click());

    let rect = header.rect.expand2(egui::vec2(0.0, 2.0));
    let mut shapes = Vec::new();
    if header.hovered() {
        let visuals = ui.visuals().widgets.hovered;
        shapes.push(egui::Shape::rect_filled(
            rect,
            visuals.corner_radius,
            visuals.weak_bg_fill,
        ));
    }
    if let Some(color) = highlight {
        shapes.push(egui::Shape::rect_filled(
            rect,
            3.0,
            color.gamma_multiply(0.22),
        ));
        // A solid bar on the leading edge, so the row still reads as marked on
        // a theme whose background leaves the translucent band very faint.
        shapes.push(egui::Shape::rect_filled(
            egui::Rect::from_min_size(rect.min, egui::vec2(3.0, rect.height())),
            1.0,
            color,
        ));
    }
    if !shapes.is_empty() {
        ui.painter().set(band, egui::Shape::Vec(shapes));
    }
    if header.clicked() {
        state.toggle(ui);
    }
    state.show_body_indented(&header, ui, add_body);
    header
}

/// A coloured HTTP-method badge, matching the terminal UI's method colours.
/// `theme` supplies the colour for any verb the shared table doesn't name.
pub fn method_badge(ui: &mut egui::Ui, theme: &GuiTheme, method: &str) {
    let col = method_color(method, theme.dim);
    ui.label(RichText::new(method).strong().monospace().color(col));
}

/// A method picker combo box. Returns true if the method changed.
pub fn method_combo(
    ui: &mut egui::Ui,
    theme: &GuiTheme,
    id: impl std::hash::Hash + std::fmt::Debug,
    method: &mut String,
) -> bool {
    let mut changed = false;
    let col = method_color(method, theme.dim);
    egui::ComboBox::from_id_salt(id)
        .selected_text(RichText::new(method.clone()).strong().color(col))
        .width(96.0)
        .show_ui(ui, |ui| {
            for m in METHODS {
                if selectable(
                    ui,
                    method == m,
                    RichText::new(m).color(method_color(m, theme.dim)),
                )
                .clicked()
                {
                    *method = m.to_string();
                    changed = true;
                }
            }
        });
    changed
}

/// One column title in a key/value table — dim and bold, so it reads as a
/// label for the column rather than as another editable row.
fn column_header(ui: &mut egui::Ui, theme: &GuiTheme, text: &str) {
    ui.label(RichText::new(text).strong().color(theme.dim));
}

/// A column title that *allocates* `w`, exactly as the cell below it does.
///
/// A bare label only claims the width of its own text, so on an empty table the
/// grid's columns shrank to fit the words "Header Value Description" and the
/// titles bunched together — then sprang apart the moment a row was added and
/// the real fields set the column widths. Sizing the titles from the same
/// numbers as the fields keeps every label still.
fn sized_header(ui: &mut egui::Ui, theme: &GuiTheme, text: &str, w: f32) {
    let h = ui.spacing().interact_size.y;
    ui.allocate_ui_with_layout(
        egui::vec2(w, h),
        egui::Layout::left_to_right(egui::Align::Center),
        |ui| {
            ui.set_min_width(w);
            column_header(ui, theme, text);
        },
    );
}

/// The width the remove ✕ column claims.
///
/// Its *natural* size — the glyph plus the button's own padding — is wider
/// than the `interact_size` a row is otherwise built from, so reserving the
/// row height for it left the filled table a few pixels wider than the header
/// that has to line up with it. Sizing the button to this reserves exactly
/// what it takes.
pub fn remove_width(ui: &egui::Ui) -> f32 {
    ui.spacing().interact_size.y + 2.0 * ui.spacing().button_padding.x
}

/// The width a text button will claim, so a row can reserve it before the
/// button is added (the value field to its left has to be sized first).
pub fn button_width(ui: &egui::Ui, text: &str) -> f32 {
    let font = egui::TextStyle::Button.resolve(ui.style());
    let w = ui
        .painter()
        .layout_no_wrap(text.to_owned(), font, Color32::PLACEHOLDER)
        .size()
        .x;
    w + 2.0 * ui.spacing().button_padding.x
}

/// The four column widths of a [`kv_editor`] row: tick, key, value, note.
///
/// The description used to be whatever the key and value left over — and they
/// claimed 40% + 60% of the row between them, so it collapsed to a sliver you
/// couldn't read a word in. All three text columns are now shares of the same
/// free width, so a note has room without starving the key or the value.
///
/// Every width is returned (rather than letting the last column fill) because
/// the header row has to allocate exactly what the rows below it do; see
/// [`sized_header`].
fn kv_widths(ui: &egui::Ui) -> (f32, f32, f32, f32) {
    let check = ui.spacing().interact_size.y + 4.0;
    // The tick, the remove ✕ and the four gaps between the five columns are
    // fixed furniture; only what's left is shared out.
    let fixed = check + remove_width(ui) + 4.0 * 8.0;
    let free = (ui.available_width() - fixed).max(240.0);
    let key = free * 0.28;
    let val = free * 0.38;
    (check, key, val, free - key - val)
}

/// An editable table of [`KvRow`]s (headers, query params, cookies, options).
/// Returns true if anything changed. Adds a trailing "add row" button.
///
/// `extract_row` receives the index of a row whose value was right-clicked and
/// sent to "Extract to parameter…". The table only reports it: which request
/// field that row *is* is the caller's business, and the entry it belongs to is
/// borrowed here, so the write-back happens back where the section was drawn.
#[allow(clippy::too_many_arguments)]
pub fn kv_editor(
    ui: &mut egui::Ui,
    theme: &GuiTheme,
    s: &Strings,
    id: impl std::hash::Hash + std::fmt::Debug,
    rows: &mut Vec<KvRow>,
    key_hint: &str,
    val_hint: &str,
    key_label: &str,
    val_label: &str,
    extract_label: &str,
    extract_row: &mut Option<usize>,
    key_options: &[&'static str],
) -> bool {
    let mut changed = false;
    let mut remove: Option<usize> = None;
    // The remove ✕ is a column of its own rather than being tucked inside the
    // description cell. Sharing a cell meant the note was positioned relative
    // to a *button*, and a button is taller than a field, so the note settled
    // a pixel or two below the key and value it belongs to — every row sagged
    // towards its right-hand edge. As its own cell each field starts on the
    // same line, and the ✕ still sits immediately right of the note.
    let (check_w, key_w, val_w, desc_w) = kv_widths(ui);
    let row_h = ui.spacing().interact_size.y;
    ui.push_id(id, |ui| {
        table_rows(ui, |ui| {
            // Column titles, as in the terminal UI: without them a bare table of
            // text boxes gives no clue that the tick is "send this row" rather
            // than "select".
            table_row(ui, |ui| {
                // The Phosphor tick, not a bare `\u{2713}`: egui's bundled fonts
                // have no glyph for it, so the literal rendered as a tofu box.
                sized_header(ui, theme, super::icons::PASS, check_w);
                sized_header(ui, theme, key_label, key_w);
                sized_header(ui, theme, val_label, val_w);
                sized_header(ui, theme, s.hdr_description, desc_w);
                // The ✕ column has no title — the button says what it does.
                ui.allocate_space(egui::vec2(remove_width(ui), 1.0));
            });
            for i in 0..rows.len() {
                table_row(ui, |ui| {
                    if ui
                        .add_sized(
                            [check_w, row_h],
                            egui::Checkbox::without_text(&mut rows[i].enabled),
                        )
                        .changed()
                    {
                        changed = true;
                    }
                    // A disabled row (checkbox unticked) isn't sent, so grey its
                    // key/value out to read as inactive — matching the terminal UI.
                    // A name or value the Hurl row grammar can't carry overrides
                    // that: the serializer has to comment such a row out to keep
                    // the file loadable at all (see `key_problem` and
                    // `value_problem`), so it is flagged in the error colour
                    // where it is typed rather than silently dropping off the
                    // wire later.
                    let bad_key = crate::hurl::key_problem(&rows[i].key).is_some()
                        && !rows[i].key.trim().is_empty();
                    let bad_value = crate::hurl::value_problem(&rows[i].value).is_some();
                    let row_color = if bad_key || bad_value {
                        theme.err
                    } else if rows[i].enabled {
                        theme.text
                    } else {
                        theme.dim
                    };
                    // Sections with a well-known vocabulary (header and cookie
                    // names) get the caret; a query parameter's name is the
                    // API's business and there is nothing to suggest.
                    let k = if key_options.is_empty() {
                        sized_key(ui, key_w, &mut rows[i].key, key_hint, row_color)
                    } else {
                        suggesting_key(
                            ui,
                            key_w,
                            &mut rows[i].key,
                            key_hint,
                            row_color,
                            key_options,
                            s.gui_suggest_no_matches,
                        )
                    };
                    if k.changed() {
                        changed = true;
                    }
                    if bad_key {
                        k.on_hover_text(s.gui_bad_key_warning);
                    }
                    // The value is the one cell whose content is the request
                    // itself, so it is the one that wraps rather than truncates.
                    let v = wrapping_field(ui, val_w, &mut rows[i].value, val_hint, row_color);
                    if v.changed() {
                        changed = true;
                    }
                    if bad_value {
                        v.clone().on_hover_text(s.gui_bad_value_warning);
                    }
                    if !rows[i].value.trim().is_empty() {
                        v.context_menu(|ui| {
                            if ui.button(extract_label).clicked() {
                                *extract_row = Some(i);
                                ui.close();
                            }
                        });
                    }
                    // The description is a note for whoever reads the file later,
                    // not part of the request, so it is always dim — even on an
                    // enabled row it shouldn't compete with the value beside it.
                    let d = wrapping_field(
                        ui,
                        desc_w,
                        &mut rows[i].desc,
                        s.gui_hint_description,
                        theme.dim,
                    );
                    if d.changed() {
                        changed = true;
                    }
                    // Sized, not free-growing: the header row has to reserve
                    // exactly what this column claims (see `kv_widths`), or an
                    // empty table and a filled one lay their columns out
                    // differently and everything shifts when the first row lands.
                    // Padded to the height of the fields rather than its own: a
                    // button's vertical padding makes it taller than the row it
                    // belongs to, so it hung two pixels below the fields and drew
                    // the eye down at the end of every row.
                    let x_w = remove_width(ui);
                    let hit = flat_buttons(ui, |ui| {
                        ui.add_sized(
                            [x_w, row_h],
                            egui::Button::new(RichText::new(super::icons::CLOSE).color(theme.err)),
                        )
                    });
                    if hit.on_hover_text(s.gui_remove).clicked() {
                        remove = Some(i);
                    }
                });
            }
        });
    });
    if let Some(i) = remove {
        rows.remove(i);
        changed = true;
    }
    if ui.button(s.gui_add).clicked() {
        rows.push(KvRow::toggled(String::new(), String::new(), true));
        changed = true;
    }
    changed
}

/// An editable table of `(name, value)` pairs without an enabled flag
/// (captures, reports). Returns true if anything changed.
/// A per-row anchor for a `[Gen]` cell's widget id, taken from its *neighbour*
/// cell's text (the name cell anchors on the expression and vice versa) so that
/// typing in a cell never changes that cell's own id. Whitespace-only text
/// doesn't count as content — an empty neighbour falls back to the row index so
/// two blank rows don't hash to the same id and clash.
///
/// `dup` is how many rows above this one have the same neighbour text, and
/// disambiguates the case the text alone can't: two rows computing `uuid` under
/// different names have the same expression, so their *name* cells would
/// otherwise share an id — egui would paint a duplicate-id warning over the
/// table and the two cells would share one caret and one undo history.
fn neighbour_key(neighbour: &str, i: usize, dup: usize) -> egui::Id {
    if neighbour.trim().is_empty() {
        egui::Id::new(("row", i))
    } else {
        egui::Id::new(("neighbour", neighbour, dup))
    }
}

/// The `# [Gen]` table: `Name | Expression`, with a function menu on each row
/// and, under it, everything wrong with the block that can be known without
/// sending anything.
///
/// A near-copy of [`pair_editor`] rather than a flag on it: the extra column
/// and the fault list are most of what this draws, and the expression column is
/// monospaced because it is code.
pub fn computed_editor(
    ui: &mut egui::Ui,
    theme: &GuiTheme,
    s: &Strings,
    // A stable identity for the request whose block this is. The per-cell ids
    // below hang off it so a `[Gen]` cell's caret and undo history (which egui
    // keys by widget id) belong to *this request's* row rather than to the
    // slot: without it, switching to another request in the list handed its
    // first row the previous request's undo stack, and Ctrl+Z wrote one
    // request's expression into the other.
    req: egui::Id,
    rows: &mut Vec<(String, String)>,
    // The names an expression here may read: the environment's variables and
    // the collection's captures. The rows above each one are added to these as
    // the table is drawn -- a row can build on the ones before it, and which
    // those are depends on where you are in the table.
    vars: &[String],
) -> bool {
    let mut changed = false;
    let mut remove: Option<usize> = None;
    let key_w = split_key_width(ui, 42.0);
    let x_w = remove_width(ui);
    let row_h = ui.spacing().interact_size.y;
    ui.push_id(req.with("computed"), |ui| {
        table_rows(ui, |ui| {
            table_row(ui, |ui| {
                sized_header(ui, theme, s.generated_name, key_w);
                column_header(ui, theme, s.generated_expr);
            });
            for i in 0..rows.len() {
                table_row(ui, |ui| {
                    // Per-row, per-request cell ids that follow the *row*, not
                    // its position, so a row keeps its caret and undo history
                    // when one above it is deleted and it slides up a slot.
                    // Each cell is keyed by the *other* cell's text — the name
                    // cell by the expression, the expression cell by the name —
                    // so typing in one never moves the id of the cell being
                    // typed in (which would drop focus every keystroke), while
                    // still giving the row a content identity that survives a
                    // deletion. An empty neighbour falls back to the row index
                    // so two blank rows don't collide.
                    let name_dup = rows[..i]
                        .iter()
                        .filter(|(_, e)| e.trim() == rows[i].1.trim())
                        .count();
                    let expr_dup = rows[..i]
                        .iter()
                        .filter(|(n, _)| n.trim() == rows[i].0.trim())
                        .count();
                    let name_anchor = neighbour_key(&rows[i].1, i, name_dup);
                    let expr_anchor = neighbour_key(&rows[i].0, i, expr_dup);
                    let name_id = req.with(("computed-name", name_anchor));
                    let expr_id = req.with(("computed-expr", expr_anchor));
                    // A name that isn't a variable Hurl will resolve, or a name
                    // left blank beside a filled-in expression, is a row that
                    // vanishes on save (the block only keeps readable rows), so
                    // flag it in the error colour where it is typed rather than
                    // letting it disappear silently.
                    let name = rows[i].0.trim();
                    let bad_name = (!name.is_empty() && !crate::hurl::is_variable_name(name))
                        || (name.is_empty() && !rows[i].1.trim().is_empty());
                    let name_color = if bad_name { theme.err } else { theme.text };
                    let k = wrapping_field_font_id(
                        ui,
                        key_w,
                        &mut rows[i].0,
                        s.generated_name,
                        name_color,
                        egui::TextStyle::Body,
                        Some(name_id),
                    );
                    if k.changed() {
                        changed = true;
                    }
                    if bad_name {
                        k.on_hover_text(s.gui_generated_bad_name);
                    }
                    // The delete ✕ is reserved before the field is sized: an
                    // infinite-width field laid out left to right claims the
                    // whole row and shoves it off the edge, and there is no
                    // horizontal scrollbar to get it back.
                    let val_w =
                        (ui.available_width() - x_w - ui.spacing().item_spacing.x).max(40.0);
                    // The completion list for what is being typed, worked out
                    // *before* the field is drawn: its keys (↑↓, Enter, Esc,
                    // Ctrl+Space) have to be taken out of the queue before the
                    // `TextEdit` gets them, or Up and Down move the caret
                    // instead of the selection.
                    //
                    // There is no button beside the field any more. A menu of
                    // thirty-five functions was the wrong shape for the job --
                    // you rarely want to read the whole list, you want the one
                    // whose first three letters you can remember -- and
                    // whatever it was labelled (`Function…`, `ƒ Insert…`, a
                    // bare `ƒ`) it read as a command that would overwrite the
                    // field. The field itself now offers everything the button
                    // did: type to filter it, or ask for the lot with
                    // Ctrl+Space or an empty cell.
                    // The rows above this one are variables it may read; the
                    // rows below are not (a block is evaluated top to bottom,
                    // and `check` calls a backward reference an error), so
                    // offering them would be offering a mistake.
                    let mut in_scope: Vec<String> = vars.to_vec();
                    in_scope.extend(
                        rows[..i]
                            .iter()
                            .map(|(n, _)| n.trim())
                            .filter(|n| !n.is_empty())
                            .map(str::to_string),
                    );
                    let mut sugg = suggest_state(ui, s, expr_id, &rows[i].1, &in_scope);
                    if sugg.take_keys(ui) {
                        changed = true;
                    }
                    sugg.apply(ui.ctx(), expr_id, &mut rows[i].1);
                    let field = wrapping_field_font_id(
                        ui,
                        val_w,
                        &mut rows[i].1,
                        s.gui_generated_expr_hint,
                        theme.text,
                        egui::TextStyle::Monospace,
                        Some(expr_id),
                    );
                    if field.changed() {
                        changed = true;
                    }
                    if sugg.show(ui, theme, &field, expr_id, &mut rows[i].1) {
                        changed = true;
                    }
                    let hit = flat_buttons(ui, |ui| {
                        ui.add_sized(
                            [x_w, row_h],
                            egui::Button::new(RichText::new(super::icons::CLOSE).color(theme.err)),
                        )
                    });
                    if hit.clicked() {
                        remove = Some(i);
                    }
                });
            }
        });
    });
    if let Some(i) = remove {
        rows.remove(i);
        changed = true;
    }
    if ui.button(s.gui_add).clicked() {
        rows.push((String::new(), String::new()));
        changed = true;
    }
    // Said here rather than at send time: a mistyped function name is a 401
    // twenty minutes later, and this is the screen where it can still be a
    // typo the user simply fixes.
    let faults = crate::generators::check(rows);
    if !faults.is_empty() {
        ui.add_space(6.0);
        ui.label(
            RichText::new(s.gui_generated_faults)
                .color(theme.err)
                .strong(),
        );
        for line in crate::i18n::summarise_gen_errors(s, &faults) {
            ui.label(RichText::new(line).color(theme.err));
        }
    }
    changed
}

/// One row of an expression field's completion list.
#[derive(Clone, PartialEq)]
struct Suggestion {
    /// What is written into the field when the row is accepted.
    text: String,
    kind: SuggestKind,
    /// One line saying what it is, shown under the list for the highlighted
    /// row. A signature says how to *call* a function and nothing about what it
    /// does, which is the half a user reaching for `hmac_sha256_b64` already
    /// knows.
    note: &'static str,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum SuggestKind {
    /// A function signature: accepted as a call, with its first argument
    /// selected.
    Signature,
    /// A ready-made call from [`crate::generators::GenFunction::examples`],
    /// written in as it stands.
    Example,
    /// A variable this row may read: an environment variable, an earlier
    /// request's capture, or a `[Gen]` row above this one. Expressions refer to
    /// variables by bare name, so they belong in the same list as the
    /// functions rather than in one of their own.
    Variable,
}

/// The state of one expression field's completion list, for the frame being
/// drawn.
///
/// A struct rather than a handful of locals because the work is split either
/// side of the field: the keys have to be taken before the `TextEdit` is added
/// (or ↑↓ move the caret instead of the selection) while the popup can only be
/// placed once there is a field rect to hang it under.
#[derive(Clone)]
struct Suggest {
    /// The field the list belongs to.
    id: egui::Id,
    /// Whether the field had focus on the previous frame, which is how an
    /// Escape that egui has already acted on is recognised (see below).
    had_focus: bool,
    /// The word the caret is in, which is what the list is filtered by.
    word: String,
    /// The rows on offer.
    rows: Vec<Suggestion>,
    /// Which row is highlighted.
    sel: usize,
    /// The word the user dismissed the list for. Kept as the *word* rather than
    /// a flag so typing another character brings the list back: Esc means "not
    /// for this", not "never again".
    dismissed_for: Option<String>,
    /// Whether the user asked for the list with Ctrl+Space, which overrides a
    /// dismissal and shows everything regardless of what has been typed.
    forced: bool,
    /// A row accepted by the keyboard this frame, to write into the field
    /// before it is drawn so the change is on screen immediately.
    accepted: Option<Suggestion>,
}

impl Default for Suggest {
    fn default() -> Self {
        Self {
            id: egui::Id::NULL,
            had_focus: false,
            word: String::new(),
            rows: Vec::new(),
            sel: 0,
            dismissed_for: None,
            forced: false,
            accepted: None,
        }
    }
}

/// Where the caret is in the field with `id`, if egui knows.
fn caret_of(ctx: &egui::Context, id: egui::Id) -> Option<usize> {
    let state = egui::TextEdit::load_state(ctx, id)?;
    state.cursor.char_range().map(|r| r.primary.index.0)
}

/// Read (and re-derive) the completion state for the expression field `id`.
///
/// Only ever offered while the field has focus: a list hanging under a field
/// nobody is typing in is in the way of the row below it.
///
/// `vars` are the names this expression may read — the environment, the
/// collection's captures, and the rows above this one.
fn suggest_state(ui: &egui::Ui, s: &Strings, id: egui::Id, text: &str, vars: &[String]) -> Suggest {
    let mut st: Suggest = ui
        .data(|d| d.get_temp::<Suggest>(id.with("suggest")))
        .unwrap_or_default();
    st.accepted = None;
    st.id = id;
    let mut focused = ui.memory(|m| m.has_focus(id));
    // egui takes a text field's focus away on Escape at the start of the pass,
    // before any widget runs -- so a key consumed here is consumed too late,
    // and the list would close only as a side effect of the field going quiet.
    // Recognise that case from the outside (focus was here last frame, is gone
    // this frame, and Escape was pressed) and put it back: Escape while the
    // list is up means "not this suggestion", not "stop typing". A second
    // Escape, with the list closed, leaves the field the usual way.
    if !focused && st.had_focus && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
        ui.ctx().memory_mut(|m| m.request_focus(id));
        focused = true;
        st.dismissed_for =
            Some(crate::generators::typed_word_at(text, caret_of(ui.ctx(), id)).prefix);
    }
    st.had_focus = focused;
    if !focused {
        st.forced = false;
    }
    let typed = crate::generators::typed_word_at(text, caret_of(ui.ctx(), id));
    // The *typed* part of the word, not the whole of it: see `TypedWord`.
    st.word = typed.prefix.clone();
    // Nothing typed yet is a question, not a blank: an empty cell (or a caret
    // just inside a bracket) is exactly where someone wants to be shown what
    // there is, which is the job the ƒ menu used to do badly.
    let browse = st.forced || st.word.is_empty();
    st.rows = if focused {
        suggestions(s, &typed, browse, vars)
    } else {
        Vec::new()
    };
    if st.dismissed_for.as_deref() != Some(st.word.as_str()) {
        st.dismissed_for = None;
    }
    st.sel = st.sel.min(st.rows.len().saturating_sub(1));
    st
}

/// The rows to offer for `word`: the variables it could be, then the functions.
///
/// Variables come first because there are a handful of them and thirty-five
/// functions: a name the user has defined is a specific answer, and burying it
/// under a scrolling list of the built-ins would make it unfindable.
fn suggestions(
    s: &Strings,
    w: &crate::generators::TypedWord,
    browse: bool,
    vars: &[String],
) -> Vec<Suggestion> {
    let lower = w.prefix.to_ascii_lowercase();
    let mut out: Vec<Suggestion> = vars
        .iter()
        .filter(|v| browse || v.to_ascii_lowercase().starts_with(&lower))
        .map(|v| Suggestion {
            text: v.clone(),
            kind: SuggestKind::Variable,
            note: s.gui_generated_var_note,
        })
        .collect();
    // The same list, from the same table, as the terminal wizard's dropdown.
    for row in
        crate::generators::suggestions_for_word(&w.prefix, &w.whole, browse).unwrap_or_default()
    {
        let f = crate::generators::function_for_suggestion(row);
        let signature = f.is_some_and(|f| f.signature == row);
        out.push(Suggestion {
            text: row.to_string(),
            kind: if signature {
                SuggestKind::Signature
            } else {
                SuggestKind::Example
            },
            note: f.map(|f| s.gen_description(f.name)).unwrap_or(""),
        });
    }
    out
}

impl Suggest {
    /// Whether the list is on screen, and so owns its keys.
    fn open(&self) -> bool {
        !self.rows.is_empty() && (self.forced || self.dismissed_for.is_none())
    }

    /// Take the keys the list answers to out of the queue before the field can
    /// read them. Returns whether a row was accepted.
    ///
    /// Enter and Tab both accept: Enter is what the terminal wizard uses, and
    /// Tab is what every other completion in every other editor uses. The field
    /// is a multiline `TextEdit` with `return_key(None)`, so neither is being
    /// stolen from anything.
    fn take_keys(&mut self, ui: &egui::Ui) -> bool {
        // Ctrl+Space is read whether the list is up or not -- asking for it is
        // the one thing that has to work when it is down.
        if self.had_focus
            && ui.input_mut(|i| i.consume_key(egui::Modifiers::CTRL, egui::Key::Space))
        {
            self.forced = true;
            self.sel = 0;
        }
        if !self.open() {
            return false;
        }
        let n = self.rows.len();
        let (mut down, mut up, mut accept, mut dismiss) = (false, false, false, false);
        ui.input_mut(|i| {
            use egui::{Key, Modifiers};
            down = i.consume_key(Modifiers::NONE, Key::ArrowDown);
            up = i.consume_key(Modifiers::NONE, Key::ArrowUp);
            accept = i.consume_key(Modifiers::NONE, Key::Enter)
                || i.consume_key(Modifiers::NONE, Key::Tab);
            dismiss = i.consume_key(Modifiers::NONE, Key::Escape);
        });
        if down {
            self.sel = (self.sel + 1) % n;
        }
        if up {
            self.sel = (self.sel + n - 1) % n;
        }
        if dismiss {
            self.dismissed_for = Some(self.word.clone());
            self.forced = false;
            // egui surrenders a text field's focus on Escape before any widget
            // runs, so consuming the key here is not enough -- the focus has
            // already gone by the time we see it. Ask for it back: Escape while
            // the list is up means "not this suggestion", not "stop typing".
            // A second Escape, with the list closed, leaves the field as usual.
            ui.ctx().memory_mut(|m| m.request_focus(self.id));
        }
        if accept {
            self.accepted = self.rows.get(self.sel).cloned();
        }
        self.accepted.is_some()
    }

    /// Write an accepted row into the field, before it is drawn.
    fn apply(&mut self, ctx: &egui::Context, id: egui::Id, text: &mut String) {
        let Some(row) = self.accepted.take() else {
            return;
        };
        self.accept(ctx, id, text, &row);
    }

    /// Write `row` in, and put the list away until the user asks again.
    fn accept(&mut self, ctx: &egui::Context, id: egui::Id, text: &mut String, row: &Suggestion) {
        accept_suggestion(ctx, id, text, row);
        // Focus stays in the field: the next thing to do is fill the argument
        // in, and a completion that leaves the user to click back into the cell
        // has done half the job.
        ctx.memory_mut(|m| m.request_focus(id));
        self.rows.clear();
        self.forced = false;
        // The caret now sits inside the brackets, where the word is empty and
        // the list would otherwise spring straight back up over the argument
        // being typed. Ctrl+Space asks for it again.
        self.dismissed_for = Some(String::new());
    }

    /// Draw the list under `field`, and act on a click. Returns whether the
    /// text changed.
    fn show(
        &mut self,
        ui: &egui::Ui,
        theme: &GuiTheme,
        field: &egui::Response,
        id: egui::Id,
        text: &mut String,
    ) -> bool {
        let open = self.open();
        let mut picked: Option<Suggestion> = None;
        let mut hovered: Option<usize> = None;
        if open {
            egui::Popup::from_response(field)
                .id(id.with("suggest-popup"))
                .open(true)
                .align(egui::RectAlign::BOTTOM_START)
                .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
                .show(|ui| {
                    egui::ScrollArea::vertical()
                        .max_height(240.0)
                        .show(ui, |ui| {
                            for (k, row) in self.rows.iter().enumerate() {
                                // An example is drawn dimmed and indented under
                                // the signature it belongs to, as the terminal
                                // wizard draws it; a variable is dimmed too,
                                // since it is a name the user already knows
                                // rather than one being offered to them.
                                let label = match row.kind {
                                    SuggestKind::Signature => RichText::new(&row.text).monospace(),
                                    SuggestKind::Example => {
                                        RichText::new(format!("    {}", row.text))
                                            .monospace()
                                            .color(theme.dim)
                                    }
                                    SuggestKind::Variable => {
                                        RichText::new(&row.text).monospace().color(theme.computed)
                                    }
                                };
                                let hit = ui.add(egui::Button::selectable(k == self.sel, label));
                                // Pointing at a row selects it, as the arrow
                                // keys do: the note and the preview under the
                                // list describe *the* highlighted row, and a
                                // mouse that moved the eye without moving the
                                // highlight left them describing whatever the
                                // keyboard last landed on.
                                if hit.hovered() {
                                    hovered = Some(k);
                                }
                                if hit.clicked() {
                                    picked = Some(row.clone());
                                }
                            }
                        });
                    // What the highlighted row would *do to this expression*,
                    // and what it does in general — under the list rather than
                    // beside each row, since a note per row would triple the
                    // width of a list whose whole job is to be scanned.
                    //
                    // The preview is here because the same row can replace the
                    // word at the caret or build a call around it, depending on
                    // what the caret is in front of and what the function can
                    // hold. Those are good rules and impossible to guess, so
                    // rather than explain them, show the answer: `base64` over
                    // `uuid` reads `-> base64(uuid)` before it is accepted.
                    // Applied before the note and preview are drawn, so a
                    // hovered row describes itself in the same frame. The rows
                    // above have already been painted with the old highlight;
                    // the repaint puts that right without a visible flicker,
                    // and without it a still mouse could sit on an unhighlighted
                    // row indefinitely.
                    if let Some(k) = hovered.filter(|k| *k != self.sel) {
                        self.sel = k;
                        ui.ctx().request_repaint();
                    }
                    let row = self.rows.get(self.sel);
                    let preview = row
                        .map(|r| preview_of(text, caret_of(ui.ctx(), id), r))
                        .filter(|p| p != text && Some(p.as_str()) != row.map(|r| r.text.as_str()));
                    let note = row.map(|r| r.note).filter(|n| !n.is_empty());
                    if preview.is_some() || note.is_some() {
                        ui.separator();
                    }
                    if let Some(preview) = preview {
                        ui.label(
                            RichText::new(format!("\u{2192} {preview}"))
                                .monospace()
                                .color(theme.computed),
                        );
                    }
                    if let Some(note) = note {
                        ui.label(RichText::new(note).color(theme.dim));
                    }
                });
        }
        let took = picked.is_some();
        if let Some(row) = picked {
            self.accept(ui.ctx(), id, text, &row);
        }
        ui.ctx()
            .data_mut(|d| d.insert_temp(id.with("suggest"), self.clone()));
        took
    }
}

/// What the field would read if `row` were accepted now.
///
/// The same edit the accept path makes, made to a copy: the list draws this
/// under the highlighted row, and the field itself is not to be touched until
/// the user actually chooses something.
fn preview_of(text: &str, caret: Option<usize>, row: &Suggestion) -> String {
    match row.kind {
        SuggestKind::Signature => match crate::generators::function_for_suggestion(&row.text) {
            Some(f) => insert_call(text, caret, f).0,
            None => text.to_string(),
        },
        _ => splice(text, caret, &row.text).0,
    }
}

/// Write the suggestion `row` into `text`: a signature becomes the call it
/// describes, anything else goes in as it stands.
fn accept_suggestion(ctx: &egui::Context, id: egui::Id, text: &mut String, row: &Suggestion) {
    match row.kind {
        SuggestKind::Signature => {
            let Some(f) = crate::generators::function_for_suggestion(&row.text) else {
                return;
            };
            write_call(ctx, id, text, f);
        }
        _ => write_text(ctx, id, text, &row.text),
    }
}

/// Write `f`'s call into the field, replacing the word the caret is in.
///
/// The word is replaced rather than inserted beside: completing `sha` with
/// `sha256` has to leave one `sha256`, not `shasha256`. With an empty word --
/// a blank cell, or a caret just inside a bracket -- there is nothing to
/// replace and the call is simply written where the caret is.
fn write_call(
    ctx: &egui::Context,
    id: egui::Id,
    text: &mut String,
    f: &crate::generators::GenFunction,
) {
    insert_at_caret(ctx, id, text, |text, caret| insert_call(text, caret, f));
}

/// Write a ready-made call, or a variable name, into the field.
///
/// The same caret and undo care as [`write_call`], but the caret lands after
/// what was written rather than inside it: these arrive complete, so the next
/// thing to do is carry on writing the expression around them.
fn write_text(ctx: &egui::Context, id: egui::Id, text: &mut String, call: &str) {
    insert_at_caret(ctx, id, text, |text, caret| {
        let (out, start, _) = splice(text, caret, call);
        let at = start + call.chars().count();
        (out, at, at)
    });
}

/// The shared half of [`write_call`] and [`write_text`]: apply an edit made
/// behind the field's back, and tell the field's own state about it.
///
/// Everything a field has to be told happens here:
///
/// * the caret — or the *selection*, since a call written in with its argument
///   names in it leaves the first of them selected, so typing over it fills the
///   argument in. egui keeps this per field and would otherwise leave it where
///   it was, pointing into text that has since moved;
/// * an undo point holding the text *before* the insert. egui only records one
///   once the text has sat still for a moment, so a completion lands inside
///   that window: Ctrl+Z would jump back past it to whatever was last stable —
///   usually the empty cell — with no redo to come back by. Recording the
///   pre-insert state makes the insert one reversible step like a typed one.
///
/// With no state stored — a cell never clicked into — there is no caret to
/// insert at and no history to preserve, so the edit goes on the end.
fn insert_at_caret(
    ctx: &egui::Context,
    id: egui::Id,
    text: &mut String,
    edit: impl Fn(&str, Option<usize>) -> (String, usize, usize),
) {
    use egui::text::{CCursor, CCursorRange};
    let Some(mut state) = egui::TextEdit::load_state(ctx, id) else {
        (*text, _, _) = edit(text, None);
        return;
    };
    let range = state.cursor.char_range();
    let at_end = CCursorRange::one(CCursor::new(text.chars().count()));
    let mut undoer = state.undoer();
    undoer.add_undo(&(range.unwrap_or(at_end), text.clone()));
    state.set_undoer(undoer);
    let (out, from, to) = edit(text, range.map(|r| r.primary.index.0));
    *text = out;
    state.cursor.set_char_range(Some(CCursorRange::two(
        CCursor::new(from),
        CCursor::new(to),
    )));
    egui::TextEdit::store_state(ctx, id, state);
}

/// Put `with` into `text` in place of the word the caret sits in, returning the
/// new text and the range that word occupied.
///
/// The word is *replaced* so choosing `sha256` after typing `sha` leaves one
/// `sha256` rather than `shasha256`, and the rest of the expression around it
/// is untouched.
fn splice(text: &str, caret: Option<usize>, with: &str) -> (String, usize, usize) {
    let w = crate::generators::typed_word_at(text, caret);
    (splice_range(text, w.start, w.end, with), w.start, w.end)
}

/// Put `with` into `text` in place of the chars in `start..end`.
fn splice_range(text: &str, start: usize, end: usize, with: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    let mut out: String = chars[..start.min(chars.len())].iter().collect();
    out.push_str(with);
    out.extend(chars[end.min(chars.len())..].iter());
    out
}

/// Write `f`'s call into `text` at the caret, returning the new text and what
/// should be selected afterwards.
///
/// A function that takes an argument is written with its brackets *and* the
/// argument names from its signature — `hmac_sha256(key, text)` — with the
/// first name selected, so typing fills it in while the rest of the call stays
/// as a reminder of what else is wanted. An unclosed bracket would be an
/// expression the user has to go back and finish, and the editor would call it
/// a syntax error in the meantime. A function that takes nothing is complete as
/// its bare name, which is how the block already reads `stamp = timestamp`.
fn insert_call(
    text: &str,
    caret: Option<usize>,
    f: &crate::generators::GenFunction,
) -> (String, usize, usize) {
    let mut args: Vec<String> = arg_names(f.signature)
        .into_iter()
        .map(str::to_string)
        .collect();
    let w = crate::generators::typed_word_at(text, caret);
    // Text the caret was put in front of is what the call is being built
    // *around*: `|uuid` completed with `base64` means `base64(uuid)`, not a
    // `base64` where the `uuid` used to be. See `generators::can_wrap` for what
    // may hold it.
    let wrapping = crate::generators::can_wrap(f) && !w.wrapped.is_empty();
    if wrapping {
        // A signature with no named argument at all can still be wrapped
        // around something if it is variadic, so there may be no placeholder
        // to overwrite.
        match args.first_mut() {
            Some(first) => *first = w.wrapped.clone(),
            None => args.push(w.wrapped.clone()),
        }
    }
    // Written with its brackets when it is holding something or needs
    // something; a function that needs nothing is complete as its bare name,
    // which is how a block already reads `stamp = timestamp`.
    let call = if wrapping || f.min_args > 0 {
        format!("{}({})", f.name, args.join(", "))
    } else {
        f.name.to_string()
    };
    let end = if wrapping { w.wrap_end } else { w.end };
    let out = splice_range(text, w.start, end, &call);
    let start = w.start;
    if !wrapping && f.min_args == 0 {
        let at = start + call.chars().count();
        return (out, at, at);
    }
    // The argument left to fill in, selected: the first, or -- when the first
    // is the text just wrapped -- the next one along. With nothing left to
    // fill in, the caret goes after the closing bracket, where the expression
    // carries on.
    let filled = usize::from(wrapping);
    let Some(arg) = args.get(filled) else {
        let at = start + call.chars().count();
        return (out, at, at);
    };
    // `(` is one character past the name; each earlier argument is followed by
    // the `, ` that `join` put in.
    let before: usize = args[..filled].iter().map(|a| a.chars().count() + 2).sum();
    let from = start + f.name.chars().count() + 1 + before;
    let to = from + arg.chars().count();
    (out, from, to)
}

/// The argument names in a signature, without the brackets that mark the
/// optional ones: `timestamp([offset_seconds])` gives `offset_seconds`.
///
/// Written into the call as placeholder text, so they have to be the names the
/// signature shows — a user who fills the first one in and stops still has a
/// call that says what is missing.
fn arg_names(signature: &str) -> Vec<&str> {
    let Some(open) = signature.find('(') else {
        return Vec::new();
    };
    let inner = signature[open + 1..].trim_end_matches(')');
    inner
        .split(',')
        .map(|a| a.trim().trim_matches(|c| c == '[' || c == ']'))
        .filter(|a| !a.is_empty())
        .collect()
}

pub fn pair_editor(
    ui: &mut egui::Ui,
    theme: &GuiTheme,
    s: &Strings,
    id: impl std::hash::Hash + std::fmt::Debug,
    rows: &mut Vec<(String, String)>,
    key_hint: &str,
    val_hint: &str,
    key_label: &str,
    val_label: &str,
) -> bool {
    let mut changed = false;
    let mut remove: Option<usize> = None;
    // See `kv_editor`: the value fills only as the last column, so the remove ✕
    // shares the value cell (right-aligned) rather than being its own column,
    // and the key takes ~40% of the free width so it grows too.
    let key_w = split_key_width(ui, 42.0);
    let x_w = remove_width(ui);
    let row_h = ui.spacing().interact_size.y;
    ui.push_id(id, |ui| {
        table_rows(ui, |ui| {
            // See `kv_editor`: titled columns, minus the enabled tick this
            // table doesn't have, and top-aligned rows so they don't sag.
            table_row(ui, |ui| {
                sized_header(ui, theme, key_label, key_w);
                column_header(ui, theme, val_label);
            });
            for i in 0..rows.len() {
                table_row(ui, |ui| {
                    let k = sized_key(ui, key_w, &mut rows[i].0, key_hint, theme.text);
                    if k.changed() {
                        changed = true;
                    }
                    let val_w = (ui.available_width() - x_w - 8.0).max(40.0);
                    let v = wrapping_field(ui, val_w, &mut rows[i].1, val_hint, theme.text);
                    if v.changed() {
                        changed = true;
                    }
                    let hit = flat_buttons(ui, |ui| {
                        ui.add_sized(
                            [x_w, row_h],
                            egui::Button::new(RichText::new(super::icons::CLOSE).color(theme.err)),
                        )
                    });
                    if hit.clicked() {
                        remove = Some(i);
                    }
                });
            }
        });
    });
    if let Some(i) = remove {
        rows.remove(i);
        changed = true;
    }
    if ui.button(s.gui_add).clicked() {
        rows.push((String::new(), String::new()));
        changed = true;
    }
    changed
}

/// A horizontal row of pill "section" tabs; sets `*current` to the clicked one.
pub fn section_tabs<T: PartialEq + Copy>(
    ui: &mut egui::Ui,
    theme: &GuiTheme,
    current: &mut T,
    tabs: &[(T, &str)],
) {
    ui.horizontal_wrapped(|ui| {
        for (value, label) in tabs {
            let selected = *current == *value;
            let mut text = RichText::new(*label);
            text = if selected {
                text.strong().color(theme.text)
            } else {
                text.color(theme.dim)
            };
            if selectable(ui, selected, text).clicked() {
                *current = *value;
            }
        }
    });
}

/// A small count suffix like " (3)" for a section that has content.
pub fn count_suffix(n: usize) -> String {
    if n == 0 {
        String::new()
    } else {
        format!(" ({n})")
    }
}

/// Colour a status code by class (2xx ok, 4xx/5xx error, else pending).
pub fn status_color(theme: &GuiTheme, status: u16) -> Color32 {
    match status {
        200..=299 => theme.ok,
        400..=599 => theme.err,
        _ => theme.pending,
    }
}

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

    fn screen() -> egui::Rect {
        egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(900.0, 600.0))
    }

    fn a_frame() -> egui::RawInput {
        egui::RawInput {
            screen_rect: Some(screen()),
            ..Default::default()
        }
    }

    fn click_at(input: &mut egui::RawInput, pos: egui::Pos2) {
        input.events.push(egui::Event::PointerMoved(pos));
        for pressed in [true, false] {
            input.events.push(egui::Event::PointerButton {
                pos,
                button: egui::PointerButton::Primary,
                pressed,
                modifiers: egui::Modifiers::NONE,
            });
        }
    }

    /// A modal dialog owns the keyboard as well as the pointer: the dimmed
    /// sheet already swallowed clicks, but Tab used to walk straight out of the
    /// dialog and into the panels behind it. Naming the dialog's layer as
    /// egui's modal layer is what confines focus to it.
    fn top_modal_layer_after(modeless: bool) -> Option<egui::LayerId> {
        let ctx = egui::Context::default();
        // Two passes: the layer is registered by the pass that draws the
        // window, and egui only reports it from the pass after that.
        for _ in 0..2 {
            let _ = ctx.run_ui(a_frame(), |ui| {
                let ctx = ui.ctx().clone();
                // Something focusable behind the dialog, which is what Tab used
                // to escape into.
                let mut behind = String::new();
                ui.add(egui::TextEdit::singleline(&mut behind));
                if modeless {
                    dialog_modeless(&ctx, "Dlg", None, |ui| ui.button("ok"));
                } else {
                    dialog(&ctx, "Dlg", None, |ui| ui.button("ok"));
                }
            });
        }
        ctx.memory(|m| m.top_modal_layer())
    }

    #[test]
    fn a_modal_dialog_confines_keyboard_focus_to_its_own_layer() {
        let layer = top_modal_layer_after(false);
        // The id is egui's own (a `Window` derives it from the title), so the
        // assertion is on what matters: a modal layer exists, and it is the
        // foreground one the dialog was put in rather than the panels below.
        assert_eq!(
            layer.map(|l| l.order),
            Some(egui::Order::Foreground),
            "the dialog's own layer is the modal one, so Tab can't leave it"
        );
        assert_ne!(layer, Some(egui::LayerId::background()));
    }

    /// The modeless shell is the opposite case by design: it reports progress
    /// beside work the user is still doing, so it must not capture the keyboard.
    #[test]
    fn a_modeless_dialog_leaves_the_keyboard_alone() {
        assert_eq!(top_modal_layer_after(true), None);
    }

    /// The flattening is scoped. A checkbox or a button in the same row still
    /// gets its outline — an outline is how a *control* says it is a control;
    /// the fields give theirs up because they are mostly content.
    #[test]
    fn flattening_a_field_does_not_flatten_the_controls_beside_it() {
        let ctx = egui::Context::default();
        // The app's own theme, not egui's defaults: the outline this is about
        // is one PaperBoy puts there.
        GuiTheme::from_spec(&crate::theme::default_preset()).apply(&ctx);
        let mut inside = egui::Stroke::new(9.0, Color32::RED);
        let mut after = egui::Stroke::new(9.0, Color32::RED);
        let _ = ctx.run_ui(a_frame(), |ui| {
            let before = ui.visuals().widgets.inactive.bg_stroke;
            assert!(before.width > 0.0, "the app's controls are outlined");
            flat_fields(ui, |ui| {
                inside = ui.visuals().widgets.inactive.bg_stroke;
            });
            after = ui.visuals().widgets.inactive.bg_stroke;
        });
        assert_eq!(inside, egui::Stroke::NONE, "no box around an idle field");
        assert!(
            after.width > 0.0,
            "and everything after it is left alone, got {after:?}"
        );
    }

    /// A field whose value doesn't fit used to hide the rest behind a
    /// scrolling viewport. It now wraps, so the row grows and the whole value
    /// is on screen — the point of the panel.
    #[test]
    fn a_long_value_wraps_instead_of_scrolling_out_of_sight() {
        let ctx = egui::Context::default();
        let measure = |text: &str| -> f32 {
            let mut value = text.to_string();
            let mut height = 0.0;
            // Twice: egui settles galley sizes on the second pass.
            for _ in 0..2 {
                let _ = ctx.run_ui(a_frame(), |ui| {
                    height = wrapping_field(ui, 200.0, &mut value, "", Color32::WHITE)
                        .rect
                        .height();
                });
            }
            height
        };

        let short = measure("small");
        let long = measure(
            "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.a-very-long-token-that-will-not-fit              in-two-hundred-points-of-width-no-matter-how-small-the-font-is",
        );
        assert!(
            long > short * 2.0,
            "a value too long for the field must wrap onto more lines: {short} then {long}"
        );
    }

    /// The wrapping is for reading, not for multi-line values: a header broken
    /// across lines would not survive being written out as Hurl.
    #[test]
    fn enter_cannot_break_a_value_across_lines() {
        let ctx = egui::Context::default();
        let mut value = "text/plain".to_string();
        let mut input = a_frame();
        // Click into the field, then press Enter.
        click_at(&mut input, egui::pos2(60.0, 12.0));
        input.events.push(egui::Event::Key {
            key: egui::Key::Enter,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: egui::Modifiers::NONE,
        });
        for _ in 0..2 {
            let _ = ctx.run_ui(input.clone(), |ui| {
                wrapping_field(ui, 200.0, &mut value, "", Color32::WHITE);
            });
        }
        assert_eq!(value, "text/plain", "Enter must not insert a newline");
    }

    /// A dialog covers the app with a sheet that eats clicks: the menu bar and
    /// the panels underneath must not act while a dialog is waiting for an
    /// answer, or a second wizard ends up opened on top of the first. It is an
    /// *input* sink only — the frame loop keeps running, so background work
    /// (a git fetch, a report run) still finishes while the dialog is up.
    #[test]
    fn a_dialog_stops_clicks_reaching_the_app_behind_it() {
        // The button sits in the far corner, well away from the centred dialog.
        let button_pos = egui::pos2(20.0, 20.0);

        let clicked_behind = |with_dialog: bool| {
            let ctx = egui::Context::default();
            let mut clicked = false;
            // Two passes: egui needs the first to lay the widgets out before a
            // click can land on them.
            for pass in 0..2 {
                let mut input = a_frame();
                if pass == 1 {
                    click_at(&mut input, button_pos);
                }
                let _ = ctx.run_ui(input, |ui| {
                    if ui.button("behind").clicked() {
                        clicked = true;
                    }
                    if with_dialog {
                        let ctx = ui.ctx().clone();
                        dialog(&ctx, "In the way", None, |ui| {
                            ui.label("answer me");
                        });
                    }
                });
            }
            clicked
        };

        assert!(
            clicked_behind(false),
            "the test's own button is clickable with no dialog up"
        );
        assert!(
            !clicked_behind(true),
            "the same click must not reach it through an open dialog"
        );
    }

    /// The dialog opens centred but is not pinned there: one anchored to the
    /// middle cannot be dragged off whatever the user opened it to look at.
    #[test]
    fn a_dialog_opens_centred_and_can_still_be_dragged_aside() {
        let ctx = egui::Context::default();
        let draw = |input: egui::RawInput| {
            let _ = ctx.run_ui(input, |ui| {
                let ctx = ui.ctx().clone();
                dialog(&ctx, "Draggable", None, |ui| {
                    ui.label("body");
                });
            });
            // egui derives a window's Area id from its title atoms.
            egui::AreaState::load(&ctx, egui::Id::new(Some("Draggable")))
                .expect("the dialog was drawn")
                .rect()
        };

        draw(a_frame());
        let centred = draw(a_frame());
        assert!(
            (centred.center().x - screen().center().x).abs() < 2.0
                && (centred.center().y - screen().center().y).abs() < 2.0,
            "it opens in the middle: {centred:?}"
        );

        // Drag the title bar to the left, as a user would.
        let grab = egui::pos2(centred.center().x, centred.min.y + 6.0);
        let mut press = a_frame();
        press.events.push(egui::Event::PointerMoved(grab));
        press.events.push(egui::Event::PointerButton {
            pos: grab,
            button: egui::PointerButton::Primary,
            pressed: true,
            modifiers: egui::Modifiers::NONE,
        });
        draw(press);

        let mut drag = a_frame();
        drag.events
            .push(egui::Event::PointerMoved(grab - egui::vec2(200.0, 0.0)));
        let moved = draw(drag);

        assert!(
            moved.center().x < centred.center().x - 100.0,
            "dragging the title bar moves it: {moved:?} vs {centred:?}"
        );
    }

    /// Paint one `tree_header_marked` row and return the fills of every solid
    /// rectangle it drew, so a test can tell a marked row from a plain one.
    fn header_fills(highlight: Option<egui::Color32>) -> Vec<egui::Color32> {
        let ctx = egui::Context::default();
        let mut fills = Vec::new();
        for _ in 0..3 {
            let out = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::pos2(0.0, 0.0),
                        egui::vec2(300.0, 200.0),
                    )),
                    ..Default::default()
                },
                |ui| {
                    tree_header_marked(
                        ui,
                        "env-row",
                        false,
                        false,
                        RichText::new("dev"),
                        highlight,
                        |_ui| {},
                    );
                },
            );
            fills.clear();
            // The band is pushed as a single `Shape::Vec`, so walk into groups
            // rather than only looking at top-level shapes.
            fn collect(shape: &egui::Shape, out: &mut Vec<egui::Color32>) {
                match shape {
                    egui::Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => {
                        out.push(r.fill)
                    }
                    egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
                    _ => {}
                }
            }
            out.shapes
                .iter()
                .for_each(|s| collect(&s.shape, &mut fills));
        }
        fills
    }

    /// The active Global Environment has to be obvious at a glance, not a tinted
    /// word among identically-shaped rows: a marked header paints a band plus a
    /// solid leading bar in the highlight colour, and an unmarked one paints
    /// neither.
    #[test]
    fn a_marked_tree_header_paints_a_band_in_the_highlight_colour() {
        let mark = egui::Color32::from_rgb(0x3d, 0xd6, 0x8c);

        let marked = header_fills(Some(mark));
        assert!(
            marked.contains(&mark),
            "the solid leading bar uses the highlight colour: {marked:?}"
        );
        assert!(
            marked
                .iter()
                .any(|c| *c != mark && c.r() > 0 && c.g() > c.r() && c.g() > c.b()),
            "a translucent band of the same hue sits behind the row: {marked:?}"
        );

        let plain = header_fills(None);
        assert!(
            !plain.contains(&mark),
            "an unmarked row paints no highlight: {plain:?}"
        );
        assert!(
            plain.len() < marked.len(),
            "the marking is the only difference between the two rows"
        );
    }

    /// A bare `desired_width` key field collapses to a sliver inside a grid
    /// whose last column fills; `sized_key` must instead render at the full
    /// [`split_key_width`] width. Regression test for "the key field is tiny".
    fn measure_key(screen_w: f32) -> (f32, f32) {
        let ctx = egui::Context::default();
        let mut key_w = 0.0;
        let mut rendered = 0.0;
        let mut text = "Content-Type".to_string();
        let mut value = "application/json".to_string();
        for _ in 0..4 {
            let _ = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::pos2(0.0, 0.0),
                        egui::vec2(screen_w, 400.0),
                    )),
                    ..Default::default()
                },
                |ui| {
                    key_w = split_key_width(ui, 72.0);
                    egui::Grid::new("t")
                        .num_columns(3)
                        .min_col_width(0.0)
                        .show(ui, |ui| {
                            ui.checkbox(&mut true, "");
                            // The *field*, not the text inside it: a
                            // `TextEdit`'s response rect is its text area, and
                            // the frame the user sees is that plus the margin.
                            rendered = sized_key(ui, key_w, &mut text, "", Color32::PLACEHOLDER)
                                .rect
                                .width()
                                + TEXT_EDIT_MARGIN;
                            ui.with_layout(
                                egui::Layout::right_to_left(egui::Align::Center),
                                |ui| {
                                    let _ = ui.button("x");
                                    ui.add(
                                        egui::TextEdit::singleline(&mut value)
                                            .desired_width(f32::INFINITY),
                                    );
                                },
                            );
                            ui.end_row();
                        });
                },
            );
        }
        (key_w, rendered)
    }

    /// Render a `kv_editor` with `n` rows in a fixed-width window and report
    /// the width the whole table claimed.
    fn kv_table_width(n: usize) -> f32 {
        let ctx = egui::Context::default();
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let s = Strings::for_language(&crate::i18n::Language::English);
        let mut rows: Vec<KvRow> = (0..n)
            .map(|i| KvRow::new(&format!("Header-{i}"), "a value"))
            .collect();
        let mut w = 0.0;
        // Grid column widths settle from the previous pass, so run a few.
        for _ in 0..4 {
            let _ = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::pos2(0.0, 0.0),
                        egui::vec2(900.0, 400.0),
                    )),
                    ..Default::default()
                },
                |ui| {
                    let before = ui.min_rect().width();
                    kv_editor(
                        ui,
                        &theme,
                        &s,
                        "kv",
                        &mut rows,
                        "name",
                        "value",
                        "Header",
                        "Value",
                        "Extract",
                        &mut None,
                        &[],
                    );
                    w = ui.min_rect().width() - before;
                },
            );
        }
        w
    }

    /// Render a `kv_editor` and report every piece of text it painted.
    fn kv_texts(rows: &mut Vec<KvRow>, key_options: &[&'static str]) -> Vec<String> {
        let ctx = egui::Context::default();
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let s = Strings::for_language(&crate::i18n::Language::English);
        let mut out = Vec::new();
        for _ in 0..4 {
            out.clear();
            let full = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::pos2(0.0, 0.0),
                        egui::vec2(900.0, 400.0),
                    )),
                    ..Default::default()
                },
                |ui| {
                    kv_editor(
                        ui,
                        &theme,
                        &s,
                        "kv",
                        rows,
                        "name",
                        "value",
                        "Header",
                        "Value",
                        "Extract",
                        &mut None,
                        key_options,
                    );
                },
            );
            for cs in &full.shapes {
                collect_text(&cs.shape, &mut out);
            }
        }
        out
    }

    fn collect_text(shape: &egui::Shape, out: &mut Vec<String>) {
        match shape {
            egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
            egui::Shape::Vec(v) => {
                for s in v {
                    collect_text(s, out);
                }
            }
            _ => {}
        }
    }

    /// The complaint: the terminal UI offers the common header names in its Key
    /// column and the GUI simply didn't. The caret is the affordance, so it has
    /// to be *there* — and only where there is a vocabulary to offer, since a
    /// query parameter's name is the API's business.
    #[test]
    fn a_key_column_with_a_vocabulary_gets_a_caret_and_one_without_does_not() {
        let mut rows = vec![KvRow::new("Accept", "application/json")];
        let with = kv_texts(&mut rows, crate::http::COMMON_HEADERS);
        assert!(
            with.iter().any(|t| t == super::super::icons::CARET_DOWN),
            "the headers table offers the list: {with:?}"
        );

        let mut rows = vec![KvRow::new("page", "2")];
        let without = kv_texts(&mut rows, &[]);
        assert!(
            !without.iter().any(|t| t == super::super::icons::CARET_DOWN),
            "a query parameter has nothing to suggest: {without:?}"
        );
    }

    /// Picking a name fills the cell, and the list is the same one the terminal
    /// UI narrows — both front-ends read `crate::http`.
    #[test]
    fn the_key_vocabulary_is_the_one_both_front_ends_share() {
        assert!(crate::http::COMMON_HEADERS.contains(&"Content-Type"));
        assert_eq!(
            crate::http::filter_headers("auth"),
            vec!["Authorization"],
            "the caret narrows to what has been typed"
        );
    }

    /// Collect every rectangle painted in a given fill, recursing into the
    /// nested shape lists a `Ui` produces.
    fn rects_filled(shape: &egui::Shape, fill: Color32, out: &mut Vec<egui::Rect>) {
        match shape {
            egui::Shape::Rect(r) if r.fill == fill => out.push(r.rect),
            egui::Shape::Vec(v) => {
                for s in v {
                    rects_filled(s, fill, out);
                }
            }
            _ => {}
        }
    }

    /// The field backgrounds a closure paints, in paint order.
    fn field_rects(theme: &GuiTheme, mut body: impl FnMut(&mut egui::Ui)) -> Vec<egui::Rect> {
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        let mut out = Vec::new();
        // Grid column widths and galley sizes settle from the previous pass.
        for _ in 0..4 {
            let full = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::pos2(0.0, 0.0),
                        egui::vec2(1200.0, 600.0),
                    )),
                    ..Default::default()
                },
                &mut body,
            );
            out.clear();
            for cs in &full.shapes {
                rects_filled(&cs.shape, theme.field(), &mut out);
            }
        }
        out
    }

    /// Selecting a row must not resize it: `Button::selectable` drops its frame
    /// while inactive, and the stroke width the frame folds into its margin
    /// went with it, so picking a request in the workspace tree grew that row
    /// and shuffled the rows after it down the panel. The fix must not be paid
    /// for by padding every row out to the framed size either — a list of
    /// requests spaced out by the border it isn't showing is its own bug — so
    /// the frameless size is the one every state has to match.
    #[test]
    fn selecting_a_row_leaves_it_exactly_where_it_was() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        // A pointer parked off the rows: hover survives from frame to frame,
        // so every run has to say where the pointer is, not just the hover one.
        let away = egui::pos2(390.0, 190.0);
        let rows = |pointer: egui::Pos2, body: &mut dyn FnMut(&mut egui::Ui, usize)| {
            // Twice: the first pass has no stored response to read a state
            // from, so the steady state is the second one.
            let mut shapes = Vec::new();
            for _ in 0..2 {
                let full = ctx.run_ui(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(
                            egui::pos2(0.0, 0.0),
                            egui::vec2(400.0, 200.0),
                        )),
                        events: vec![egui::Event::PointerMoved(pointer)],
                        ..Default::default()
                    },
                    |ui| {
                        for i in 0..3 {
                            body(ui, i);
                        }
                    },
                );
                shapes = full.shapes;
            }
            shapes
        };
        let with = |selected: bool, pointer: egui::Pos2| {
            let mut rects = Vec::new();
            let shapes = rows(pointer, &mut |ui, i| {
                let r = selectable_row(ui, selected && i == 1, "GET /one").rect;
                if i == 0 {
                    rects.clear();
                }
                rects.push(r);
            });
            (rects, shapes)
        };

        let (quiet, _) = with(false, away);
        let (picked, picked_shapes) = with(true, away);
        assert_eq!(
            quiet, picked,
            "selecting the middle row moved it or its neighbours"
        );
        let (hovered, _) = with(false, quiet[0].center());
        assert_eq!(quiet, hovered, "hovering a row moved it or its neighbours");

        // The bare, unframed button is the size a row has always been.
        let mut bare = Vec::new();
        rows(away, &mut |ui, i| {
            let r = ui
                .add(egui::Button::selectable(false, "GET /one").frame_when_inactive(false))
                .rect;
            if i == 0 {
                bare.clear();
            }
            bare.push(r);
        });
        assert_eq!(
            bare, quiet,
            "rows grew to make room for a border they aren't drawing"
        );

        // The border still has to be *there*: it is drawn inside the selected
        // row's own rect rather than around it.
        let mut border = None;
        for cs in &picked_shapes {
            stroked_rects(&cs.shape, &mut |rect, width| {
                if width > 0.0 && rect == picked[1] {
                    border = Some(width);
                }
            });
        }
        assert!(
            border.is_some(),
            "the selected row lost its border: {picked_shapes:?}"
        );
    }

    /// Walk a shape tree, reporting every rectangle drawn with a visible
    /// stroke (rect, stroke width).
    fn stroked_rects(shape: &egui::Shape, out: &mut dyn FnMut(egui::Rect, f32)) {
        match shape {
            egui::Shape::Rect(r) if r.stroke.width > 0.0 => out(r.rect, r.stroke.width),
            egui::Shape::Vec(v) => {
                for s in v {
                    stroked_rects(s, out);
                }
            }
            _ => {}
        }
    }

    /// Every row of a list framed is a list that reads as disabled — the
    /// complaint that started this: the request tree looked "greyed out,
    /// almost like they are disabled" once the theme gave `raised` a colour
    /// distinct enough from the panel to be seen. A segmented control still
    /// wants its frames, so the two must part company.
    #[test]
    fn an_unselected_row_paints_no_chip_but_an_unselected_tab_does() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        let chips = |body: &dyn Fn(&mut egui::Ui)| {
            let mut out = Vec::new();
            for _ in 0..2 {
                let full = ctx.run_ui(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(
                            egui::pos2(0.0, 0.0),
                            egui::vec2(400.0, 200.0),
                        )),
                        ..Default::default()
                    },
                    |ui| body(ui),
                );
                out.clear();
                for cs in &full.shapes {
                    rects_filled(&cs.shape, theme.raised(), &mut out);
                }
            }
            out.len()
        };

        assert_eq!(
            chips(&|ui| {
                selectable_row(ui, false, "GET /one");
                selectable_row(ui, false, "GET /two");
            }),
            0,
            "an unselected list row is content, not a chip"
        );
        assert_eq!(
            chips(&|ui| {
                selectable(ui, false, "Params");
                selectable(ui, false, "Headers");
            }),
            2,
            "a segmented control keeps every option framed"
        );
    }

    /// A row's fields must sit on one line. The description shares its cell
    /// with the remove ✕, and a button is taller than a field — centring the
    /// cell's contents against it dropped the note ~2px below the key and
    /// value beside it, so every row visibly sagged to the right.
    #[test]
    fn the_fields_in_a_row_line_up_with_each_other() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let s = Strings::for_language(&crate::i18n::Language::English);
        let mut rows = vec![
            KvRow::new("Authorization", "Bearer abc"),
            KvRow::new("Accept", "application/json"),
        ];
        let rects = field_rects(&theme, |ui| {
            kv_editor(
                ui,
                &theme,
                &s,
                "kv",
                &mut rows,
                "name",
                "value",
                "Header",
                "Value",
                "Extract",
                &mut None,
                &[],
            );
        });
        assert_eq!(rects.len(), 6, "three fields per row, got {rects:?}");
        for row in rects.chunks(3) {
            let first = row[0];
            for (i, r) in row.iter().enumerate() {
                // Exactly, not nearly: a fifth of a pixel is invisible in the
                // model and a whole pixel on screen once the row lands on a
                // fractional y, which is what made the table look as though it
                // sloped. Any tolerance here is a tolerance for the bug.
                assert!(
                    (r.top() - first.top()).abs() < 0.01,
                    "field {i} sits at {} but the row starts at {}",
                    r.top(),
                    first.top()
                );
                assert!(
                    (r.height() - first.height()).abs() < 0.01,
                    "field {i} is {} tall, the row is {}",
                    r.height(),
                    first.height()
                );
            }
        }
    }

    /// The remove ✕ has to be the height of the fields it sits between. A
    /// button's own vertical padding makes it taller, so it hung below the row
    /// and drew the eye downwards at the end of every line — the sag again,
    /// this time at the right-hand edge.
    #[test]
    fn the_remove_button_does_not_hang_below_the_row() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let s = Strings::for_language(&crate::i18n::Language::English);
        let mut rows = vec![KvRow::new("Accept", "application/json")];
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        let mut button_fill = Color32::TRANSPARENT;
        let mut fields = Vec::new();
        let mut buttons = Vec::new();
        let full = ctx.run_ui(a_frame(), |ui| {
            button_fill = ui.visuals().widgets.inactive.weak_bg_fill;
            kv_editor(
                ui,
                &theme,
                &s,
                "kv",
                &mut rows,
                "name",
                "value",
                "Header",
                "Value",
                "Extract",
                &mut None,
                &[],
            );
        });
        for cs in &full.shapes {
            rects_filled(&cs.shape, theme.field(), &mut fields);
            rects_filled(&cs.shape, button_fill, &mut buttons);
        }
        let field = *fields.first().expect("a field was painted");
        // The ✕ is the rightmost control on the row; the "+ Add" button below
        // it starts at the left edge.
        let x = buttons
            .iter()
            .filter(|b| b.top() < field.bottom())
            .max_by(|a, b| a.left().total_cmp(&b.left()))
            .copied()
            .expect("the remove button was painted");
        assert!(
            x.height() <= field.height() + 0.01,
            "the ✕ is {} tall next to a {} field",
            x.height(),
            field.height()
        );
    }

    /// Striping a table whose every cell is a filled field gives each row two
    /// competing backgrounds. The fields are the row; nothing is painted
    /// behind them.
    #[test]
    fn kv_rows_are_not_striped() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let s = Strings::for_language(&crate::i18n::Language::English);
        let mut rows = vec![KvRow::new("Accept", "application/json"); 4];
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        let mut stripe = Color32::TRANSPARENT;
        let mut found = Vec::new();
        let full = ctx.run_ui(a_frame(), |ui| {
            stripe = ui.visuals().faint_bg_color;
            kv_editor(
                ui,
                &theme,
                &s,
                "kv",
                &mut rows,
                "name",
                "value",
                "Header",
                "Value",
                "Extract",
                &mut None,
                &[],
            );
        });
        for cs in &full.shapes {
            rects_filled(&cs.shape, stripe, &mut found);
        }
        // Buttons and checkboxes share `faint_bg_color`; only a band as wide
        // as the table is a stripe.
        found.retain(|r| r.width() > 300.0);
        assert!(found.is_empty(), "row stripes painted: {found:?}");
    }

    /// The column titles used to be bare labels, so an empty table sized its
    /// columns to the words "Header Value Description" and everything jumped
    /// when the first row appeared. The table must claim the same width either
    /// way.
    #[test]
    fn empty_and_filled_tables_lay_out_their_columns_identically() {
        let empty = kv_table_width(0);
        let filled = kv_table_width(2);
        assert!(
            (empty - filled).abs() < 1.0,
            "empty table was {empty} wide, filled was {filled}"
        );
    }

    /// The description column used to be whatever the key (40%) and value (60%)
    /// left over — i.e. nothing. It must get a readable share of its own.
    #[test]
    fn the_description_column_gets_a_readable_share() {
        let ctx = egui::Context::default();
        let mut got = (0.0, 0.0, 0.0, 0.0);
        let _ = ctx.run_ui(
            egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::pos2(0.0, 0.0),
                    egui::vec2(900.0, 400.0),
                )),
                ..Default::default()
            },
            |ui| got = kv_widths(ui),
        );
        let (check, key, val, desc) = got;
        assert!(desc > 150.0, "description was only {desc} wide");
        assert!(key > 150.0 && val > key, "key {key}, value {val}");
        // Nothing may overflow the row: the four columns plus the fixed
        // furniture have to fit what the table was given.
        let total = check + key + val + desc + 3.0 * 8.0 + 24.0;
        assert!(total <= 900.0, "columns sum to {total}, wider than the row");
    }

    #[test]
    fn key_field_renders_at_the_computed_split_width() {
        let (key_w, rendered) = measure_key(600.0);
        // The key must fill (near enough) the computed width, not collapse to
        // the ~24px minimum a bare grid cell would give it.
        assert!(key_w > 150.0, "split width should be substantial: {key_w}");
        assert!(
            (rendered - key_w).abs() < 2.0,
            "key rendered {rendered}, expected ~{key_w}"
        );
    }

    /// Whether the row's body was drawn — the observable half of "reveal this
    /// environment": a caller outside the panel asks for it, and the collapsing
    /// row opens without the user having clicked it.
    fn body_drawn(force_open: bool, id: &'static str) -> bool {
        let ctx = egui::Context::default();
        let mut drawn = false;
        for _ in 0..3 {
            drawn = false;
            let _ = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::pos2(0.0, 0.0),
                        egui::vec2(300.0, 200.0),
                    )),
                    ..Default::default()
                },
                |ui| {
                    tree_header_marked(
                        ui,
                        id,
                        false,
                        force_open,
                        RichText::new("dev"),
                        None,
                        |_ui| {
                            drawn = true;
                        },
                    );
                },
            );
        }
        drawn
    }

    #[test]
    fn a_collapsed_row_can_be_opened_by_its_caller_rather_than_by_a_click() {
        assert!(
            !body_drawn(false, "env-closed"),
            "a default-closed row starts closed"
        );
        assert!(
            body_drawn(true, "env-revealed"),
            "asking to reveal it should open it with no click involved"
        );
    }

    /// A tree row is a click target, and the environment list — built from
    /// these headers — was the one list in the app that gave no sign the
    /// pointer was over a row.
    #[test]
    fn a_tree_row_lights_up_under_the_pointer() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        let wash = ctx
            .style_of(egui::Theme::Dark)
            .visuals
            .widgets
            .hovered
            .weak_bg_fill;
        let washes = |pointer: egui::Pos2| {
            let mut out = Vec::new();
            for _ in 0..2 {
                let full = ctx.run_ui(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(
                            egui::pos2(0.0, 0.0),
                            egui::vec2(300.0, 200.0),
                        )),
                        events: vec![egui::Event::PointerMoved(pointer)],
                        ..Default::default()
                    },
                    |ui| {
                        tree_header(ui, "hover-row", false, RichText::new("dev"), |_ui| {});
                    },
                );
                out.clear();
                for cs in &full.shapes {
                    rects_filled(&cs.shape, wash, &mut out);
                }
            }
            out.len()
        };

        assert_eq!(
            washes(egui::pos2(280.0, 190.0)),
            0,
            "a row at rest is plain"
        );
        assert_eq!(
            washes(egui::pos2(40.0, 8.0)),
            1,
            "the row under the pointer should say so"
        );
    }

    /// A field that *asks* for its maximum height makes its row that tall
    /// whatever it holds — which is what pushed the URL off the line it shares
    /// with the method picker and the Send button. A value that fits has to
    /// take exactly the room it needs.
    #[test]
    fn a_short_value_does_not_reserve_the_room_a_long_one_would() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        let row_height = |value: Option<&str>| {
            let mut text = value.unwrap_or_default().to_string();
            let mut out = 0.0;
            // Galley sizes settle from the previous pass.
            for _ in 0..3 {
                let _ = ctx.run_ui(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(
                            egui::pos2(0.0, 0.0),
                            egui::vec2(400.0, 600.0),
                        )),
                        ..Default::default()
                    },
                    |ui| {
                        // The URL row: a picker, the field, and a button.
                        ui.horizontal(|ui| {
                            let _ = ui.button("POST");
                            if value.is_some() {
                                wrapping_field(ui, 200.0, &mut text, "", Color32::WHITE);
                            }
                            let _ = ui.button("Send");
                            out = ui.min_rect().height();
                        });
                    },
                );
            }
            out
        };

        // The row the controls alone make, against the row they make with a
        // one-line URL between them.
        let controls = row_height(None);
        let with_url = row_height(Some("{{url}}/create_session"));
        assert!(
            with_url <= controls + 2.0,
            "a one-line URL made its row {with_url}px tall, next to {controls}px of controls"
        );
    }

    /// A JWT in an environment variable is a hundred wrapped lines, and a
    /// field that tall pushed every other variable out of the panel. Past a
    /// few lines the field scrolls within itself instead of growing.
    #[test]
    fn a_very_long_value_stops_growing_and_scrolls_instead() {
        let theme = GuiTheme::from_spec(&crate::theme::default_preset());
        let ctx = egui::Context::default();
        theme.apply(&ctx);
        let height = |value: &str| {
            let mut text = value.to_string();
            let mut out = 0.0;
            // Galley sizes settle from the previous pass.
            for _ in 0..3 {
                let _ = ctx.run_ui(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(
                            egui::pos2(0.0, 0.0),
                            egui::vec2(300.0, 600.0),
                        )),
                        ..Default::default()
                    },
                    |ui| {
                        ui.scope(|ui| {
                            wrapping_field(ui, 120.0, &mut text, "", Color32::WHITE);
                            out = ui.min_rect().height();
                        });
                    },
                );
            }
            out
        };

        let one_line = height("short");
        let jwt = height(&"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.".repeat(40));
        assert!(
            jwt > one_line,
            "a value that needs two lines still gets them"
        );
        assert!(
            jwt <= one_line * (FIELD_MAX_LINES + 1.0),
            "a huge value took the whole panel ({jwt}px for a {one_line}px row)"
        );
    }

    /// One frame stamped at `time`: what the body reserved, and every stroked
    /// path it painted, as its point list.
    fn spun_frame(time: f64) -> (egui::Rect, Vec<Vec<egui::Pos2>>) {
        fn walk(s: &egui::epaint::Shape, out: &mut Vec<Vec<egui::Pos2>>) {
            match s {
                egui::epaint::Shape::Path(p) if !p.stroke.is_empty() => out.push(p.points.clone()),
                egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                _ => {}
            }
        }
        let ctx = egui::Context::default();
        let rect = std::cell::Cell::new(egui::Rect::NOTHING);
        let out = ctx.run_ui(
            egui::RawInput {
                time: Some(time),
                ..a_frame()
            },
            |ui| rect.set(spinning_icon(ui, egui::Color32::RED).rect),
        );
        let mut shapes = Vec::new();
        for c in &out.shapes {
            walk(&c.shape, &mut shapes);
        }
        (rect.get(), shapes)
    }

    /// Where the painted arc starts, as an angle about the ring's centre.
    fn arc_start(arc: &[egui::Pos2]) -> f32 {
        let d = arc[0] - ring_centre(arc);
        d.y.atan2(d.x)
    }

    /// The centre of the ring the arc lies on, fitted as the circumcircle of
    /// three well-separated points. Its bounding box is no use for this: the
    /// notch pulls one side in, and which side changes as it turns.
    fn ring_centre(arc: &[egui::Pos2]) -> egui::Pos2 {
        let p = |i: usize| {
            let q = arc[i * (arc.len() - 1) / 3];
            (q.x as f64, q.y as f64)
        };
        let ((ax, ay), (bx, by), (cx, cy)) = (p(0), p(1), p(2));
        let (sa, sb, sc) = (ax * ax + ay * ay, bx * bx + by * by, cx * cx + cy * cy);
        let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
        egui::pos2(
            ((sa * (by - cy) + sb * (cy - ay) + sc * (ay - by)) / d) as f32,
            ((sa * (cx - bx) + sb * (ax - cx) + sc * (bx - ax)) / d) as f32,
        )
    }

    /// Where a plain label of the same glyph puts that glyph's *ink* — which
    /// is not the middle of the box it reserves, because the ring sits on the
    /// text line rather than filling the em vertically.
    fn still_icon_ink_centre() -> egui::Pos2 {
        fn walk(s: &egui::epaint::Shape, out: &mut Option<egui::Pos2>) {
            match s {
                egui::epaint::Shape::Text(t) => {
                    if let Some(row) = t.galley.rows.first() {
                        *out = Some(
                            t.pos + row.pos.to_vec2() + row.visuals.mesh_bounds.center().to_vec2(),
                        );
                    }
                }
                egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                _ => {}
            }
        }
        let ctx = egui::Context::default();
        let out = ctx.run_ui(a_frame(), |ui| {
            ui.colored_label(egui::Color32::RED, super::super::icons::RUNNING);
        });
        let mut found = None;
        for c in &out.shapes {
            walk(&c.shape, &mut found);
        }
        found.expect("the label painted its glyph")
    }

    #[test]
    fn the_running_icon_turns_as_time_passes() {
        let (_, first) = spun_frame(0.30);
        let (_, later) = spun_frame(0.45);
        assert_eq!(first.len(), 1, "one arc painted");
        assert_eq!(later.len(), 1);
        assert!(
            (arc_start(&first[0]) - arc_start(&later[0])).abs() > 0.1,
            "a later frame draws the notch somewhere else, which is the animation"
        );
    }

    /// The whole reason the arc is painted rather than spun as text: `epaint`
    /// rounds a galley's position to a whole pixel before applying its angle,
    /// so a rotating glyph advances in 1px hops — it stands still for several
    /// frames and then jumps. A path is rounded nowhere, so equal slices of
    /// time move it by equal (and, here, sub-pixel) amounts.
    #[test]
    fn the_running_icon_turns_smoothly_rather_than_a_pixel_at_a_time() {
        let steps: Vec<f32> = (0..24)
            .map(|i| {
                let (_, now) = spun_frame(i as f64 * 0.004);
                now[0][0]
            })
            .collect::<Vec<_>>()
            .windows(2)
            .map(|w| (w[1] - w[0]).length())
            .collect();
        let (small, large) = steps
            .iter()
            .fold((f32::MAX, 0.0_f32), |(a, b), s| (a.min(*s), b.max(*s)));
        assert!(
            small > 0.0,
            "the arc stalled between frames, which is what pixel snapping looks like"
        );
        assert!(
            large < 1.0,
            "a 4ms step moved the arc {large}px — that is a jump, not a turn"
        );
        assert!(
            large / small < 1.5,
            "the arc moves {small}px on one step and {large}px on another, so it is turning in lurches"
        );
    }

    /// Turning must move the notch, not the ring. The ring also has to land
    /// exactly where the still icons' ink lands, or the spinner floats above
    /// or below the line its neighbours sit on.
    #[test]
    fn the_turning_icon_sits_still_and_on_the_line() {
        let still = still_icon_ink_centre();
        for time in [0.0, 0.4, 0.9, 1.7] {
            let (rect, shapes) = spun_frame(time);
            let arc = &shapes[0];
            let bbox = arc.iter().fold(egui::Rect::NOTHING, |b, p| {
                b.union(egui::Rect::from_pos(*p))
            });
            assert!(
                rect.contains_rect(bbox),
                "at t={time} the arc spills out of the {rect:?} it reserved: {bbox:?}"
            );
            let centre = ring_centre(arc);
            assert!(
                (centre - still).length() < 0.1,
                "at t={time} the ring is centred on {centre:?}, but a still icon's ink is at {still:?}"
            );
        }
    }

    /// Every Phosphor glyph is exactly one em wide, which is what stops a
    /// request row or a results-grid row from shifting sideways as its marker
    /// goes scheduled → running → finished. The turning icon has to reserve
    /// what the still ones do or it reintroduces the jitter.
    #[test]
    fn the_turning_icon_reserves_what_a_plain_icon_label_would() {
        let ctx = egui::Context::default();
        let plain = std::cell::Cell::new(egui::Rect::NOTHING);
        let _ = ctx.run_ui(a_frame(), |ui| {
            plain.set(
                ui.colored_label(egui::Color32::RED, super::super::icons::PASS)
                    .rect,
            );
        });
        let (spun, _) = spun_frame(0.5);
        let (a, b) = (plain.get().size(), spun.size());
        assert!(
            (a.x - b.x).abs() < 0.5 && (a.y - b.y).abs() < 0.5,
            "the turning icon reserved {b:?} where a still one reserves {a:?}"
        );
    }
}

/// What a [`dialog`] frame produced, and whether the user asked to close it.
///
/// `inner` is `None` when egui declined to draw the window at all — which is
/// not an answer, so callers keep the dialog armed rather than deciding for
/// the user.
pub(crate) struct DialogFrame<R> {
    pub inner: Option<R>,
    /// The user pressed Escape or clicked the window's ✕ this frame. Every
    /// dialog treats this as its cancel, so there is always a way out that
    /// doesn't involve finding the right button.
    pub dismissed: bool,
}

impl<R> DialogFrame<R> {
    /// The frame's answer, or `default` when egui drew nothing.
    pub fn inner_or(self, default: R) -> R {
        self.inner.unwrap_or(default)
    }
}

/// The modal window shell shared by every GUI dialog.
///
/// Behaves the way a desktop dialog is expected to: it opens centred but can
/// be dragged aside (an anchored dialog cannot be moved off whatever you
/// opened it to look at), it carries the two ways out a windowed dialog has —
/// a ✕ in the title bar and the Escape key, both reported as
/// [`DialogFrame::dismissed`] so the caller can run its own Cancel — and it
/// puts a dimmed, click-swallowing sheet over the app behind it.
///
/// That sheet blocks *input*, not the frame loop: the app keeps painting and
/// keeps polling its background work, so a git fetch or a report run started
/// before the dialog opened still finishes while it is up.
pub(crate) fn dialog<R>(
    ctx: &egui::Context,
    title: &str,
    min_width: Option<f32>,
    add: impl FnOnce(&mut egui::Ui) -> R,
) -> DialogFrame<R> {
    dialog_with(ctx, title, min_width, None, true, add)
}

/// A [`dialog`] without the sheet behind it, for the one case where the dialog
/// is *reporting* rather than *asking*: a long import that has everything it
/// needs and now only has to be waited for. The rest of the app stays usable
/// while it runs, because there is no question standing in the way of it.
pub(crate) fn dialog_modeless<R>(
    ctx: &egui::Context,
    title: &str,
    min_width: Option<f32>,
    add: impl FnOnce(&mut egui::Ui) -> R,
) -> DialogFrame<R> {
    dialog_with(ctx, title, min_width, None, false, add)
}

/// A [`dialog`] the user can resize, for the ones whose body is a list: how
/// much of a repo's files or a workspace's collections fits on screen is the
/// user's call, not a number picked here.
pub(crate) fn dialog_resizable<R>(
    ctx: &egui::Context,
    title: &str,
    default_size: [f32; 2],
    add: impl FnOnce(&mut egui::Ui) -> R,
) -> DialogFrame<R> {
    dialog_with(ctx, title, None, Some(default_size), true, add)
}

fn dialog_with<R>(
    ctx: &egui::Context,
    title: &str,
    min_width: Option<f32>,
    default_size: Option<[f32; 2]>,
    modal: bool,
    add: impl FnOnce(&mut egui::Ui) -> R,
) -> DialogFrame<R> {
    if modal {
        shade(ctx, title);
    }
    let mut open = true;
    let mut window = egui::Window::new(title)
        .collapsible(false)
        .resizable(default_size.is_some())
        // Centred on first sight, then wherever the user drags it.
        .pivot(egui::Align2::CENTER_CENTER)
        .default_pos(ctx.input(|i| i.content_rect()).center())
        // Above the sheet, which is itself above the panels.
        .order(egui::Order::Foreground)
        .open(&mut open);
    if let Some(size) = default_size {
        window = window.default_size(size);
    }
    // No dialog may be taller (or wider) than the window it sits in. A
    // resizable egui window sizes itself to its content, and content that is
    // laid out as "as much as I have" — a `ScrollArea` with `auto_shrink`
    // off — will happily ask for more than the screen has, at which point the
    // dialog runs off both ends at once and neither its heading nor its Close
    // button can be reached. Capping it hands the overflow back to the scroll
    // area, which is what was supposed to absorb it. The inset leaves the title
    // bar and drop shadow on-screen so the dialog can still be dragged.
    let content = ctx.input(|i| i.content_rect());
    window = window.max_size([
        (content.width() - 48.0).max(240.0),
        (content.height() - 48.0).max(160.0),
    ]);
    let shown = window.show(ctx, |ui| {
        if let Some(w) = min_width {
            ui.set_min_width(w);
        }
        add(ui)
    });
    // The sheet stops the *pointer*, but keyboard focus is a separate,
    // context-wide list: Tab out of the last field of a dialog and egui happily
    // walked on into the panels behind it, typing into a request the dialog was
    // asking about. Naming the dialog's layer as the modal one confines Tab and
    // the arrow keys to it, which is the behaviour every other desktop dialog
    // has. Registered after the window is shown because it is the window that
    // owns the layer; egui applies it from the next frame, as it does for its
    // own `Modal`.
    if modal && let Some(r) = &shown {
        ctx.memory_mut(|m| m.set_modal_layer(r.response.layer_id));
    }
    let inner = shown.and_then(|r| r.inner);
    // Escape is read from the raw input rather than consumed: a dialog is the
    // top-most thing on screen, so nothing underneath it should be acting on
    // the same press anyway.
    // Escape closes the ones that are asking something. A modeless dialog is
    // sitting beside work the user is still doing, and Escape there belongs to
    // whatever they are actually typing into.
    let esc = modal && ctx.input(|i| i.key_pressed(egui::Key::Escape));
    DialogFrame {
        inner,
        dismissed: !open || esc,
    }
}

/// The dimmed sheet between a dialog and the app: it darkens what is behind
/// and swallows every click, drag and scroll aimed at it, so the menu bar and
/// the panels cannot be driven while a dialog is waiting for an answer (which
/// is how a second wizard used to end up opened on top of the first).
///
/// Deliberately *only* an input sink — nothing here stops the frame loop, so
/// background work carries on and the app never looks hung.
fn shade(ctx: &egui::Context, title: &str) {
    let screen = ctx.input(|i| i.content_rect());
    egui::Area::new(egui::Id::new(("paperboy-dialog-shade", title)))
        .order(egui::Order::Middle)
        .fixed_pos(screen.min)
        .interactable(true)
        .show(ctx, |ui| {
            ui.painter()
                .rect_filled(screen, 0.0, egui::Color32::from_black_alpha(96));
            ui.allocate_response(screen.size(), egui::Sense::click_and_drag());
        });
}

#[cfg(test)]
mod function_menu_tests {
    use super::{egui, insert_call};
    use crate::generators::function;

    #[test]
    fn a_chosen_function_lands_at_the_caret_with_its_argument_selected() {
        let f = function("sha256").expect("sha256 is a generator function");
        // Caret between the two brackets of the outer call: the inner call is
        // written there, not tacked onto the end.
        let (text, from, to) = insert_call("base64()", Some(7), f);
        assert_eq!(text, "base64(sha256(text))");
        assert_eq!(
            &text[from..to],
            "text",
            "the argument name is selected, so typing fills it in"
        );
    }

    /// A call with more than one argument keeps the rest as a reminder of what
    /// is wanted, with only the first selected.
    #[test]
    fn every_argument_is_written_in_and_the_first_is_selected() {
        let f = function("hmac_sha256").expect("hmac_sha256 is a generator function");
        let (text, from, to) = insert_call("", None, f);
        assert_eq!(text, "hmac_sha256(key, message)");
        assert_eq!(&text[from..to], "key");
    }

    #[test]
    fn a_half_typed_name_is_replaced_rather_than_doubled() {
        let f = function("uuid").expect("uuid is a generator function");
        let (text, from, to) = insert_call("id = uu", Some(7), f);
        assert_eq!(text, "id = uuid");
        // Nothing to fill in, so the caret sits after the name and nothing is
        // selected.
        assert_eq!((from, to), (9, 9));
    }

    /// An edit made behind a text field's back is outside egui's own undo
    /// bookkeeping, which only records a point once the text has been still for
    /// a moment: without an explicit one, Ctrl+Z after choosing a function
    /// jumped back past the insert to whatever was last stable — usually an
    /// empty cell — and there was no redo to come back by.
    #[test]
    fn choosing_a_function_leaves_something_for_ctrl_z_to_undo() {
        use egui::text::{CCursor, CCursorRange};
        let ctx = egui::Context::default();
        let id = egui::Id::new("expr");
        let mut state = egui::widgets::text_edit::TextEditState::default();
        state
            .cursor
            .set_char_range(Some(CCursorRange::one(CCursor::new(7))));
        egui::TextEdit::store_state(&ctx, id, state);

        let mut text = "base64()".to_string();
        let f = function("sha256").expect("sha256 is a generator function");
        super::write_call(&ctx, id, &mut text, f);
        assert_eq!(text, "base64(sha256(text))");

        let state = egui::TextEdit::load_state(&ctx, id).expect("state was stored");
        assert_eq!(
            state
                .cursor
                .char_range()
                .map(|r| (r.secondary.index.0, r.primary.index.0)),
            Some((14, 18)),
            "the argument written in is selected, ready to be typed over"
        );
        let now = (
            CCursorRange::one(CCursor::new(18)),
            "base64(sha256(text))".to_string(),
        );
        assert_eq!(
            state.undoer().undo(&now).map(|(_, t)| t.as_str()),
            Some("base64()"),
            "one undo goes back to the expression as it was"
        );
    }

    #[test]
    fn a_field_never_clicked_into_appends() {
        let f = function("uuid").expect("uuid is a generator function");
        let (text, from, to) = insert_call("", None, f);
        assert_eq!(text, "uuid");
        assert_eq!((from, to), (4, 4));
    }
}