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
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
//! The top menu bar and the modal dialogs (open/save, rename, prompt) plus the
//! theme editor. Everything the terminal UI reaches through its `:`-menu and
//! wizards, driven through the shared [`crate::session::Session`].

use std::path::Path;

use eframe::egui;

use crate::i18n::{Language, Status, Strings};
use crate::request::RequestView;
use crate::session::PickerKind;
use crate::theme::{THEME_COLOR_COUNT, ThemeSpec, is_builtin};

use super::app::{Dialog, GuiApp, OpenKind, PromptKind, RenameTarget, SaveKind};

/// In-progress theme edit: the spec being edited plus the name it started with
/// (so applying can replace an existing custom theme rather than duplicate it).
pub struct ThemeEditState {
    pub spec: ThemeSpec,
    pub original_name: String,
}

// ── Alt-key menu mnemonics ──────────────────────────────────────────────────

/// Keyboard access to the top-level menus, following the convention every
/// desktop toolkit teaches: `Alt` on its own arms the menu bar and reveals each
/// menu's mnemonic letter, and the letter then opens that menu. `Alt+F` as a
/// single chord does the same thing in one go, because that is what most people
/// who know the pattern actually press.
///
/// The underlines only appear while armed. Showing them permanently puts three
/// pieces of keyboard trivia on screen for the whole session for the benefit of
/// the one moment someone wants them, which is exactly the sort of chrome the
/// rest of this restyle removed.
#[derive(Default)]
pub struct AltMenus {
    /// Alt has been pressed and released alone: the bar is armed and a letter
    /// will open a menu.
    armed: bool,
    /// Alt is currently held and nothing else has been pressed with it yet, so
    /// releasing it now counts as "Alt on its own" rather than as a chord.
    alt_alone: bool,
    alt_was_down: bool,
    /// Each menu's mnemonic and the widget id of its button, collected as the
    /// bar is drawn. egui ids are deterministic frame to frame, so a letter
    /// pressed now opens the menu registered on the previous frame.
    ids: Vec<(char, egui::Id)>,
}

impl AltMenus {
    /// Whether a lone `Alt` has put the bar into "waiting for a letter" mode.
    ///
    /// The underlines no longer depend on this — they are always drawn — so
    /// this is now only read by the tests that pin the arming state machine.
    #[cfg(test)]
    pub fn is_armed(&self) -> bool {
        self.armed
    }

    /// Note where a menu button ended up, so a mnemonic can open it.
    fn register(&mut self, mnemonic: char, id: egui::Id) {
        self.ids.retain(|(c, _)| *c != mnemonic);
        self.ids.push((mnemonic, id));
    }

    fn id_for(&self, c: char) -> Option<egui::Id> {
        self.ids
            .iter()
            .find(|(m, _)| m.eq_ignore_ascii_case(&c))
            .map(|(_, id)| *id)
    }
}

/// The first character of a mnemonic string, upper-cased. The i18n table holds
/// these as one-character strings so a translator can pick a letter that suits
/// their language's own words.
fn mnemonic_char(s: &str) -> Option<char> {
    s.chars().next().map(|c| c.to_ascii_uppercase())
}

/// Update the armed state from this frame's input, and open a menu if a
/// mnemonic was pressed.
///
/// Run *before* the buttons are drawn, so opening a menu takes effect on the
/// same frame the key arrives.
fn handle_menu_mnemonics(app: &mut GuiApp, ctx: &egui::Context) {
    // A text field having focus means the letters are being typed into it, not
    // aimed at the menu bar; arming would swallow them.
    if ctx.memory(|m| m.focused().is_some()) {
        app.alt_menus.armed = false;
        app.alt_menus.alt_alone = false;
        return;
    }

    struct Frame {
        alt_down: bool,
        escape: bool,
        // (letter, was Alt held) for each key pressed this frame.
        pressed: Vec<(char, bool)>,
    }
    let f = ctx.input(|i| Frame {
        alt_down: i.modifiers.alt,
        escape: i.key_pressed(egui::Key::Escape),
        pressed: i
            .events
            .iter()
            .filter_map(|e| match e {
                egui::Event::Key {
                    key,
                    pressed: true,
                    modifiers,
                    ..
                } => mnemonic_char(key.name()).map(|c| (c, modifiers.alt)),
                _ => None,
            })
            .collect(),
    });

    // egui reports modifier keys through `modifiers` rather than as key events,
    // so "was Alt pressed on its own" has to be read from the edges of that flag
    // plus whether anything else arrived while it was held.
    if f.alt_down && !app.alt_menus.alt_was_down {
        app.alt_menus.alt_alone = true;
    }
    if !f.pressed.is_empty() {
        app.alt_menus.alt_alone = false;
    }

    let mut opened = false;
    for (c, with_alt) in &f.pressed {
        // `Alt+F` as a chord, or `F` on its own once armed.
        if (*with_alt || app.alt_menus.armed)
            && let Some(id) = app.alt_menus.id_for(*c)
        {
            egui::Popup::open_id(ctx, id.with("popup"));
            opened = true;
            break;
        }
    }

    if opened || f.escape {
        app.alt_menus.armed = false;
        app.alt_menus.alt_alone = false;
    } else if !f.alt_down && app.alt_menus.alt_was_down && app.alt_menus.alt_alone {
        // Alt pressed and released with nothing in between: toggle, so a second
        // Alt puts the bar away again.
        app.alt_menus.armed = !app.alt_menus.armed;
        app.alt_menus.alt_alone = false;
    }
    app.alt_menus.alt_was_down = f.alt_down;
}

/// A menu title with its mnemonic underlined.
///
/// Drawn always, not only once `Alt` has armed the bar. Hiding the underlines
/// until Alt is tapped is a Windows convention that assumes you already know
/// the mnemonics are there — and here it left the menus looking as though they
/// had none, so nobody would think to press Alt to find out. The underline is
/// the only thing that advertises the feature, so it has to be visible before
/// the feature is used.
///
/// Falls back to the plain title when the mnemonic doesn't occur in the
/// translated title at all — a translator is free to pick a letter that isn't in
/// the word (Danish "Indstillinger" happens to start with its own), and an
/// underline drawn under the wrong character would be worse than none.
fn menu_title(ui: &egui::Ui, title: &str, mnemonic: char) -> egui::WidgetText {
    // Matched case-insensitively over the *original* title, so `pos` is a byte
    // index into the string actually being sliced below. Searching an
    // uppercased copy instead would drift the moment a language's uppercase
    // form has a different byte length from its lowercase one (German "ß" is
    // the classic; Turkish dotted "i" is the near miss), silently underlining
    // the wrong character.
    let Some((pos, matched)) = title
        .char_indices()
        .find(|(_, c)| c.to_uppercase().eq(mnemonic.to_uppercase()))
    else {
        return title.into();
    };
    let font = egui::TextStyle::Button.resolve(ui.style());
    let color = ui.visuals().widgets.inactive.fg_stroke.color;
    let mut job = egui::text::LayoutJob::default();
    let mut push = |s: &str, underline: bool| {
        if s.is_empty() {
            return;
        }
        job.append(
            s,
            0.0,
            egui::TextFormat {
                font_id: font.clone(),
                color,
                underline: if underline {
                    egui::Stroke::new(1.0, color)
                } else {
                    egui::Stroke::NONE
                },
                ..Default::default()
            },
        );
    };
    let end = pos + matched.len_utf8();
    push(&title[..pos], false);
    push(&title[pos..end], true);
    push(&title[end..], false);
    job.into()
}

// ── Menu bar ────────────────────────────────────────────────────────────────

pub fn menu_bar(app: &mut GuiApp, ui: &mut egui::Ui) {
    handle_menu_mnemonics(app, ui.ctx());
    egui::MenuBar::new().ui(ui, |ui| {
        file_menu(app, ui);
        edit_menu(app, ui);
        settings_menu(app, ui);
        view_menu(app, ui);
        help_menu(app, ui);
        // The status message rides along here, to the right of the menus,
        // exactly where the terminal UI draws it. See `GuiApp::status_message`
        // for why it is not in the status bar at the foot of the window.
        ui.add_space(16.0);
        app.status_message(ui);
        // No Send button here. There used to be one pinned to the right of this
        // bar, doing exactly what the Send beside the URL does (`run_active`) —
        // but it was drawn unconditionally, so in the report editor or a
        // workspace view it fired at whatever request happened to be selected
        // off-screen. One Send, next to the request it sends.
    });
}

/// The Help menu: a home for the keyboard-shortcuts overlay so F1 is not the
/// only way to find it. Discoverability was the whole complaint — a shortcut no
/// menu points at is a shortcut nobody knows exists — so the overlay earns a
/// visible entry, with its F1 accelerator shown the same way Save shows Ctrl+S.
fn help_menu(app: &mut GuiApp, ui: &mut egui::Ui) {
    let (title, mnemonic) = (app.strings.gui_menu_help, app.strings.gui_menu_help_key);
    top_menu(app, ui, title, mnemonic, |app, ui| {
        if ui
            .button(format!(
                "{}\t{}",
                app.strings.gui_shortcuts_title, app.strings.gui_shortcut_help
            ))
            .clicked()
        {
            app.dialog = Some(Dialog::Shortcuts);
            ui.close();
        }
    });
}

/// Draw one top-level menu button, registering its mnemonic so `Alt`+letter can
/// open it and underlining that letter.
fn top_menu<R>(
    app: &mut GuiApp,
    ui: &mut egui::Ui,
    title: &str,
    mnemonic: &str,
    content: impl FnOnce(&mut GuiApp, &mut egui::Ui) -> R,
) {
    let Some(m) = mnemonic_char(mnemonic) else {
        return;
    };
    let text = menu_title(ui, title, m);
    let resp = ui.menu_button(text, |ui| content(app, ui));
    app.alt_menus.register(m, resp.response.id);
}

/// The Edit menu. Currently just the one entry — undoing a request delete —
/// but that action needed a home somewhere more discoverable than "press `u`
/// in the terminal UI", and there was no existing menu that fit rather than
/// stretched to accommodate it (File is about whole files; Settings and View
/// are configuration, not an in-session action). A one-item menu is a fair
/// trade for that: the alternative was wedging it into the Requests panel's
/// header, which only the graphical front-end has and which was still less
/// discoverable than the standard place every editor puts "Undo".
fn edit_menu(app: &mut GuiApp, ui: &mut egui::Ui) {
    let (title, mnemonic) = (app.strings.gui_menu_edit, app.strings.gui_menu_edit_key);
    top_menu(app, ui, title, mnemonic, |app, ui| {
        let ci = app.active_ci();
        // Disabled rather than hidden when there's nothing to restore, so the
        // menu's shape doesn't shift under a user who opens it out of habit —
        // and so the one item in it is still there to explain what the
        // shortcut does even when it currently can't.
        let has_deleted = !app.session.collections[ci].deleted_entries.is_empty();
        if ui
            .add_enabled(
                has_deleted,
                egui::Button::new(format!(
                    "{}\t{}",
                    app.strings.gui_undo_delete_request, app.strings.gui_shortcut_undo_delete
                )),
            )
            .clicked()
        {
            app.undo_delete_request();
            ui.close();
        }
    });
}

/// The File menu. Grouped into submenus by *verb* (New / Open / Save) rather
/// than one flat list, because the local and Git variants of each had grown to
/// a dozen sibling entries where "open" and "save" items were interleaved.
///
/// The File menu, shaped the way the terminal's is: **what** first, **where**
/// second. "Open ▸ Workspace ▸ From a Postman account…" says what that import
/// produces, where a bare "From Postman…" sitting among the open commands left
/// the user to guess; and the same submenu is where "Local folder…" and "From
/// Git…" live, so the sources for a thing are listed together instead of being
/// spread over three top-level entries.
///
/// Import is the exception, and sits at the top level: it is the word someone
/// arriving from Postman scans for, and reaching it by way of "Open â–¸
/// Workspace" asks them to know what PaperBoy will make of their export before
/// they have made it.
fn file_menu(app: &mut GuiApp, ui: &mut egui::Ui) {
    let (title, mnemonic) = (app.strings.gui_menu_file, app.strings.gui_menu_file_key);
    top_menu(app, ui, title, mnemonic, |app, ui| {
        if ui.button(app.strings.gui_new_collection_ellipsis).clicked() {
            app.dialog = Some(Dialog::Prompt {
                kind: PromptKind::NewCollectionName,
                text: String::new(),
            });
            ui.close();
        }
        ui.separator();

        // Submenus close only themselves, leaving the File menu hanging open
        // over the app; every leaf sets this so the whole menu goes with it.
        let mut close_menu = false;

        // Import is its own top-level entry rather than a leaf three levels
        // down under Open â–¸ Workspace: "import" is the word someone arriving
        // from Postman looks for, and they will not find it by first deciding
        // that what they want is a workspace. Its two routes are named after
        // what the user has — a file they exported, or an account to connect
        // to — because that, not the transport, is what they can answer.
        ui.menu_button(app.strings.gui_menu_import, |ui| {
            if ui
                .button(app.strings.gui_menu_import_file)
                .on_hover_text(app.strings.help_menu_import_file)
                .clicked()
            {
                open_via_picker(app, OpenKind::PostmanExport);
                close_menu = true;
                ui.close();
            }
            if ui
                .button(app.strings.gui_menu_import_account)
                .on_hover_text(app.strings.help_menu_import_account)
                .clicked()
            {
                app.postman.open();
                close_menu = true;
                ui.close();
            }
        });
        ui.separator();
        ui.menu_button(app.strings.gui_menu_open, |ui| {
            ui.menu_button(app.strings.file_kind_collection, |ui| {
                if ui.button(app.strings.gui_menu_from_file).clicked() {
                    open_via_picker(app, OpenKind::Collection);
                    close_menu = true;
                    ui.close();
                }
                if ui.button(app.strings.gui_menu_from_git).clicked() {
                    app.remote.open_load();
                    close_menu = true;
                    ui.close();
                }
            });
            ui.menu_button(app.strings.file_kind_environment, |ui| {
                if ui.button(app.strings.gui_menu_from_file).clicked() {
                    open_via_picker(app, OpenKind::Environment);
                    close_menu = true;
                    ui.close();
                }
                // The same flow as a collection: which of the two arrived is
                // read off the file that was picked, not asked up front.
                if ui.button(app.strings.gui_menu_from_git).clicked() {
                    app.remote.open_load();
                    close_menu = true;
                    ui.close();
                }
            });
            ui.menu_button(app.strings.file_kind_report, |ui| {
                if ui.button(app.strings.gui_menu_from_file).clicked() {
                    open_via_picker(app, OpenKind::Report);
                    close_menu = true;
                    ui.close();
                }
                if ui.button(app.strings.gui_menu_from_git).clicked() {
                    app.remote.open_load_report();
                    close_menu = true;
                    ui.close();
                }
            });
            ui.menu_button(app.strings.file_kind_workspace, |ui| {
                if ui.button(app.strings.gui_menu_from_folder).clicked() {
                    open_via_picker(app, OpenKind::Workspace);
                    close_menu = true;
                    ui.close();
                }
                if ui.button(app.strings.gui_menu_from_git).clicked() {
                    app.remote.open_load_workspace();
                    close_menu = true;
                    ui.close();
                }
                // A Postman import produces a whole folder of collections and
                // environments — a workspace — so this is where it belongs.
                if ui.button(app.strings.gui_menu_from_postman).clicked() {
                    app.postman.open();
                    close_menu = true;
                    ui.close();
                }
            });
        });
        ui.separator();

        // Save writes straight to the file the thing came from; Save As always
        // asks. Keeping them apart is the point: the menu used to offer only
        // the asking kind, so saving a report you had just edited meant walking
        // through a file dialog to name the file it already had.
        let save_hint = if save_active_has_path(app) {
            app.strings.help_menu_save
        } else {
            app.strings.help_menu_save_unsaved
        };
        if ui
            .button(format!(
                "{}\t{}",
                app.strings.gui_menu_save, app.strings.gui_shortcut_save
            ))
            .on_hover_text(save_hint)
            .clicked()
        {
            save_active(app);
            close_menu = true;
            ui.close();
        }
        ui.menu_button(
            format!(
                "{}\t{}",
                app.strings.gui_menu_save_as, app.strings.gui_shortcut_save_as
            ),
            |ui| {
                ui.menu_button(app.strings.file_kind_collection, |ui| {
                    if ui.button(app.strings.gui_menu_to_file).clicked() {
                        save_via_picker(app, SaveKind::Collection);
                        close_menu = true;
                        ui.close();
                    }
                    if ui.button(app.strings.gui_menu_to_git).clicked() {
                        app.remote.open_save_collection(app.active_ci());
                        close_menu = true;
                        ui.close();
                    }
                });
                // Only offered where they can work: a report save needs a report in
                // the editor, and a workspace push needs a tab that came from git.
                let has_report = app.report_editor.is_some();
                ui.menu_button(app.strings.file_kind_report, |ui| {
                    if ui
                        .add_enabled(has_report, egui::Button::new(app.strings.gui_menu_to_file))
                        .clicked()
                    {
                        save_via_picker(app, SaveKind::Report);
                        close_menu = true;
                        ui.close();
                    }
                    if ui
                        .add_enabled(has_report, egui::Button::new(app.strings.gui_menu_to_git))
                        .clicked()
                    {
                        app.remote.open_save_report();
                        close_menu = true;
                        ui.close();
                    }
                });
                let ci = app.active_ci();
                let is_ws = app
                    .session
                    .collections
                    .get(ci)
                    .is_some_and(|c| c.workspace_git_origin.is_some());
                ui.menu_button(app.strings.file_kind_workspace, |ui| {
                    if ui
                        .add_enabled(is_ws, egui::Button::new(app.strings.gui_menu_to_git))
                        .clicked()
                    {
                        app.remote.open_save_workspace(ci);
                        close_menu = true;
                        ui.close();
                    }
                });
                ui.menu_button(app.strings.gui_menu_kind_response, |ui| {
                    if ui.button(app.strings.gui_menu_to_file).clicked() {
                        save_via_picker(app, SaveKind::Response);
                        close_menu = true;
                        ui.close();
                    }
                });
            },
        );
        ui.separator();

        if ui.button(app.strings.gui_set_base_url).clicked() {
            app.dialog = Some(Dialog::Prompt {
                kind: PromptKind::BaseUrl,
                text: app.session.vars.base_url.clone(),
            });
            ui.close();
        }
        ui.separator();

        if ui
            .button(format!(
                "{}\t{}",
                app.strings.gui_close_tab, app.strings.gui_shortcut_close_tab_key
            ))
            .clicked()
        {
            app.request_close_tab(app.active_ci());
            ui.close();
        }
        if ui.button(app.strings.gui_quit).clicked() {
            ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
        }

        if close_menu {
            ui.close();
        }
    });
}

fn settings_menu(app: &mut GuiApp, ui: &mut egui::Ui) {
    let (title, mnemonic) = (
        app.strings.gui_menu_settings,
        app.strings.gui_menu_settings_key,
    );
    top_menu(app, ui, title, mnemonic, |app, ui| {
        ui.menu_button(app.strings.gui_language, |ui| {
            for (lang, label) in [
                (Language::English, app.strings.lang_english),
                (Language::French, app.strings.lang_french),
                (Language::Danish, app.strings.lang_danish),
            ] {
                if ui.radio(app.session.language == lang, label).clicked() {
                    app.session.language = lang;
                    app.session.save();
                    ui.close();
                }
            }
        });
        ui.menu_button(app.strings.gui_theme_menu, |ui| {
            let active = app.session.active_theme.clone();
            for spec in app.session.all_themes() {
                let selected = active.as_deref() == Some(spec.name.as_str());
                if ui.radio(selected, &spec.name).clicked() {
                    app.session.active_theme = Some(spec.name.clone());
                    app.session.save();
                    ui.close();
                }
            }
            ui.separator();
            if ui.button(app.strings.gui_follow_language).clicked() {
                app.session.active_theme = None;
                app.session.save();
                ui.close();
            }
            ui.separator();
            if ui.button(app.strings.gui_new_custom_theme).clicked() {
                let mut spec = app.session.active_theme_spec();
                spec.name = unique_theme_name(app, app.strings.gui_custom);
                app.dialog = Some(Dialog::Theme(Box::new(ThemeEditState {
                    original_name: spec.name.clone(),
                    spec,
                })));
                ui.close();
            }
            let editable = active.as_ref().map(|n| !is_builtin(n)).unwrap_or(false);
            if ui
                .add_enabled(
                    editable,
                    egui::Button::new(app.strings.gui_edit_current_theme),
                )
                .clicked()
            {
                let spec = app.session.active_theme_spec();
                app.dialog = Some(Dialog::Theme(Box::new(ThemeEditState {
                    original_name: spec.name.clone(),
                    spec,
                })));
                ui.close();
            }
        });
        ui.separator();
        ui.colored_label(app.theme.dim, app.strings.gui_preferences);
        if ui
            .checkbox(
                &mut app.session.confirm_on_exit,
                app.strings.gui_confirm_on_exit,
            )
            .changed()
        {
            app.session.save();
        }
        if ui
            .checkbox(
                &mut app.session.confirm_on_clear,
                app.strings.gui_confirm_on_clear,
            )
            .changed()
        {
            app.session.save();
        }
        if ui
            .checkbox(
                &mut app.session.confirm_on_delete_env,
                app.strings.gui_confirm_delete_env,
            )
            .changed()
        {
            app.session.save();
        }
        if ui
            .checkbox(
                &mut app.session.confirm_on_delete_request,
                app.strings.gui_confirm_delete_request,
            )
            .changed()
        {
            app.session.save();
        }
        if ui
            .checkbox(
                &mut app.session.run_all_batch_mode,
                app.strings.gui_run_all_batch,
            )
            .changed()
        {
            app.session.save();
        }
        let mut hurl_default = app.session.default_request_view == RequestView::Hurl;
        if ui
            .checkbox(&mut hurl_default, app.strings.gui_default_code_hurl)
            .changed()
        {
            app.session.default_request_view = if hurl_default {
                RequestView::Hurl
            } else {
                RequestView::Json
            };
            app.show_hurl = hurl_default;
            app.session.save();
        }
    });
}

fn view_menu(app: &mut GuiApp, ui: &mut egui::Ui) {
    let (title, mnemonic) = (app.strings.gui_menu_view, app.strings.gui_menu_view_key);
    top_menu(app, ui, title, mnemonic, |app, ui| {
        if ui
            .radio(!app.show_reports, app.strings.gui_request_response)
            .clicked()
        {
            app.show_reports = false;
            ui.close();
        }
        if ui
            .radio(app.show_reports, app.strings.gui_reports)
            .clicked()
        {
            app.show_reports = true;
            ui.close();
        }
    });
}

fn unique_theme_name(app: &GuiApp, base: &str) -> String {
    let exists = |name: &str| app.session.all_themes().iter().any(|t| t.name == name);
    if !exists(base) {
        return base.to_string();
    }
    let mut n = 2;
    while exists(&format!("{base} {n}")) {
        n += 1;
    }
    format!("{base} {n}")
}

// ── Dialogs ─────────────────────────────────────────────────────────────────

pub fn show_dialog(app: &mut GuiApp, ctx: &egui::Context) {
    let Some(dialog) = app.dialog.take() else {
        return;
    };
    match dialog {
        Dialog::Rename { target, text } => rename_dialog(app, ctx, target, text),
        Dialog::ExtractParameter {
            ci,
            entry,
            target,
            value,
            range,
            name,
        } => extract_parameter_dialog(app, ctx, ci, entry, target, value, range, name),
        Dialog::Prompt { kind, text } => prompt_dialog(app, ctx, kind, text),
        Dialog::ProbeBuilder(builder) => probe_builder_dialog(app, ctx, builder),
        Dialog::Theme(state) => theme_dialog(app, ctx, *state),
        Dialog::CloseGitWorkspace { ci, root } => close_git_workspace_dialog(app, ctx, ci, root),
        Dialog::UnsavedQuit { count, tabs } => unsaved_quit_dialog(app, ctx, count, tabs),
        Dialog::UnsavedCloseTab { ci, name, count } => {
            unsaved_close_tab_dialog(app, ctx, ci, name, count)
        }
        Dialog::WorkspaceReload { ci, reload } => workspace_reload_dialog(app, ctx, ci, *reload),
        Dialog::ExportResults { path } => export_results_dialog(app, ctx, path),
        Dialog::RevertToSaved {
            ci,
            path,
            entry,
            name,
        } => revert_to_saved_dialog(app, ctx, ci, path, entry, name),
        Dialog::ConfirmDeleteRequest { ci, idx, name } => {
            confirm_delete_request_dialog(app, ctx, ci, idx, name)
        }
        Dialog::DeleteWorkspaceItem {
            ci,
            path,
            is_dir,
            name,
            file_count,
            unsaved,
        } => confirm_delete_workspace_item_dialog(
            app, ctx, ci, path, is_dir, name, file_count, unsaved,
        ),
        Dialog::ConfirmRunAll { ci, total, non_get } => {
            confirm_run_all_dialog(app, ctx, ci, total, non_get)
        }
        Dialog::Shortcuts => shortcuts_dialog(app, ctx),
    }
}

/// The response viewer's assert/capture builder.
///
/// Three steps in one window: pick a value the server actually sent, say what
/// should be true about it, and — for a capture — name the variable. Each step
/// leads with what it is asking for, because a bare list of `jsonpath "$" …`
/// lines says what the answers look like but never what the question was.
///
/// Picking and committing are separate. Rows are *selected* by a click and
/// acted on by the button (or a double-click, or Enter): a list where the first
/// click commits gives no chance to look at a row before choosing it, and the
/// whole point of this dialog is looking. Whatever is selected is highlighted
/// in the response body behind the dialog, so "which of these six tokens is
/// `$.data[0].token`?" is answered by looking rather than by reading paths.
///
/// Opened by right-clicking the response body (which pre-selects the value
/// under the caret) or from the Assert… button (which starts on the list).
fn probe_builder_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    mut builder: Box<super::probe::ProbeBuilder>,
) {
    let title = app.strings.gui_probe_title;
    let l = ProbeLabels::new(app);
    let strings = crate::i18n::Strings::mapped(&app.session.language, super::icons::drawable);
    let (dim, err, accent, text) = (
        app.theme.dim,
        app.theme.err,
        app.theme.accent,
        app.theme.text,
    );
    // What the frame decided, applied after it closes: the dialog body borrows
    // `builder`, and applying writes through `app` to the same session the
    // rows were built from.
    let mut back = false;
    let mut advance = false;
    let mut chosen_verb: Option<crate::probe::Verb> = None;
    let mut start_capture = false;
    let mut copy: Option<crate::probe::Probe> = None;
    let mut hovered: Option<crate::probe::Subject> = None;
    let selection = builder.selection.clone();
    // Wide enough that the title fits its own bar: an egui window shrinks to
    // its content, and this one's content is a list of short rows, so the
    // heading was being elided to "Assert or capture from the res…" — on the
    // one dialog whose whole job is to say what it is for.
    let frame = super::widgets::dialog(ctx, title, Some(520.0), |ui| {
        let mut keep = true;
        let (up, down, enter) = ui.input(|i| {
            (
                i.key_pressed(egui::Key::ArrowUp),
                i.key_pressed(egui::Key::ArrowDown),
                i.key_pressed(egui::Key::Enter),
            )
        });
        match (builder.chosen.clone(), builder.capture_name.clone()) {
            // Step one: which value?
            (None, _) => {
                step_heading(ui, accent, dim, l.step_subject, l.step_subject_hint);
                ui.add(
                    egui::TextEdit::singleline(&mut builder.filter)
                        .desired_width(f32::INFINITY)
                        .hint_text(l.filter),
                );
                ui.add_space(6.0);
                let rows: Vec<crate::probe::Probe> =
                    builder.visible().into_iter().cloned().collect();
                builder.selected = move_selection(builder.selected, rows.len(), up, down);
                let mut clicked: Option<usize> = None;
                egui::ScrollArea::vertical()
                    .max_height(300.0)
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        // Rows are one line each, clipped with an ellipsis
                        // rather than wrapped. A row ends in a value the server
                        // chose, and a 60-character bearer token holds no break
                        // opportunity, so wrapping tore the literal off after
                        // its opening quote and left a `"` sitting alone on a
                        // line. What the row is for is being scannable; the
                        // whole value is a highlight and a Copy value away.
                        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
                        // egui grows a hovered widget by a pixel, which in a
                        // list of rows means the row under the pointer -- and
                        // everything below it -- shifts as the pointer crosses
                        // it. Aiming at a moving row is exactly what this list
                        // must not ask for.
                        steady_rows(ui);
                        for (i, probe) in rows.iter().enumerate() {
                            let row = super::probe::subject_row(probe);
                            let widget = ui.selectable_label(
                                i == builder.selected,
                                egui::RichText::new(row).monospace(),
                            );
                            if widget.clicked() {
                                clicked = Some(i);
                            }
                            // Merely pointing at a row highlights its value in
                            // the response: the fastest way to answer "which of
                            // these is $.data[0].token?" is to run the pointer
                            // down the list and watch the body.
                            if widget.hovered() {
                                hovered = Some(probe.subject.clone());
                            }
                            // A double-click is the shortcut for people who
                            // already know which row they want.
                            if widget.double_clicked() {
                                clicked = Some(i);
                                advance = true;
                            }
                            if i == builder.selected && (up || down) {
                                widget.scroll_to_me(None);
                            }
                        }
                    });
                if let Some(i) = clicked {
                    builder.selected = i;
                }
                let picked = rows.get(builder.selected).cloned();
                ui.add_space(8.0);
                centred_row(ui, &[l.next, l.copy, l.cancel], |ui| {
                    if ui
                        .add_enabled(picked.is_some(), egui::Button::new(l.next))
                        .clicked()
                        || (enter && picked.is_some())
                    {
                        advance = true;
                    }
                    if ui
                        .add_enabled(picked.is_some(), egui::Button::new(l.copy))
                        .on_hover_text(l.copy_hint)
                        .clicked()
                    {
                        copy = picked.clone();
                    }
                    if ui.button(l.cancel).clicked() {
                        keep = false;
                    }
                });
                if advance {
                    builder.chosen = picked;
                }
            }
            // Step three: what should the captured value be called?
            (Some(probe), Some(mut name)) => {
                step_heading(ui, accent, dim, l.step_name, l.step_name_hint);
                chosen_value(ui, &probe, l.selected, dim, text);
                ui.add_space(6.0);
                let resp = ui.add(
                    egui::TextEdit::singleline(&mut name)
                        .desired_width(320.0)
                        .hint_text(l.name),
                );
                let submit = resp.lost_focus() && enter;
                // The row exactly as it will be written, so the name being
                // typed is visibly the left-hand side of a real `[Captures]`
                // line rather than an answer to an unexplained prompt.
                let row = crate::probe::capture_row(&probe.subject, &name);
                ui.add_space(4.0);
                ui.label(
                    egui::RichText::new(format!("{}: {}", row.0, row.1))
                        .monospace()
                        .color(dim),
                );
                builder.capture_name = Some(name);
                // Set when Add was pressed on an empty name: say why nothing was
                // written rather than let the whole dialog vanish silently.
                if builder.name_required {
                    ui.colored_label(err, l.name_required);
                }
                ui.add_space(8.0);
                centred_row(ui, &[l.back, l.add_capture, l.copy, l.cancel], |ui| {
                    if ui.button(l.back).clicked() {
                        back = true;
                    }
                    if ui.button(l.add_capture).clicked() || submit {
                        chosen_verb = Some(crate::probe::Verb::Capture);
                    }
                    if ui.button(l.copy).on_hover_text(l.copy_hint).clicked() {
                        copy = Some(probe.clone());
                    }
                    if ui.button(l.cancel).clicked() {
                        keep = false;
                    }
                });
            }
            // Step two: what about it?
            (Some(probe), None) => {
                step_heading(ui, accent, dim, l.step_verb, l.step_verb_hint);
                chosen_value(ui, &probe, l.selected, dim, text);
                ui.add_space(6.0);
                builder.selected_verb =
                    move_selection(builder.selected_verb, builder.verbs.len(), up, down);
                let mut clicked: Option<usize> = None;
                egui::ScrollArea::vertical()
                    .max_height(260.0)
                    .auto_shrink([false, true])
                    .show(ui, |ui| {
                        // Rows are one line each, clipped with an ellipsis
                        // rather than wrapped. A row ends in a value the server
                        // chose, and a 60-character bearer token holds no break
                        // opportunity, so wrapping tore the literal off after
                        // its opening quote and left a `"` sitting alone on a
                        // line. What the row is for is being scannable; the
                        // whole value is a highlight and a Copy value away.
                        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
                        // egui grows a hovered widget by a pixel, which in a
                        // list of rows means the row under the pointer -- and
                        // everything below it -- shifts as the pointer crosses
                        // it. Aiming at a moving row is exactly what this list
                        // must not ask for.
                        steady_rows(ui);
                        for (i, verb) in builder.verbs.iter().enumerate() {
                            let row = super::probe::verb_row(&probe.subject, verb, &strings);
                            let widget = ui.selectable_label(
                                i == builder.selected_verb,
                                egui::RichText::new(row).monospace(),
                            );
                            if widget.clicked() {
                                clicked = Some(i);
                            }
                            if widget.double_clicked() {
                                clicked = Some(i);
                                advance = true;
                            }
                        }
                    });
                if let Some(i) = clicked {
                    builder.selected_verb = i;
                }
                if enter {
                    advance = true;
                }
                // Choosing a capture is not the end of the dialog -- it still
                // needs a name -- so the button says so rather than promising
                // to add something and then asking another question.
                let commit = match builder.verbs.get(builder.selected_verb) {
                    Some(crate::probe::Verb::Capture) => l.next,
                    _ => l.add_assert,
                };
                ui.add_space(8.0);
                centred_row(ui, &[l.back, commit, l.copy, l.cancel], |ui| {
                    if ui.button(l.back).clicked() {
                        back = true;
                    }
                    if ui.button(commit).clicked() {
                        advance = true;
                    }
                    if ui.button(l.copy).on_hover_text(l.copy_hint).clicked() {
                        copy = Some(probe.clone());
                    }
                    if ui.button(l.cancel).clicked() {
                        keep = false;
                    }
                });
                if advance {
                    match builder.verbs.get(builder.selected_verb) {
                        Some(crate::probe::Verb::Capture) => start_capture = true,
                        Some(other) => chosen_verb = Some(other.clone()),
                        None => {}
                    }
                }
            }
        }
        keep
    });
    // A frame egui never drew is not an answer: keep the dialog open.
    if frame.dismissed || !frame.inner_or(true) {
        return;
    }
    if let Some(probe) = copy {
        if let Some(text) = super::probe::value_text(app, &probe) {
            ctx.copy_text(text);
            app.session.status = Some(crate::i18n::Status::Copied);
        }
    }
    if advance
        && builder.capture_name.is_none()
        && builder.chosen.is_some()
        && builder.verbs.is_empty()
    {
        // Just arrived on step two: work out what can be said about the value.
        let probe = builder.chosen.clone().expect("checked above");
        builder.verbs = crate::probe::verbs_for(&probe, selection.as_deref());
        builder.selected_verb = 0;
    } else if back {
        // Back from the name field returns to the verbs, not all the way out:
        // one step per press, like the terminal UI's Esc.
        if builder.capture_name.take().is_none() {
            builder.chosen = None;
            builder.verbs.clear();
        }
    } else if start_capture {
        let subject = builder.chosen.as_ref().map(|p| p.subject.clone());
        if let Some(subject) = subject {
            builder.name_required = false;
            builder.capture_name = Some(super::probe::suggested_name(app, &builder, &subject));
        }
    } else if let Some(verb) = chosen_verb {
        let name = builder.capture_name.clone().unwrap_or_default();
        // An empty capture name is refused by `apply`; closing the dialog on
        // that refusal threw away three steps of work with nothing to show for
        // it. Keep the dialog up and flag why. Any other outcome — written, or
        // a duplicate that is already there — is done, so close.
        if matches!(verb, crate::probe::Verb::Capture) && name.trim().is_empty() {
            builder.name_required = true;
        } else {
            super::probe::apply(app, &builder, &verb, &name);
            return;
        }
    }
    // Show which value the dialog is talking about, in the response itself.
    // Only on a change: rewriting the field's selection every frame would take
    // it away from anything else that touches it.
    let showing = hovered
        .or_else(|| builder.chosen.as_ref().map(|p| p.subject.clone()))
        .or_else(|| {
            builder
                .visible()
                .get(builder.selected)
                .map(|p| p.subject.clone())
        });
    if showing != builder.highlighted
        && let Some(subject) = showing.clone()
    {
        super::probe::highlight(app, ctx, &subject);
    }
    builder.highlighted = showing;
    app.dialog = Some(Dialog::ProbeBuilder(builder));
}

/// The builder's labels, read out of `app` once so the dialog body can borrow
/// the builder mutably without holding a second borrow of the app.
struct ProbeLabels {
    back: &'static str,
    add_assert: &'static str,
    add_capture: &'static str,
    cancel: &'static str,
    filter: &'static str,
    name: &'static str,
    name_required: &'static str,
    step_subject: &'static str,
    step_subject_hint: &'static str,
    step_verb: &'static str,
    step_verb_hint: &'static str,
    step_name: &'static str,
    step_name_hint: &'static str,
    selected: &'static str,
    copy: &'static str,
    copy_hint: &'static str,
    next: &'static str,
}

impl ProbeLabels {
    fn new(app: &GuiApp) -> Self {
        Self {
            back: app.strings.gui_probe_back,
            add_assert: app.strings.gui_probe_add_assert,
            add_capture: app.strings.gui_probe_add_capture,
            cancel: app.strings.gui_cancel,
            filter: app.strings.gui_probe_filter_hint,
            name: app.strings.probe_capture_name_title,
            name_required: app.strings.gui_probe_name_required,
            step_subject: app.strings.gui_probe_step_subject,
            step_subject_hint: app.strings.gui_probe_step_subject_hint,
            step_verb: app.strings.gui_probe_step_verb,
            step_verb_hint: app.strings.gui_probe_step_verb_hint,
            step_name: app.strings.gui_probe_step_name,
            step_name_hint: app.strings.gui_probe_step_name_hint,
            selected: app.strings.gui_probe_selected,
            copy: app.strings.gui_probe_copy_value,
            copy_hint: app.strings.gui_probe_copy_value_hint,
            next: app.strings.gui_probe_next,
        }
    }
}

/// A step's "what am I being asked?" header: the question, then one line of
/// what the answer will do.
fn step_heading(ui: &mut egui::Ui, accent: egui::Color32, dim: egui::Color32, q: &str, hint: &str) {
    ui.label(egui::RichText::new(q).strong().color(accent));
    ui.colored_label(dim, hint);
    ui.add_space(6.0);
}

/// The value the later steps are about, restated: by step two the list is gone,
/// and "what did I click?" should not need the dialog to be reopened.
fn chosen_value(
    ui: &mut egui::Ui,
    probe: &crate::probe::Probe,
    lbl: &str,
    dim: egui::Color32,
    text: egui::Color32,
) {
    ui.horizontal_wrapped(|ui| {
        ui.colored_label(dim, format!("{lbl}:"));
        ui.label(
            egui::RichText::new(crate::probe::subject_label(&probe.subject))
                .monospace()
                .strong()
                .color(text),
        );
        let value = crate::probe::value_preview(probe.value.as_ref(), 60);
        if !value.is_empty() {
            ui.label(egui::RichText::new(value).monospace().color(dim));
        }
    });
}

/// Rows that do not move when the pointer crosses them.
///
/// egui expands a hovered (and a pressed) widget by a pixel, which is a nice
/// touch on a button and unusable in a list: the row under the pointer grows,
/// pushing every row below it down, so the thing being aimed at moves out from
/// under the aim.
fn steady_rows(ui: &mut egui::Ui) {
    let widgets = &mut ui.style_mut().visuals.widgets;
    widgets.hovered.expansion = 0.0;
    widgets.active.expansion = 0.0;
    // A `selectable_label` is a `Button`, and a button's outline is part of
    // what it measures. An *unselected, unhovered* row is the one state egui
    // draws with no frame at all, so any stroke width on the others made the
    // row grow the moment it was hovered or selected -- pushing every row
    // below it down, under a pointer that was aiming at one of them. Both
    // states still read clearly through their fill.
    for state in [
        &mut widgets.inactive,
        &mut widgets.hovered,
        &mut widgets.active,
        &mut widgets.open,
    ] {
        state.bg_stroke.width = 0.0;
    }
}

/// A row of buttons centred in the dialog rather than left-aligned against it.
///
/// egui lays a `horizontal` out from the left edge, and the width has to be
/// known before the buttons are added to place them anywhere else -- so the
/// labels are measured first, in the same text style the buttons will use.
fn centred_row(ui: &mut egui::Ui, labels: &[&str], add: impl FnOnce(&mut egui::Ui)) {
    let font = egui::TextStyle::Button.resolve(ui.style());
    let padding = ui.spacing().button_padding.x * 2.0;
    let gap = ui.spacing().item_spacing.x;
    let width: f32 = labels
        .iter()
        .map(|t| {
            let galley = ui.painter().layout_no_wrap(
                t.to_string(),
                font.clone(),
                egui::Color32::PLACEHOLDER,
            );
            galley.size().x + padding
        })
        .sum::<f32>()
        + gap * labels.len().saturating_sub(1) as f32;
    ui.horizontal(|ui| {
        let slack = ui.available_width() - width;
        if slack > 0.0 {
            ui.add_space(slack / 2.0);
        }
        add(ui);
    });
}

/// Arrow-key movement over a list of `len` rows, clamped at both ends.
///
/// Clamped rather than wrapping: a list this short is read top to bottom, and
/// arriving back at the top after the last row reads as a lost keypress.
fn move_selection(selected: usize, len: usize, up: bool, down: bool) -> usize {
    if len == 0 {
        return 0;
    }
    let mut i = selected.min(len - 1);
    if up {
        i = i.saturating_sub(1);
    }
    if down {
        i = (i + 1).min(len - 1);
    }
    i
}

/// Confirm deleting a request. Gated on `confirm_on_delete_request`; the delete
/// records an undo step, so cancelling re-arms the dialog (a click outside must
/// not be able to lose the request either) while confirming removes it and
/// leaves it recoverable via Undo Delete Request / Ctrl+Z.
fn confirm_delete_request_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    idx: usize,
    name: String,
) {
    let title = app.strings.gui_delete_request_title;
    let (go, cancel, question) = (
        app.strings.gui_delete,
        app.strings.gui_cancel,
        app.strings.confirm_delete_request_q.replace("{r}", &name),
    );
    let mut decided = false;
    let dismissed = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            if ui.button(go).clicked() {
                app.delete_request_now(ci, idx);
                decided = true;
            }
            if ui.button(cancel).clicked() {
                decided = true;
            }
        });
    })
    .dismissed;
    decided |= dismissed;
    if !decided {
        app.dialog = Some(Dialog::ConfirmDeleteRequest { ci, idx, name });
    }
}

/// Confirm deleting a workspace file or folder from disk.
///
/// Unlike the request delete above, this is *not* gated on the
/// `confirm_on_delete_request` preference and can never be turned off: that
/// preference guards an undoable in-memory delete, whereas this removes a file
/// — or a whole folder's worth of them — from disk with no undo, so it must
/// always ask. The prompt says what is about to go: a folder's file count so
/// the size of the loss is visible, and a warning when there are unsaved edits
/// under the item that the delete would take with it. Cancelling (or dismissing)
/// re-arms the dialog so a stray click outside can't delete by default;
/// confirming performs the delete and its fix-up.
#[allow(clippy::too_many_arguments)]
fn confirm_delete_workspace_item_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    path: std::path::PathBuf,
    is_dir: bool,
    name: String,
    file_count: usize,
    unsaved: bool,
) {
    let title = app.strings.gui_ws_delete_title;
    let go = app.strings.gui_delete;
    let cancel = app.strings.gui_cancel;
    let question = if is_dir {
        app.strings
            .confirm_delete_ws_folder_q
            .replace("{name}", &name)
            .replace("{n}", &file_count.to_string())
    } else {
        app.strings
            .confirm_delete_ws_file_q
            .replace("{name}", &name)
    };
    let unsaved_note = unsaved.then_some(app.strings.confirm_delete_ws_unsaved);
    let mut decided = false;
    let dismissed = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        if let Some(note) = unsaved_note {
            ui.add_space(4.0);
            ui.colored_label(app.theme.err, note);
        }
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            if ui.button(go).clicked() {
                super::requests::delete_workspace_item(app, ci, &path);
                decided = true;
            }
            if ui.button(cancel).clicked() {
                decided = true;
            }
        });
    })
    .dismissed;
    decided |= dismissed;
    if !decided {
        app.dialog = Some(Dialog::DeleteWorkspaceItem {
            ci,
            path,
            is_dir,
            name,
            file_count,
            unsaved,
        });
    }
}

/// Confirm a "Run All" that would fire non-GET requests. The count of how many
/// will run — and how many of those are not GET — is the whole point: it turns
/// "run everything" from a leap into an informed choice, so a collection full
/// of writes isn't one stray click from executing. Cancelling re-arms nothing
/// (there is nothing to lose by dismissing); confirming runs the collection.
fn confirm_run_all_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    total: usize,
    non_get: usize,
) {
    let title = app.strings.gui_run_all_confirm_title;
    let (go, cancel, question) = (
        app.strings.gui_run_all,
        app.strings.gui_cancel,
        app.strings
            .confirm_run_all_q
            .replace("{n}", &total.to_string())
            .replace("{m}", &non_get.to_string()),
    );
    let mut answered: Option<bool> = None;
    let dismissed = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            if ui.button(go).clicked() {
                answered = Some(true);
            }
            if ui.button(cancel).clicked() {
                answered = Some(false);
            }
        });
    })
    .dismissed;
    if dismissed {
        answered = Some(false);
    }
    match answered {
        Some(true) => {
            app.session.run_all_entries(ci);
        }
        Some(false) => {}
        // No answer yet (egui drew nothing, or the user hasn't clicked): keep
        // the dialog armed rather than deciding for them.
        None => app.dialog = Some(Dialog::ConfirmRunAll { ci, total, non_get }),
    }
}

/// The F1 keyboard-shortcuts overlay: every GUI shortcut, grouped, with a short
/// description. Built from [`super::shortcut_help_sections`] so it can never
/// drift from the keys the app actually binds, and dismissed with Escape or the
/// close button like every other modal.
fn shortcuts_dialog(app: &mut GuiApp, ctx: &egui::Context) {
    let title = app.strings.gui_shortcuts_title;
    let sections = super::shortcut_help_sections(&app.strings);
    let theme = app.theme;
    let close_lbl = app.strings.gui_close;
    let mut close = false;
    // Sized to its content rather than resizable. This is a reference card, not
    // a workspace: there is nothing in it worth dragging bigger, and being
    // resizable was what let it grow. `egui` remembers a resizable window's
    // size across runs, so leaving it resizable would also have left anyone who
    // had already seen the oversized version still looking at it.
    let list_max_h = (ctx.input(|i| i.content_rect()).height() * 0.65).max(200.0);
    let dismissed = super::widgets::dialog(ctx, title, Some(420.0), |ui| {
        egui::ScrollArea::vertical()
            // Shrink to the content vertically, but not horizontally: the grid
            // wants the full dialog width so its two columns line up down the
            // whole overlay, while its height should be the height of the list.
            // `false` on this axis made the scroll area claim every pixel it
            // could be given, so the dialog filled the screen with most of it
            // blank and ran its heading and Close button off both ends at once.
            .auto_shrink([false, true])
            // ...and a ceiling, so a list longer than the screen scrolls inside
            // the dialog instead of pushing Close out of the bottom of it.
            .max_height(list_max_h)
            .show(ui, |ui| {
                for (i, section) in sections.iter().enumerate() {
                    if i > 0 {
                        ui.add_space(8.0);
                    }
                    ui.colored_label(theme.accent, section.title);
                    ui.add_space(2.0);
                    egui::Grid::new(("shortcuts_grid", i))
                        .num_columns(2)
                        .spacing([18.0, 4.0])
                        .show(ui, |ui| {
                            for (keys, desc) in &section.rows {
                                ui.colored_label(theme.text, egui::RichText::new(*keys).strong());
                                ui.colored_label(theme.dim, *desc);
                                ui.end_row();
                            }
                        });
                }
            });
        ui.add_space(8.0);
        ui.separator();
        ui.horizontal(|ui| {
            if ui.button(close_lbl).clicked() {
                close = true;
            }
        });
    })
    .dismissed;
    // Not re-armed on close: the overlay is a reference the user is done with,
    // not a question waiting on an answer.
    if !(close || dismissed) {
        app.dialog = Some(Dialog::Shortcuts);
    }
}

/// Confirm discarding a request's (or a whole workspace file's) in-memory edits
/// in favour of what is on disk. Cancelling re-arms the dialog, like every
/// other destructive confirmation here, so a click outside can't lose an edit.
fn revert_to_saved_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    path: std::path::PathBuf,
    entry: Option<usize>,
    name: String,
) {
    let title = app.strings.gui_revert_title;
    let (go, cancel, question) = (
        app.strings.gui_revert_go,
        app.strings.gui_cancel,
        match entry {
            Some(_) => app.strings.confirm_revert_request_q.replace("{r}", &name),
            None => app.strings.confirm_revert_file_q.replace("{f}", &name),
        },
    );
    let mut decided = false;
    let dismissed = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            if ui.button(go).clicked() {
                match entry {
                    Some(ei) => {
                        // Declining here means the file changed under us since
                        // the pre-check; the dialog has already been confirmed,
                        // so the status line is the only place left to say so.
                        app.session.status = match app.session.collections[ci].revert_request(ei) {
                            Some(_) => Some(crate::i18n::Status::RequestReverted(name.clone())),
                            None => Some(crate::i18n::Status::NothingToRevert),
                        };
                    }
                    None => {
                        let _ = app.session.collections[ci].revert_workspace_file(&path);
                    }
                }
                decided = true;
            }
            if ui.button(cancel).clicked() {
                decided = true;
            }
        });
    })
    .dismissed;
    decided |= dismissed;
    if !decided {
        app.dialog = Some(Dialog::RevertToSaved {
            ci,
            path,
            entry,
            name,
        });
    } else {
        app.session.save();
    }
}

/// Pick the file *and* the format a report's results are exported as.
///
/// The format lives beside the name because it *is* the name: every writer is
/// chosen by extension (see [`crate::report::writer::writer_for_extension`]),
/// so choosing Excel has to make the file end `.xlsx` or the choice is a lie.
/// The native picker's filter dropdown could not do that — it filters what the
/// dialog lists and nothing more — so it sat in the far corner appearing to do
/// nothing. Browse… still hands off to the native picker for people who want to
/// go looking for a folder.
fn export_results_dialog(app: &mut GuiApp, ctx: &egui::Context, mut path: String) {
    let title = app.strings.gui_save_results_title;
    let (lbl_export, lbl_cancel, lbl_browse, lbl_format) = (
        app.strings.gui_report_export_go,
        app.strings.gui_cancel,
        app.strings.gui_browse,
        app.strings.gui_report_export_format,
    );
    let mut act = ExportChoice::Keep;
    let theme_dim = app.theme.dim;
    let answered = modal(ctx, title, |ui| {
        ui.horizontal(|ui| {
            ui.colored_label(theme_dim, lbl_format);
            let current = std::path::Path::new(&path)
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("")
                .to_ascii_lowercase();
            egui::ComboBox::from_id_salt("pb_export_format")
                .selected_text(format_label(&current))
                .show_ui(ui, |ui| {
                    for ext in crate::report::writer::OUTPUT_EXTENSIONS {
                        if ui
                            .selectable_label(ext == current, format_label(ext))
                            .clicked()
                            && ext != current
                        {
                            path = retarget_extension(&path, ext);
                        }
                    }
                });
        });
        let resp = ui.add(
            egui::TextEdit::singleline(&mut path)
                .desired_width(420.0)
                .hint_text(".csv / .json / .html / .xlsx"),
        );
        let entered = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
        ui.horizontal(|ui| {
            if ui.button(lbl_browse).clicked() {
                act = ExportChoice::Browse;
            }
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if ui.button(lbl_cancel).clicked() {
                    act = ExportChoice::Cancel;
                }
                if ui.button(lbl_export).clicked() || entered {
                    act = ExportChoice::Write;
                }
            });
        });
    });
    // A frame egui never drew is not an answer: keep the dialog armed.
    if answered.inner.is_none() {
        act = ExportChoice::Keep;
    }
    if answered.dismissed {
        act = ExportChoice::Cancel;
    }
    match act {
        ExportChoice::Keep => app.dialog = Some(Dialog::ExportResults { path }),
        ExportChoice::Cancel => {}
        ExportChoice::Browse => save_via_picker(app, SaveKind::ReportResults),
        ExportChoice::Write => {
            match export_report_results(app, &path) {
                Ok(()) => {
                    app.session.status = Some(crate::i18n::Status::Saved);
                }
                // A failed export leaves the dialog open with the name still in
                // it: the fix is nearly always a word in that name.
                Err(e) => {
                    app.session.status = Some(crate::i18n::Status::Error(e));
                    app.dialog = Some(Dialog::ExportResults { path });
                }
            }
        }
    }
}

/// What [`export_results_dialog`] decided this frame.
enum ExportChoice {
    /// No answer yet — re-arm the dialog unchanged.
    Keep,
    Cancel,
    /// Hand over to the native save picker.
    Browse,
    Write,
}

/// The display name for an export format, from its extension.
fn format_label(ext: &str) -> &'static str {
    match ext {
        "json" => "JSON",
        "html" | "htm" => "HTML",
        "xlsx" => "Excel",
        "pdf" => "PDF",
        "csv" => "CSV",
        // An unknown extension is shown as itself rather than silently
        // corrected: the name in the box is the user's, and the Export button
        // is what tells them the format isn't one PaperBoy writes.
        _ => "—",
    }
}

/// Rewrite `path`'s extension to `ext`, keeping everything else.
///
/// A path with no extension gains one rather than being left alone — a name
/// typed as `results` still has to become `results.csv` for a writer to be
/// found for it.
fn retarget_extension(path: &str, ext: &str) -> String {
    let p = std::path::Path::new(path);
    if p.as_os_str().is_empty() {
        return format!("results.{ext}");
    }
    p.with_extension(ext).to_string_lossy().into_owned()
}

/// Last chance before quitting throws away request edits that were never
/// written to a file.
///
/// A Workspace tab's requests are deliberately not persisted between runs (see
/// `persistence`), and edits parked for a file the user has switched away from
/// live only in memory, so "quit" really is the moment they disappear — hence a
/// modal rather than a status line. Cancelling re-arms nothing: the close was
/// already refused, so there is simply nothing left to do.
fn unsaved_quit_dialog(app: &mut GuiApp, ctx: &egui::Context, count: usize, tabs: String) {
    let title = app.strings.gui_unsaved_quit_title;
    let (quit, cancel, question) = (
        app.strings.gui_quit_anyway,
        app.strings.gui_cancel,
        app.strings
            .gui_unsaved_quit_q
            .replace("{n}", &count.to_string())
            .replace("{t}", &tabs),
    );
    let save_all = app.strings.gui_save_all_and_quit;
    let mut decided = false;
    let mut save_then_quit = false;
    let decided = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            // Offered first: it is the only answer that keeps the work, so it
            // should be the one the eye lands on before "Quit anyway".
            if ui.button(save_all).clicked() {
                save_then_quit = true;
                decided = true;
            }
            if ui.button(quit).clicked() {
                app.allow_close = true;
                ctx.send_viewport_cmd(egui::ViewportCommand::Close);
                decided = true;
            }
            if ui.button(cancel).clicked() {
                decided = true;
            }
        });
    })
    .dismissed
        || decided;
    if save_then_quit {
        // A save that fails must not take the app down with it -- the dialog
        // comes back reporting the file that refused, so the work is still
        // there to be dealt with.
        match app.save_all_unsaved_edits() {
            Ok(_) => {
                app.allow_close = true;
                ctx.send_viewport_cmd(egui::ViewportCommand::Close);
            }
            Err(e) => {
                app.session.status = Some(crate::i18n::Status::Error(e));
                app.dialog = Some(Dialog::UnsavedQuit { count, tabs });
            }
        }
        return;
    }
    if !decided {
        app.dialog = Some(Dialog::UnsavedQuit { count, tabs });
    }
}

/// The same warning for one tab. Confirming hands over to the ordinary close
/// path, so a downloaded git Workspace still gets its keep-or-delete question.
fn unsaved_close_tab_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    name: String,
    count: usize,
) {
    let title = app.strings.gui_unsaved_quit_title;
    let (close, cancel, question) = (
        app.strings.gui_close_anyway,
        app.strings.gui_cancel,
        app.strings
            .gui_unsaved_close_tab_q
            .replace("{n}", &count.to_string())
            .replace("{t}", &name),
    );
    let mut decided = false;
    let dismissed = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            if ui.button(close).clicked() {
                app.close_tab_now(ci);
                decided = true;
            }
            if ui.button(cancel).clicked() {
                decided = true;
            }
        });
    })
    .dismissed;
    decided |= dismissed;
    if !decided {
        app.dialog = Some(Dialog::UnsavedCloseTab { ci, name, count });
    } else {
        app.session.save();
    }
}

/// Keep-or-delete prompt for a Workspace folder PaperBoy downloaded itself.
/// Cancel re-arms the dialog so an accidental click outside can't close the tab.
fn close_git_workspace_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    root: std::path::PathBuf,
) {
    let title = app.strings.gui_close_git_workspace_title;
    let (keep, delete, cancel, question) = (
        app.strings.close_git_workspace_keep,
        app.strings.close_git_workspace_delete,
        app.strings.close_git_workspace_cancel,
        app.strings
            .close_git_workspace_q
            .replace("{p}", &root.display().to_string()),
    );
    let mut decided = false;
    let dismissed = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            if ui.button(keep).clicked() {
                app.session.close_tab(ci);
                decided = true;
            }
            if ui.button(delete).clicked() {
                app.session.close_tab_deleting_workspace(ci);
                decided = true;
            }
            if ui.button(cancel).clicked() {
                decided = true;
            }
        });
    })
    .dismissed;
    decided |= dismissed;
    if !decided {
        app.dialog = Some(Dialog::CloseGitWorkspace { ci, root });
    } else {
        app.session.save();
    }
}

/// Offer to redownload a restored Workspace whose folder has vanished. Declining
/// leaves the tab in place but empty — the recorded origin stays on it, so the
/// same offer comes back next launch.
fn workspace_reload_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    reload: crate::persistence::PendingWorkspaceReload,
) {
    let title = app.strings.gui_workspace_reload_title;
    let ref_label = if reload.origin.ref_kind == crate::git_remote::RefKind::Branch {
        app.strings.git_branches
    } else {
        app.strings.git_tags
    };
    let question = app
        .strings
        .workspace_reload_confirm_q
        .replace("{name}", &reload.tab_name)
        .replace(
            "{ref}",
            &format!("[{ref_label}] {}", reload.origin.ref_name),
        )
        .replace("{url}", &reload.origin.repo_url);
    let (yes, no, hint) = (
        app.strings.gui_workspace_reload_yes,
        app.strings.gui_workspace_reload_no,
        app.strings.workspace_reload_save_hint,
    );
    let mut answer: Option<bool> = None;
    let dismissed = modal(ctx, title, |ui| {
        ui.colored_label(app.theme.text, question);
        ui.add_space(4.0);
        ui.colored_label(app.theme.dim, hint);
        ui.add_space(8.0);
        ui.horizontal(|ui| {
            if ui.button(yes).clicked() {
                answer = Some(true);
            }
            if ui.button(no).clicked() {
                answer = Some(false);
            }
        });
    })
    .dismissed;
    // Dismissing is declining: the offer is recorded on the tab, so it comes
    // back next launch rather than being lost.
    if dismissed {
        answer = Some(false);
    }
    match answer {
        Some(true) => app.start_workspace_redownload(ci, reload),
        Some(false) => {}
        // Re-arm until the user answers; the reload can't be silently skipped.
        None => {
            app.dialog = Some(Dialog::WorkspaceReload {
                ci,
                reload: Box::new(reload),
            });
        }
    }
}

/// A centred modal window shell shared by every dialog.
///
/// [`DialogFrame::inner`] is `None` when egui declined to show the window at
/// all. Callers treat that as "no answer this frame" and leave the dialog
/// armed rather than deciding for the user — a render path must never panic,
/// and an unanswered dialog simply reappears. `dismissed` is the ✕ or Escape,
/// which every dialog runs as its Cancel.
fn modal<R>(
    ctx: &egui::Context,
    title: &str,
    add: impl FnOnce(&mut egui::Ui) -> R,
) -> super::widgets::DialogFrame<R> {
    super::widgets::dialog(ctx, title, None, add)
}

/// What an open dialog is for, once it answers. See [`PickAction`].
fn open_title(app: &GuiApp, kind: OpenKind) -> &'static str {
    match kind {
        OpenKind::Collection => app.strings.gui_open_collection_title,
        OpenKind::Environment => app.strings.gui_open_environment_title,
        OpenKind::Workspace => app.strings.gui_open_workspace_title,
        OpenKind::Report => app.strings.gui_open_report_title,
        OpenKind::PostmanExport => app.strings.postman_export_open_title,
    }
}

fn open_picker_kind(kind: OpenKind) -> PickerKind {
    match kind {
        OpenKind::Environment => PickerKind::Environment,
        _ => PickerKind::Other,
    }
}

/// Open a collection / environment / workspace through a native OS picker.
/// Replaces the old type-a-path modal — a menu click pops the native chooser,
/// and a successful pick loads immediately; failures show a native error alert.
///
/// The dialog runs on a worker thread and is collected by
/// [`poll_pending_pick`] some frames later, so this returns straight away.
pub fn open_via_picker(app: &mut GuiApp, kind: OpenKind) {
    let title = open_title(app, kind);
    let dir = app
        .session
        .picker_dir(open_picker_kind(kind))
        .map(|p| p.to_path_buf());
    let filters = |f: &[super::filepick::Filter]| super::filepick::owned_filters(f);
    let pick_kind = match kind {
        OpenKind::Workspace => super::filepick::PickKind::Folder,
        OpenKind::Collection => super::filepick::PickKind::File {
            filters: filters(&[
                (app.strings.gui_filter_collections, &["hurl", "json"]),
                (app.strings.gui_filter_all, &["*"]),
            ]),
        },
        OpenKind::Environment => super::filepick::PickKind::File {
            filters: filters(&[
                (
                    app.strings.gui_filter_environments,
                    &["vars", "env", "json"],
                ),
                (app.strings.gui_filter_all, &["*"]),
            ]),
        },
        OpenKind::Report => super::filepick::PickKind::File {
            filters: filters(&[
                (app.strings.gui_filter_reports, &["trail"]),
                (app.strings.gui_filter_all, &["*"]),
            ]),
        },
        OpenKind::PostmanExport => super::filepick::PickKind::File {
            filters: filters(&[
                (app.strings.gui_filter_postman_export, &["json"]),
                (app.strings.gui_filter_all, &["*"]),
            ]),
        },
    };
    app.request_pick(pick_kind, title, dir.as_deref(), PickAction::Open(kind));
}

/// What to do with a path once its dialog answers.
///
/// The click that opened the dialog knows what it was for; the frame that
/// collects the path, many frames later, does not — so the intent travels with
/// the request.
pub enum PickAction {
    Open(OpenKind),
    Save(SaveKind),
    /// A `root:` / `baseline:` / `collection:` path in the report editor's
    /// settings panel.
    ReportHeaderFile {
        key: &'static str,
        occurrence: usize,
    },
    /// A `FOLDER`/`FILE` parameter's path, chosen from the run settings.
    ReportParamPath {
        name: String,
    },
    /// The default value of a `FOLDER`/`FILE` `PARAM`, picked from its block.
    ReportParamDefault {
        path: Vec<usize>,
    },
    /// The folder (or file) a `FOR … IN FILES/FOLDERS` loop walks.
    ReportLoopDir {
        path: Vec<usize>,
        file: bool,
    },
    /// Where a Postman import should put the workspace it builds.
    PostmanDest,
    /// The folder a `FILES`/`FOLDERS` node wizard is being pointed at.
    ReportWizardDir,
    /// Naming a new collection / report / environment in a workspace.
    NewWorkspaceItem {
        ci: usize,
        kind: crate::workspace::NewItemKind,
    },
    /// A `File`/`Base64File` value in a request's Form or Multipart body.
    FormFieldFile {
        ci: usize,
        entry: usize,
        field: usize,
    },
    /// Where to keep a workspace just downloaded from a git remote.
    GitWorkspaceDir,
}

/// Collect a finished file dialog, if one has finished, and act on it. Called
/// once per frame from [`super::app::GuiApp::draw`].
pub fn poll_pending_pick(app: &mut GuiApp) {
    let Some(pending) = app.pending_pick.as_mut() else {
        return;
    };
    let Some((action, picked)) = pending.take() else {
        return; // still open — the usual case
    };
    app.pending_pick = None;
    // Every picker teaches the next one where the user just was. The report
    // editor's own dialogs used to be left out of this, so browsing to a corpus
    // folder was forgotten and the next Browse… opened back at the workspace
    // root — the one complaint this is here to fix. `Other` deliberately seeds
    // only the general last-browsed folder, leaving the environment/import
    // memories to the pickers those are actually about.
    if let Some(path) = picked.as_ref() {
        app.session
            .remember_picker_dir(crate::session::PickerKind::Other, path);
    }
    // The report editor's own pickers write into the open editor rather than
    // loading a file, so they have no error to report.
    match action {
        PickAction::ReportParamPath { name } => {
            if let Some(path) = picked.as_ref()
                && let Some(ed) = app.report_editor.as_mut()
            {
                ed.param_values
                    .insert(name, path.to_string_lossy().into_owned());
            }
            return;
        }
        PickAction::ReportHeaderFile { key, occurrence } => {
            super::report_editor::apply_picked_header_file(app, key, occurrence, picked);
            return;
        }
        PickAction::ReportParamDefault { path } => {
            super::report_editor::apply_picked_param_default(app, &path, picked);
            return;
        }
        PickAction::ReportLoopDir { path, file } => {
            super::report_editor::apply_picked_loop_dir(app, &path, file, picked);
            return;
        }
        PickAction::PostmanDest => {
            super::postman::apply_picked_dest(app, picked);
            return;
        }
        PickAction::ReportWizardDir => {
            super::report_wizard::apply_picked_dir(app, picked);
            return;
        }
        PickAction::NewWorkspaceItem { ci, kind } => {
            super::requests::apply_new_workspace_item(app, ci, kind, picked);
            return;
        }
        PickAction::FormFieldFile { ci, entry, field } => {
            super::editor::apply_picked_form_file(app, ci, entry, field, picked);
            return;
        }
        PickAction::GitWorkspaceDir => {
            super::remote::apply_picked_workspace_dir(app, picked);
            return;
        }
        _ => {}
    }
    let (title, picker_kind) = match action {
        PickAction::Open(kind) => (open_title(app, kind), open_picker_kind(kind)),
        PickAction::Save(kind) => (save_title(app, kind), save_picker_kind(kind)),
        _ => unreachable!("handled above"),
    };
    let Some(path) = picked else {
        return; // cancelled
    };
    // Remembered even when the load fails: the user still browsed there, and
    // sending the next picker back to square one would be the bigger annoyance.
    app.session.remember_picker_dir(picker_kind, &path);
    let outcome = match action {
        PickAction::Open(kind) => apply_open(app, kind, &path),
        PickAction::Save(kind) => apply_save(app, kind, &path),
        _ => unreachable!("handled above"),
    };
    if let Err(msg) = outcome {
        super::filepick::error_alert(title, &msg);
    }
    app.session.save();
}

/// Load the chosen path as the given kind, returning a user-facing error string
/// on failure (bad folder / unreadable / unparseable). The success side effects
/// (loading into the session, refocusing) mirror the old dialog's submit path.
fn apply_open(app: &mut GuiApp, kind: OpenKind, path: &Path) -> Result<(), String> {
    if kind == OpenKind::Workspace {
        if path.is_dir() {
            app.session.open_workspace(path.to_path_buf());
            app.focus = super::Focus::List;
            app.close_report_editor();
            return Ok(());
        }
        return Err(app.strings.gui_not_a_folder.to_string());
    }
    let path_str = path.to_string_lossy().into_owned();
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("{} {e}", app.strings.gui_could_not_read))?;
    let name = file_stem(&path_str);
    // A report opens into the report editor rather than a tab. It also joins
    // the session's report list, so it is listed beside the others, survives a
    // restart, and its edits are saved back to the file it came from.
    if kind == OpenKind::Report {
        let report = crate::report::Report::load_local(path)?;
        let existing = app
            .session
            .reports
            .iter()
            .position(|r| r.path.as_deref() == Some(&path_str));
        let idx = match existing {
            Some(i) => i,
            None => {
                app.session
                    .reports
                    .push(crate::persistence::PersistedReport {
                        name: report.name.clone(),
                        text: report.text.clone(),
                        path: Some(path_str.clone()),
                        git_origin: None,
                        workspace_root: None,
                        embedded_active: true,
                    });
                app.session.reports.len() - 1
            }
        };
        app.open_report_editor(
            crate::gui::report_editor::ReportOrigin::Session(idx),
            report,
        );
        app.focus = super::Focus::Main;
        return Ok(());
    }
    // An export is sorted by what it holds, not by what the user said it was:
    // Postman writes collections and environments to the same `.json`, and
    // making the user know which they picked is exactly the knowledge they
    // came here without. The same applies to the plain Collection and
    // Environment pickers -- one of them is bound to be handed the other kind.
    let asked = kind;
    let kind = match kind {
        OpenKind::PostmanExport => match crate::postman::export_kind(&content) {
            Some(crate::postman::ExportKind::Collection) => OpenKind::Collection,
            Some(crate::postman::ExportKind::Environment) => OpenKind::Environment,
            None => return Err(app.strings.gui_not_postman_export.to_string()),
        },
        OpenKind::Collection
            if crate::postman::export_kind(&content)
                == Some(crate::postman::ExportKind::Environment) =>
        {
            OpenKind::Environment
        }
        OpenKind::Environment
            if crate::postman::export_kind(&content)
                == Some(crate::postman::ExportKind::Collection) =>
        {
            OpenKind::Collection
        }
        other => other,
    };
    let ok = match kind {
        OpenKind::Collection => {
            app.session
                .load_collection_text(name, &content, Some(path.to_path_buf()))
        }
        OpenKind::Environment => app
            .session
            .load_environment_text(name, &content, Some(path.to_path_buf()), None)
            .is_some(),
        OpenKind::Workspace | OpenKind::Report | OpenKind::PostmanExport => unreachable!(),
    };
    if ok {
        // Only when the file overruled the menu entry -- a Postman export
        // opened through the dedicated entry went where it was asked to go.
        if asked != OpenKind::PostmanExport && asked != kind {
            app.session.status = Some(match kind {
                OpenKind::Collection => Status::OpenedAsCollection,
                _ => Status::OpenedAsEnvironment,
            });
        }
        Ok(())
    } else {
        Err(app.strings.gui_could_not_parse.to_string())
    }
}

/// The results-export dialog's format filters, with `ext`'s own format moved to
/// the front.
///
/// The dialog applies its first filter by default, so leading with the format
/// the report's `# output:` directive declares means exporting a report that
/// says `# output: xlsx` writes a spreadsheet without the user touching the
/// dropdown — while the other three stay one click away. This is what gives the
/// GUI the terminal UI's behaviour, whose export picker is seeded the same way.
/// An unrecognised extension leaves the order alone, so CSV leads as before.
fn report_result_filters(ext: &str) -> Vec<super::filepick::Filter<'static>> {
    const ALL: [super::filepick::Filter<'static>; 5] = [
        ("CSV", &["csv"]),
        ("JSON", &["json"]),
        ("HTML", &["html"]),
        ("Excel", &["xlsx"]),
        ("PDF", &["pdf"]),
    ];
    let want = ext.to_ascii_lowercase();
    let mut filters = ALL.to_vec();
    if let Some(i) = filters
        .iter()
        .position(|(_, exts)| exts.contains(&want.as_str()))
    {
        let leading = filters.remove(i);
        filters.insert(0, leading);
    }
    filters
}

/// Save the active collection / environment / response / report results through
/// a native OS save picker.
fn save_title(app: &GuiApp, kind: SaveKind) -> &'static str {
    match kind {
        SaveKind::Collection => app.strings.gui_save_collection_title,
        SaveKind::Environment(_) => app.strings.gui_save_environment_title,
        SaveKind::Response => app.strings.gui_save_response_title,
        SaveKind::ReportResults => app.strings.gui_save_results_title,
        SaveKind::ReportBaseline => app.strings.gui_save_baseline_title,
        SaveKind::Report => app.strings.gui_save_report_title,
    }
}

fn save_picker_kind(kind: SaveKind) -> PickerKind {
    match kind {
        SaveKind::Environment(_) => PickerKind::Environment,
        _ => PickerKind::Other,
    }
}

/// What "Save" (the File menu entry and Ctrl+S) writes: whatever is in front of
/// the user.
///
/// The open report editor wins when there is one, since it is drawn over the
/// request view and is the thing being edited; otherwise it is the active
/// collection tab. Reported as a `SaveKind` so the fallback to a picker, when
/// the target has never been written anywhere, needs no second decision about
/// what is being saved.
pub fn active_save_kind(app: &GuiApp) -> SaveKind {
    if app.report_editor.is_some() {
        SaveKind::Report
    } else {
        SaveKind::Collection
    }
}

/// Save what is in front of the user, straight to the file it came from.
///
/// Falls back to the Save As picker when that thing has never been written
/// anywhere -- there is no path to save to, and refusing outright would leave
/// Ctrl+S doing nothing on exactly the documents most likely to need saving.
/// An item that *does* know its file is written without a dialog: a save
/// shortcut that always asks where is no shortcut.
pub fn save_active(app: &mut GuiApp) {
    match active_save_kind(app) {
        SaveKind::Report => match app.report_editor.as_mut() {
            Some(ed) if ed.report.path.is_some() => {
                super::report_editor::request_save(ed);
            }
            _ => save_via_picker(app, SaveKind::Report),
        },
        _ => {
            let ci = app.active_ci();
            let Some(path) = app.session.collections.get(ci).and_then(|c| c.path.clone()) else {
                save_via_picker(app, SaveKind::Collection);
                return;
            };
            let text = app.session.collections[ci].to_hurl();
            match std::fs::write(&path, text) {
                Ok(()) => {
                    app.session.collections[ci].mark_saved();
                    app.session.save();
                    app.session.status = Some(crate::i18n::Status::Saved);
                }
                Err(e) => {
                    app.session.status = Some(crate::i18n::Status::Error(format!(
                        "{} {e}",
                        app.strings.gui_could_not_write
                    )));
                }
            }
        }
    }
}

/// Whether [`save_active`] would write without asking -- i.e. whether the thing
/// in front of the user already has a file. Drives the Save entry's hint, so
/// the menu can say which of the two it is about to do.
pub fn save_active_has_path(app: &GuiApp) -> bool {
    match active_save_kind(app) {
        SaveKind::Report => app
            .report_editor
            .as_ref()
            .is_some_and(|e| e.report.path.is_some()),
        _ => app
            .session
            .collections
            .get(app.active_ci())
            .is_some_and(|c| c.path.is_some()),
    }
}

pub fn save_via_picker(app: &mut GuiApp, kind: SaveKind) {
    let title = save_title(app, kind);
    // Seed the dialog from any remembered path (collections/environments) and a
    // sensible default filename.
    let current = match kind {
        SaveKind::Collection => app.session.collections[app.active_ci()]
            .path
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default(),
        SaveKind::Environment(id) => app
            .session
            .global_envs
            .iter()
            .find(|e| e.id == id)
            .and_then(|e| e.path.as_ref())
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default(),
        // A results export defaults to the format the report's `# output:`
        // directive declares (CSV when it declares none), beside the report --
        // the same name the terminal UI suggests, `{time}` token included. The
        // dialog can still be pointed at any of the other formats.
        SaveKind::ReportResults => app
            .report_editor
            .as_ref()
            .map(|e| {
                crate::report::writer::export_path(
                    &e.report,
                    &crate::report::writer::report_output_extension(&e.report),
                )
            })
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default(),
        // A baseline snapshot is named the same way, so a report's results file
        // and its snapshot sit side by side under one stem.
        SaveKind::ReportBaseline => app
            .report_editor
            .as_ref()
            .map(|e| crate::report::writer::export_path(&e.report, "baseline"))
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default(),
        // A report saves as its own `.trail` source, seeded from the file it was
        // loaded from so "Save report" over an opened file re-offers that file.
        SaveKind::Report => app
            .report_editor
            .as_ref()
            .and_then(|e| e.report.path.clone())
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| {
                app.report_editor
                    .as_ref()
                    .map(|e| format!("{}.trail", e.report.name))
                    .unwrap_or_default()
            }),
        SaveKind::Response => String::new(),
    };
    let picker_kind = save_picker_kind(kind);
    // The file's own folder wins (a re-save belongs where it already lives);
    // an unsaved item falls back to wherever the user last browsed.
    let dir = super::filepick::seed_dir(&current)
        .or_else(|| app.session.picker_dir(picker_kind).map(|p| p.to_path_buf()));
    let default_name = std::path::Path::new(&current)
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| match kind {
            SaveKind::Collection => "collection.hurl".into(),
            SaveKind::Environment(_) => "environment.vars".into(),
            SaveKind::Response => "response.txt".into(),
            SaveKind::ReportResults => "results.csv".into(),
            SaveKind::ReportBaseline => "report.baseline".into(),
            SaveKind::Report => "report.trail".into(),
        });
    let result_filters = report_result_filters(
        std::path::Path::new(&current)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or_default(),
    );
    let filters: &[super::filepick::Filter] = match kind {
        SaveKind::Collection => &[("Hurl", &["hurl"]), ("All files", &["*"])],
        SaveKind::Environment(_) => &[("Vars", &["vars"]), ("All files", &["*"])],
        SaveKind::ReportResults => &result_filters,
        SaveKind::ReportBaseline => &[("Baseline", &["baseline"]), ("All files", &["*"])],
        SaveKind::Report => &[("PaperTrail", &["trail"]), ("All files", &["*"])],
        SaveKind::Response => &[("All files", &["*"])],
    };
    app.request_pick(
        super::filepick::PickKind::Save {
            default_name,
            filters: super::filepick::owned_filters(filters),
        },
        title,
        dir.as_deref(),
        PickAction::Save(kind),
    );
}

/// Write the given kind to `path`, returning a user-facing error on failure.
fn apply_save(app: &mut GuiApp, kind: SaveKind, path: &Path) -> Result<(), String> {
    let path_str = path.to_string_lossy();
    // Report results export writes format-specific bytes (chosen by extension).
    if matches!(kind, SaveKind::ReportResults) {
        return export_report_results(app, &path_str);
    }
    if matches!(kind, SaveKind::ReportBaseline) {
        return save_report_baseline(app, path);
    }
    if matches!(kind, SaveKind::Report) {
        super::report_editor::save_report_to(app, path)?;
        app.session.save();
        return Ok(());
    }
    let content = match kind {
        SaveKind::Collection => Some(app.session.collections[app.active_ci()].to_hurl()),
        SaveKind::Environment(id) => app
            .session
            .global_envs
            .iter()
            .find(|e| e.id == id)
            .map(|e| e.to_vars_text()),
        SaveKind::Response => Some(app.session.response.lock().unwrap().body.to_string()),
        SaveKind::ReportResults | SaveKind::ReportBaseline | SaveKind::Report => None,
    };
    let text = content.ok_or_else(|| app.strings.gui_nothing_to_save.to_string())?;
    std::fs::write(path, text).map_err(|e| {
        format!(
            "{} {}",
            app.strings.gui_could_not_write,
            crate::shared_utils::friendly_error(&e)
        )
    })?;
    // Remember the path for collections/environments.
    match kind {
        SaveKind::Collection => {
            let ci = app.active_ci();
            app.session.collections[ci].path = Some(path.to_path_buf());
            // The file on disk now matches what is in memory, so the "new" and
            // "edited" pencils must go — including any parked edits for it.
            app.session.collections[ci].mark_saved();
        }
        SaveKind::Environment(id) => {
            if let Some(e) = app.session.global_envs.iter_mut().find(|e| e.id == id) {
                e.path = Some(path.to_path_buf());
            }
        }
        SaveKind::Response
        | SaveKind::ReportResults
        | SaveKind::ReportBaseline
        | SaveKind::Report => {}
    }
    app.session.save();
    Ok(())
}

/// Write the open report editor's last-run results to `path`, choosing the
/// output format from the file extension (csv / json / html / xlsx). Marks the
/// results exported so a rerun won't warn about discarding them.
fn export_report_results(app: &mut GuiApp, path: &str) -> Result<(), String> {
    let ext = std::path::Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");
    let writer = crate::report::writer::writer_for_extension(ext)
        .ok_or_else(|| format!("{} {ext}", app.strings.gui_unsupported_format))?;
    let ed = app
        .report_editor
        .as_ref()
        .ok_or_else(|| app.strings.gui_nothing_to_save.to_string())?;
    // A run in flight and a run never started both leave `result` empty, but
    // they are different problems: one is "wait", the other is "press Run".
    // "Nothing to save" told the reader neither.
    let result = ed.result.as_ref().ok_or_else(|| {
        if ed.is_running() {
            app.strings.report_export_still_running.to_string()
        } else {
            app.strings.report_export_no_result.to_string()
        }
    })?;
    let header = ed
        .flow
        .as_ref()
        .map(|f| f.header.clone())
        .unwrap_or_default();
    let bytes = writer.write(result, &header)?;
    std::fs::write(path, bytes).map_err(|e| {
        format!(
            "{} {}",
            app.strings.gui_could_not_write,
            crate::shared_utils::friendly_error(&e)
        )
    })?;
    if let Some(ed) = app.report_editor.as_mut() {
        ed.results_exported = true;
        // Remembered so the toolbar can offer to open it: an HTML export is
        // written to be read in a browser, and hunting for the file you just
        // named is the only step between the two.
        ed.last_export = Some(path.to_string());
    }
    app.session.status = Some(crate::i18n::Status::ReportExported(path.to_string()));
    Ok(())
}

/// Write the open report editor's last run to `path` as a `.baseline` JSON
/// snapshot — PaperTrail's "Source B", which a later run diffs against once its
/// `# baseline:` directive or a `BASELINE(FILE(…))` role points at the file.
///
/// Like a results export, this marks the run exported: the result is on disk
/// now, so a rerun needn't warn about discarding it.
fn save_report_baseline(app: &mut GuiApp, path: &Path) -> Result<(), String> {
    let result = app
        .report_editor
        .as_ref()
        .and_then(|e| e.result.as_ref())
        .ok_or_else(|| app.strings.report_baseline_no_result.to_string())?;
    crate::report::Baseline::from_result(result)
        .save(path)
        .map_err(|e| {
            format!(
                "{} {}",
                app.strings.gui_could_not_write,
                crate::shared_utils::friendly_error(&e)
            )
        })?;
    if let Some(ed) = app.report_editor.as_mut() {
        ed.results_exported = true;
    }
    app.session.status = Some(crate::i18n::Status::ReportBaselineSaved(
        path.display().to_string(),
    ));
    Ok(())
}

fn rename_dialog(app: &mut GuiApp, ctx: &egui::Context, target: RenameTarget, mut text: String) {
    let title = app.strings.gui_rename;
    let lbl_name = app.strings.gui_name;
    let lbl_rename = app.strings.gui_rename;
    let lbl_cancel = app.strings.gui_cancel;
    let frame = modal(ctx, title, |ui| {
        let resp = ui.add(
            egui::TextEdit::singleline(&mut text)
                .desired_width(320.0)
                .hint_text(lbl_name),
        );
        let submit = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
        let mut keep = true;
        let mut go = submit;
        ui.horizontal(|ui| {
            if ui.button(lbl_rename).clicked() {
                go = true;
            }
            if ui.button(lbl_cancel).clicked() {
                keep = false;
            }
        });
        (keep, go)
    });
    // A frame egui never drew is not an answer: keep the dialog open;
    // dismissing it is the Cancel button.
    let dismissed = frame.dismissed;
    let (keep, submit) = frame.inner_or((true, false));
    let keep = keep && !dismissed;
    if !keep {
        return;
    }
    if submit {
        if !text.trim().is_empty() {
            match target {
                RenameTarget::Request { ci, idx } => {
                    if let Some(col) = app.session.collections.get_mut(ci) {
                        if let Some(entry) = col.entries.get_mut(idx) {
                            entry.title = text.clone();
                            entry.mark_edited();
                        }
                        col.invalidate_request_json();
                    }
                }
                RenameTarget::Tab { ci } => {
                    if let Some(col) = app.session.collections.get_mut(ci) {
                        col.name = text.clone();
                    }
                }
                // A workspace file/folder is renamed on disk (and everything
                // holding its old path repointed), rather than by editing an
                // in-memory title — see `rename_workspace_item`.
                RenameTarget::WorkspaceItem { ci, path } => {
                    super::requests::rename_workspace_item(app, ci, &path, text.trim());
                }
            }
            app.session.save();
        }
        return;
    }
    app.dialog = Some(Dialog::Rename { target, text });
}

/// Name the parameter a request field is being extracted into.
///
/// The name is re-checked against the request every frame rather than once on
/// submit, so the refusal appears as the offending name is typed; and the OK
/// button is a no-op while it stands, so Enter can't smuggle a refused name
/// past the check.
#[allow(clippy::too_many_arguments)]
fn extract_parameter_dialog(
    app: &mut GuiApp,
    ctx: &egui::Context,
    ci: usize,
    entry: usize,
    target: super::editor::ExtractTarget,
    value: String,
    range: Option<std::ops::Range<usize>>,
    mut name: String,
) {
    let title = app.strings.extract_title;
    let lbl_value = app.strings.extract_value;
    let lbl_name = app.strings.extract_name_label;
    let lbl_ok = app.strings.gui_ok;
    let lbl_cancel = app.strings.gui_cancel;
    let dim = app.theme.dim;
    let err_color = app.theme.err;
    let declared = app
        .session
        .collections
        .get(ci)
        .and_then(|c| c.entries.get(entry))
        .map(|e| e.variable_defaults())
        .unwrap_or_default();
    let msg_invalid = app.strings.extract_name_invalid;
    let msg_conflict = app.strings.extract_name_conflict;
    let frame = modal(ctx, title, |ui| {
        ui.label(egui::RichText::new(crate::i18n::fill(lbl_value, &[&value])).color(dim));
        ui.add_space(4.0);
        ui.label(egui::RichText::new(lbl_name).color(dim));
        let resp = ui.add(
            egui::TextEdit::singleline(&mut name)
                .desired_width(320.0)
                .hint_text(lbl_name),
        );
        let error = crate::hurl::check_parameter_name(&name, &value, &declared);
        match &error {
            Some(crate::hurl::ParamNameError::Invalid) => {
                ui.label(egui::RichText::new(msg_invalid).color(err_color));
            }
            Some(crate::hurl::ParamNameError::Conflict(existing)) => {
                ui.label(
                    egui::RichText::new(crate::i18n::fill(msg_conflict, &[&name, existing]))
                        .color(err_color),
                );
            }
            None => {}
        }
        let submit = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
        let mut keep = true;
        let mut go = submit;
        ui.horizontal(|ui| {
            if ui
                .add_enabled(error.is_none(), egui::Button::new(lbl_ok))
                .clicked()
            {
                go = true;
            }
            if ui.button(lbl_cancel).clicked() {
                keep = false;
            }
        });
        (keep, go && error.is_none())
    });
    // A frame egui never drew is not an answer: keep the dialog open;
    // dismissing it is the Cancel button.
    let dismissed = frame.dismissed;
    let (keep, submit) = frame.inner_or((true, false));
    let keep = keep && !dismissed;
    if !keep {
        return;
    }
    if submit {
        super::editor::apply_extract_parameter(app, ci, entry, target, range, &value, &name);
        app.session.save();
        return;
    }
    app.dialog = Some(Dialog::ExtractParameter {
        ci,
        entry,
        target,
        value,
        range,
        name,
    });
}

fn prompt_dialog(app: &mut GuiApp, ctx: &egui::Context, kind: PromptKind, mut text: String) {
    let title = match &kind {
        PromptKind::BaseUrl => app.strings.gui_base_url_title,
        PromptKind::NewEnvName => app.strings.gui_new_env_name_title,
        PromptKind::NewCollectionName => app.strings.gui_new_collection_name_title,
        PromptKind::NewWorkspaceFolder { .. } => app.strings.gui_ws_new_folder_title,
    };
    let lbl_ok = app.strings.gui_ok;
    let lbl_cancel = app.strings.gui_cancel;
    let frame = modal(ctx, title, |ui| {
        let resp = ui.add(egui::TextEdit::singleline(&mut text).desired_width(360.0));
        let submit = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
        let mut keep = true;
        let mut go = submit;
        ui.horizontal(|ui| {
            if ui.button(lbl_ok).clicked() {
                go = true;
            }
            if ui.button(lbl_cancel).clicked() {
                keep = false;
            }
        });
        (keep, go)
    });
    // A frame egui never drew is not an answer: keep the dialog open;
    // dismissing it is the Cancel button.
    let dismissed = frame.dismissed;
    let (keep, submit) = frame.inner_or((true, false));
    let keep = keep && !dismissed;
    if !keep {
        return;
    }
    if submit {
        match &kind {
            PromptKind::BaseUrl => {
                app.session.vars.base_url = text.clone();
                app.session.save();
            }
            PromptKind::NewEnvName => {
                let name = if text.trim().is_empty() {
                    app.strings.gui_default_env_name.to_string()
                } else {
                    text.clone()
                };
                app.session.add_environment(name);
            }
            PromptKind::NewCollectionName => {
                let name = if text.trim().is_empty() {
                    app.strings.gui_untitled.to_string()
                } else {
                    text.clone()
                };
                app.session.add_collection(name);
                app.session.save();
            }
            PromptKind::NewWorkspaceFolder { ci, dir } => {
                let (ci, dir) = (*ci, dir.clone());
                super::requests::new_workspace_folder(app, ci, &dir, text.trim());
            }
        }
        return;
    }
    app.dialog = Some(Dialog::Prompt { kind, text });
}

fn theme_dialog(app: &mut GuiApp, ctx: &egui::Context, mut state: ThemeEditState) {
    enum Action {
        Keep,
        Cancel,
        Apply,
    }
    let strings = Strings::mapped(&app.session.language, super::icons::drawable);
    let title = app.strings.gui_theme_editor_title;
    let lbl_name = app.strings.gui_name;
    let lbl_apply = app.strings.gui_apply;
    let lbl_cancel = app.strings.gui_cancel;
    let dim = app.theme.dim;
    let frame = modal(ctx, title, |ui| {
        ui.horizontal(|ui| {
            ui.colored_label(dim, lbl_name);
            ui.text_edit_singleline(&mut state.spec.name);
        });
        ui.separator();
        egui::Grid::new("theme_colors")
            .num_columns(2)
            .spacing([12.0, 6.0])
            .show(ui, |ui| {
                for i in 0..THEME_COLOR_COUNT {
                    let label = color_label(&strings, i);
                    ui.colored_label(dim, label);
                    let mut rgb = state.spec.color(i);
                    if ui.color_edit_button_srgb(&mut rgb).changed() {
                        state.spec.set_color(i, rgb);
                    }
                    ui.end_row();
                }
            });
        ui.separator();
        let mut action = Action::Keep;
        ui.horizontal(|ui| {
            if ui.button(lbl_apply).clicked() {
                action = Action::Apply;
            }
            if ui.button(lbl_cancel).clicked() {
                action = Action::Cancel;
            }
        });
        action
    });
    // A frame egui never drew is not an answer: keep the dialog open;
    // dismissing it is the Cancel button.
    let action = if frame.dismissed {
        Action::Cancel
    } else {
        frame.inner_or(Action::Keep)
    };

    match action {
        Action::Cancel => {}
        Action::Apply => {
            // Replace an existing custom theme of the same original name, else add.
            if let Some(existing) = app
                .session
                .custom_themes
                .iter_mut()
                .find(|t| t.name == state.original_name)
            {
                *existing = state.spec.clone();
            } else {
                app.session.custom_themes.push(state.spec.clone());
            }
            app.session.active_theme = Some(state.spec.name.clone());
            app.session.save();
        }
        Action::Keep => {
            app.dialog = Some(Dialog::Theme(Box::new(state)));
        }
    }
}

fn file_stem(path: &str) -> String {
    std::path::Path::new(path)
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "untitled".to_string())
}

/// The i18n label for the `i`th editable theme colour (mirrors the terminal
/// UI's `theme_editor::color_label`, reading the same `Strings` fields).
use crate::theme::color_label;

/// The probe builder's modal, driven through the real dialog layer with
/// simulated clicks. Harness in [`crate::gui::probe_test_support`].
#[cfg(test)]
mod probe_dialog_tests {
    use crate::gui::app::Dialog;
    use crate::gui::probe_test_support::*;
    use eframe::egui;

    /// Clearing the suggested name and pressing Add must not throw the dialog
    /// away: `apply` refuses an empty name, and the caller used to `return`
    /// either way, losing three steps of work with nothing written. Now the
    /// dialog stays up and says why.
    #[test]
    fn add_with_an_empty_capture_name_loses_the_dialog() {
        let body = r#"{"token":"abc"}"#;
        let mut app = app_with(body, vec![], 200);
        let probe = crate::probe::probes(200, None, &[], body)
            .into_iter()
            .find(|p| crate::probe::subject_label(&p.subject) == "$.token")
            .unwrap();
        let ctx = themed_ctx();
        super::super::probe::open(&mut app, &ctx, Some(probe));
        if let Some(Dialog::ProbeBuilder(b)) = &mut app.dialog {
            b.capture_name = Some(String::new());
        }

        dialog_frame(&mut app, &ctx, vec![]);
        let painted = dialog_frame(&mut app, &ctx, vec![]);
        let add = centre_of(&painted, app.strings.gui_probe_add_capture);
        let (press, release) = click_events(add, egui::PointerButton::Primary);
        dialog_frame(&mut app, &ctx, press);
        dialog_frame(&mut app, &ctx, release);

        let captures = app.session.collections[0].entries[0].captures.clone();
        assert!(
            captures.is_empty(),
            "an empty name should not write a capture"
        );
        assert!(
            app.dialog.is_some(),
            "Add with an empty name threw the dialog away and wrote nothing"
        );
    }

    /// One click on a row must not commit it. The list is there to be read —
    /// picking a row and acting on it are separate, so a row can be looked at
    /// (and highlighted in the body) before it is chosen.
    #[test]
    fn a_click_selects_a_row_without_choosing_it() {
        let body = r#"{"first":"one","token":"abc"}"#;
        let mut app = app_with(body, vec![], 200);
        let ctx = themed_ctx();
        super::super::probe::open(&mut app, &ctx, None);

        dialog_frame(&mut app, &ctx, vec![]);
        let painted = dialog_frame(&mut app, &ctx, vec![]);
        let row = centre_of(&painted, "$.token");
        let (press, release) = click_events(row, egui::PointerButton::Primary);
        dialog_frame(&mut app, &ctx, press);
        dialog_frame(&mut app, &ctx, release);

        let Some(Dialog::ProbeBuilder(b)) = &app.dialog else {
            panic!("the click closed the builder");
        };
        assert!(
            b.chosen.is_none(),
            "the first click jumped straight to step two"
        );
        assert_eq!(
            b.visible()
                .get(b.selected)
                .map(|p| crate::probe::subject_label(&p.subject)),
            Some("$.token".to_string()),
            "the click did not select the row it landed on"
        );

        let painted = dialog_frame(&mut app, &ctx, vec![]);
        let next = centre_of(&painted, app.strings.gui_probe_next);
        let (press, release) = click_events(next, egui::PointerButton::Primary);
        dialog_frame(&mut app, &ctx, press);
        dialog_frame(&mut app, &ctx, release);

        let Some(Dialog::ProbeBuilder(b)) = &app.dialog else {
            panic!("Next closed the builder");
        };
        assert_eq!(
            b.chosen
                .as_ref()
                .map(|p| crate::probe::subject_label(&p.subject)),
            Some("$.token".to_string()),
            "Next did not take the selected row to step two"
        );
        assert!(!b.verbs.is_empty(), "step two has nothing to say about it");
    }

    /// Whichever value the builder is talking about is shown *in the response*,
    /// as a real selection of the body field — so it can be seen, and copied,
    /// rather than matched to a path by eye.
    #[test]
    fn the_value_under_discussion_is_highlighted_in_the_body() {
        let body = "{\n  \"first\": \"one\",\n  \"token\": \"abc\"\n}";
        let mut app = app_with(body, vec![], 200);
        let ctx = themed_ctx();
        panel_frame(&mut app, &ctx, vec![]);
        let probe = crate::probe::probes(200, None, &[], body)
            .into_iter()
            .find(|p| crate::probe::subject_label(&p.subject) == "$.token")
            .unwrap();
        super::super::probe::open(&mut app, &ctx, Some(probe));
        dialog_frame(&mut app, &ctx, vec![]);

        let range = egui::TextEdit::load_state(&ctx, super::super::probe::body_field_id(&app))
            .and_then(|s| s.cursor.char_range())
            .expect("the builder highlighted nothing")
            .as_sorted_char_range();
        let selected: String = body
            .chars()
            .skip(range.start.0)
            .take(range.end.0 - range.start.0)
            .collect();
        assert_eq!(
            selected, "\"abc\"",
            "the highlight covers the wrong part of the body"
        );
    }

    /// Copy value puts the bytes the server actually sent on the clipboard —
    /// the same logic that isolates a section for an assert, reused for the
    /// far more common "I just want this value" case.
    #[test]
    fn copy_value_puts_the_chosen_value_on_the_clipboard() {
        let body = r#"{"token":"abc"}"#;
        let mut app = app_with(body, vec![], 200);
        let ctx = themed_ctx();
        let probe = crate::probe::probes(200, None, &[], body)
            .into_iter()
            .find(|p| crate::probe::subject_label(&p.subject) == "$.token")
            .unwrap();
        super::super::probe::open(&mut app, &ctx, Some(probe));

        dialog_frame(&mut app, &ctx, vec![]);
        let painted = dialog_frame(&mut app, &ctx, vec![]);
        let copy = centre_of(&painted, app.strings.gui_probe_copy_value);
        let (press, release) = click_events(copy, egui::PointerButton::Primary);
        dialog_frame(&mut app, &ctx, press);
        let full = ctx.run_ui(input(release), |ui| super::show_dialog(&mut app, ui.ctx()));
        let copied: Vec<String> = full
            .platform_output
            .commands
            .iter()
            .filter_map(|c| match c {
                egui::output::OutputCommand::CopyText(t) => Some(t.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(
            copied,
            vec!["\"abc\"".to_string()],
            "Copy value did not copy the value it is pointing at"
        );
        assert!(
            app.dialog.is_some(),
            "copying threw the builder away instead of leaving it up"
        );
    }

    /// A verb row ends in a literal the server chose. A long one — a bearer
    /// token, say — holds no space to break at, so wrapping split it right
    /// after its opening quote and left a lone `"` on a line of its own, in a
    /// list whose rows are supposed to read as single assert lines.
    #[test]
    fn a_long_value_does_not_wrap_the_verb_rows() {
        let token = "PVmx3If8pKT2OFZttbomJuZqTdQpL3dXeNEDB5Opl0vBwXUYtjG3Mo6WkGmp";
        let body = format!(r#"{{"token":"{token}"}}"#);
        let mut app = app_with(&body, vec![], 200);
        let ctx = themed_ctx();
        let probe = crate::probe::probes(200, None, &[], &body)
            .into_iter()
            .find(|p| crate::probe::subject_label(&p.subject) == "$.token")
            .unwrap();
        super::super::probe::open(&mut app, &ctx, Some(probe));

        let mut painted = Vec::new();
        for _ in 0..3 {
            painted = dialog_frame(&mut app, &ctx, vec![]);
        }
        let wrapped: Vec<String> = painted
            .iter()
            .filter(|(_, g)| g.text().contains("jsonpath") && g.rows.len() > 1)
            .map(|(_, g)| g.text().to_string())
            .collect();
        assert!(
            wrapped.is_empty(),
            "an assert row wrapped onto a second line: {wrapped:?}"
        );
    }

    /// Hovering a row must not move the rows. A list that shifts under the
    /// pointer is unusable for aiming at anything.
    #[test]
    fn hovering_a_row_does_not_move_the_list() {
        let token = "PVmx3If8pKT2OFZttbomJuZqTdQpL3dXeNEDB5Opl0vBwXUYtjG3Mo6WkGmp";
        let body = format!(r#"{{"token":"{token}","other":"{token}"}}"#);
        let mut app = app_with(&body, vec![], 200);
        let ctx = themed_ctx();
        super::super::probe::open(&mut app, &ctx, None);
        let mut painted = Vec::new();
        for _ in 0..3 {
            painted = dialog_frame(&mut app, &ctx, vec![]);
        }
        let before: Vec<(String, egui::Pos2)> = painted
            .iter()
            .map(|(p, g)| (g.text().to_string(), *p))
            .collect();
        let row = centre_of(&painted, "$.token");
        let mut after = Vec::new();
        for _ in 0..3 {
            let p = dialog_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(row)]);
            after = p.iter().map(|(p, g)| (g.text().to_string(), *p)).collect();
        }
        assert_eq!(before, after, "hovering a row moved the list");
    }

    /// Pointing at a row is enough to show its value in the response: running
    /// the pointer down the list and watching the body is the quickest way to
    /// tell six similar-looking tokens apart.
    #[test]
    fn hovering_a_row_highlights_that_value_in_the_body() {
        let body = "{\n  \"first\": \"one\",\n  \"token\": \"abc\"\n}";
        let mut app = app_with(body, vec![], 200);
        let ctx = themed_ctx();
        panel_frame(&mut app, &ctx, vec![]);
        super::super::probe::open(&mut app, &ctx, None);
        let mut painted = Vec::new();
        for _ in 0..3 {
            painted = dialog_frame(&mut app, &ctx, vec![]);
        }
        let row = centre_of(&painted, "$.token");
        for _ in 0..3 {
            dialog_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(row)]);
        }

        let range = egui::TextEdit::load_state(&ctx, super::super::probe::body_field_id(&app))
            .and_then(|s| s.cursor.char_range())
            .expect("hovering highlighted nothing")
            .as_sorted_char_range();
        let selected: String = body
            .chars()
            .skip(range.start.0)
            .take(range.end.0 - range.start.0)
            .collect();
        assert_eq!(
            selected, "\"abc\"",
            "the hovered row highlighted the wrong part of the body"
        );
    }

    /// The subject list is a filter field over rows of monospace text with no
    /// width cap on the path column. On a small window the dialog must still
    /// paint inside the screen.
    #[test]
    fn the_builder_fits_a_small_window() {
        let deep = format!(
            r#"{{"{}":{{"{}":"{}"}}}}"#,
            "a_very_long_field_name_indeed".repeat(2),
            "another_long_nested_field_name".repeat(2),
            "v".repeat(200)
        );
        let mut app = app_with(&deep, vec![], 200);
        let ctx = themed_ctx();
        super::super::probe::open(&mut app, &ctx, None);
        let screen = egui::vec2(520.0, 380.0);
        let mut painted = Vec::new();
        for _ in 0..3 {
            let full = ctx.run_ui(
                egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), screen)),
                    ..Default::default()
                },
                |ui| super::show_dialog(&mut app, ui.ctx()),
            );
            painted = collect(&full);
        }
        let overflow: Vec<(String, f32)> = painted
            .iter()
            .map(|(p, g)| (g.text().to_string(), p.x + g.size().x))
            .filter(|(_, right)| *right > screen.x)
            .collect();
        assert!(
            overflow.is_empty(),
            "the builder paints past the right edge of a {}x{} window: {overflow:?}",
            screen.x,
            screen.y
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::i18n::Language;
    use crate::session::Session;

    fn app() -> GuiApp {
        GuiApp::for_test(Session::default())
    }

    /// Every picker leaves a trail: after the report editor's own parameter
    /// dialog lands somewhere, the next dialog that has no seed of its own
    /// opens there rather than back at square one.
    #[test]
    fn a_report_editors_picker_teaches_the_next_one_where_the_user_was() {
        let dir = std::env::temp_dir().join(format!("pb_pick_memory_{}", std::process::id()));
        let corpus = dir.join("Face");
        std::fs::create_dir_all(&corpus).unwrap();

        let mut app = app();
        assert!(
            app.session
                .picker_dir(crate::session::PickerKind::Other)
                .is_none(),
            "nothing browsed yet"
        );
        app.pending_pick = Some(super::super::filepick::resolved(
            PickAction::ReportParamPath {
                name: "CORPUS".to_string(),
            },
            Some(corpus.clone()),
        ));
        poll_pending_pick(&mut app);

        assert_eq!(
            app.session.picker_dir(crate::session::PickerKind::Other),
            Some(corpus.as_path()),
            "the folder just picked is where the next picker starts"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The desktop import route asks for "a file you exported from Postman"
    /// and works out for itself which of PaperBoy's two shelves it belongs on —
    /// Postman gives collections and environments the same `.json` extension,
    /// and knowing which is which is exactly what a newcomer has not learned
    /// yet.
    #[test]
    fn an_exported_postman_file_opens_as_whichever_kind_it_turns_out_to_be() {
        let dir = std::env::temp_dir().join(format!("pb_gui_import_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let collection = dir.join("api.json");
        std::fs::write(
            &collection,
            r#"{"info":{"name":"Api","schema":"x"},"item":[{"name":"Health","request":{"method":"GET","url":"http://127.0.0.1:8080/health"}}]}"#,
        )
        .unwrap();
        let environment = dir.join("staging.json");
        std::fs::write(
            &environment,
            r#"{"name":"Staging","values":[{"key":"BASE","value":"http://x","enabled":true}]}"#,
        )
        .unwrap();
        let other = dir.join("notes.json");
        std::fs::write(&other, r#"{"hello":"world"}"#).unwrap();

        let mut app = app();
        let tabs = app.session.collections.len();
        let envs = app.session.global_envs.len();

        assert!(apply_open(&mut app, OpenKind::PostmanExport, &collection).is_ok());
        assert_eq!(app.session.collections.len(), tabs + 1);
        assert_eq!(app.session.global_envs.len(), envs);

        assert!(apply_open(&mut app, OpenKind::PostmanExport, &environment).is_ok());
        assert_eq!(app.session.global_envs.len(), envs + 1);
        assert_eq!(app.session.collections.len(), tabs + 1);

        // And a `.json` that is neither says so in those terms, rather than
        // "could not parse that file".
        let err = apply_open(&mut app, OpenKind::PostmanExport, &other).unwrap_err();
        assert_eq!(err, app.strings.gui_not_postman_export);

        std::fs::remove_dir_all(&dir).ok();
    }

    /// The everyday Collection and Environment entries do the same sorting:
    /// pointing "Open Collection" at a Postman *environment* export loads it as
    /// an environment (and says so) instead of refusing a file the app can
    /// plainly read. Only PaperBoy's own formats are taken at their word.
    #[test]
    fn the_ordinary_open_entries_follow_a_postman_export_too() {
        let dir = std::env::temp_dir().join(format!("pb_gui_reroute_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let collection = dir.join("api.json");
        std::fs::write(
            &collection,
            r#"{"info":{"name":"Api","schema":"x"},"item":[{"name":"Health","request":{"method":"GET","url":"http://127.0.0.1:8080/health"}}]}"#,
        )
        .unwrap();
        let environment = dir.join("staging.json");
        std::fs::write(
            &environment,
            r#"{"name":"Staging","values":[{"key":"BASE","value":"http://x","enabled":true}]}"#,
        )
        .unwrap();

        let mut app = app();
        let tabs = app.session.collections.len();
        let envs = app.session.global_envs.len();

        assert!(apply_open(&mut app, OpenKind::Collection, &environment).is_ok());
        assert_eq!(app.session.global_envs.len(), envs + 1);
        assert_eq!(app.session.collections.len(), tabs);
        assert!(
            matches!(app.session.status, Some(Status::OpenedAsEnvironment)),
            "the status says which shelf it landed on, got {:?}",
            app.session.status
        );

        assert!(apply_open(&mut app, OpenKind::Environment, &collection).is_ok());
        assert_eq!(app.session.collections.len(), tabs + 1);
        assert_eq!(app.session.global_envs.len(), envs + 1);
        assert!(
            matches!(app.session.status, Some(Status::OpenedAsCollection)),
            "the status says which shelf it landed on, got {:?}",
            app.session.status
        );

        std::fs::remove_dir_all(&dir).ok();
    }
    #[test]
    fn an_export_remembers_the_file_it_wrote_so_it_can_be_opened() {
        use crate::report::model::{ReportResult, ReportRow};

        let mut app = app();
        let mut ed = crate::gui::report_editor::ReportEditor::new(
            crate::gui::report_editor::ReportOrigin::Session(0),
            crate::report::Report::scratch("r"),
        );
        let mut result = ReportResult::default();
        result.column_order = vec!["Time".to_string()];
        result.rows.push(ReportRow {
            cells: [("Time".to_string(), "100".to_string())]
                .into_iter()
                .collect(),
            key: vec!["a".to_string()],
            ..Default::default()
        });
        ed.result = Some(result);
        assert!(
            ed.last_export.is_none(),
            "nothing exported, nothing to open"
        );
        app.report_editor = Some(ed);

        let dir = std::env::temp_dir().join(format!("pb_gui_export_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("r.csv");
        let done = export_report_results(&mut app, &path.to_string_lossy());
        std::fs::remove_dir_all(&dir).ok();

        assert!(done.is_ok(), "the export should succeed: {done:?}");
        assert_eq!(
            app.report_editor.as_ref().unwrap().last_export.as_deref(),
            Some(path.to_string_lossy().as_ref()),
            "and the file it wrote is the one Open would hand to the desktop"
        );
    }

    /// Saving a baseline writes a snapshot the report engine can load straight
    /// back — the whole point of the button, and the thing a compile check
    /// can't tell you.
    #[test]
    fn saving_a_baseline_writes_a_snapshot_that_loads_again() {
        use crate::report::model::{ReportResult, ReportRow};

        let mut app = app();
        let mut ed = crate::gui::report_editor::ReportEditor::new(
            crate::gui::report_editor::ReportOrigin::Session(0),
            crate::report::Report::scratch("r"),
        );
        let mut result = ReportResult::default();
        result.rows.push(ReportRow {
            cells: [("Time".to_string(), "100".to_string())]
                .into_iter()
                .collect(),
            key: vec!["a".to_string()],
            ..Default::default()
        });
        ed.result = Some(result);
        app.report_editor = Some(ed);

        let dir = std::env::temp_dir().join(format!("pb_gui_baseline_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("r.baseline");
        let saved = save_report_baseline(&mut app, &path);
        let loaded = crate::report::Baseline::load(&path);
        std::fs::remove_dir_all(&dir).ok();

        assert!(saved.is_ok(), "saving should succeed: {saved:?}");
        let loaded = loaded.expect("the snapshot must load back");
        assert_eq!(loaded.rows.len(), 1);
        assert_eq!(
            loaded.rows[0].cells.get("Time").map(String::as_str),
            Some("100")
        );
        // The run is on disk now, so a rerun needn't warn about losing it.
        assert!(app.report_editor.as_ref().unwrap().results_exported);
    }

    /// Opening a report from disk must put it in the editor *and* in the
    /// session's report list, so it is listed beside the others and survives a
    /// restart -- the thing that makes it a real tab rather than a scratch view.
    #[test]
    fn opening_a_report_file_loads_it_into_the_editor_and_the_session() {
        let mut app = app();
        let dir = std::env::temp_dir().join(format!("pb_gui_open_rep_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("nightly.trail");
        std::fs::write(&path, "# name: nightly\nREPORT smoke\n").unwrap();

        let res = apply_open(&mut app, OpenKind::Report, &path);
        // Opening the same file twice must reuse its tab rather than stack up
        // duplicates that would then disagree about the file's contents.
        let again = apply_open(&mut app, OpenKind::Report, &path);
        std::fs::remove_dir_all(&dir).ok();

        assert!(res.is_ok() && again.is_ok(), "{res:?} {again:?}");
        let ed = app.report_editor.as_ref().expect("editor must be open");
        assert_eq!(ed.report.name, "nightly");
        assert_eq!(app.session.reports.len(), 1);
        assert_eq!(
            app.session.reports[0].path.as_deref(),
            Some(path.to_string_lossy().as_ref())
        );
    }

    /// Ctrl+S on a collection that already has a file writes it there and
    /// clears the unsaved marker -- no dialog, and nothing left to warn about.
    #[test]
    fn saving_a_collection_in_place_writes_it_and_clears_the_marker() {
        let mut app = app();
        let dir = std::env::temp_dir().join(format!("pb_save_active_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("c.hurl");
        std::fs::write(
            &path,
            "GET https://example.test
",
        )
        .unwrap();
        let ci = app.active_ci();
        app.session.collections[ci].path = Some(path.clone());

        assert!(
            save_active_has_path(&app),
            "a collection with a file saves without asking"
        );
        save_active(&mut app);
        // The fixture collection holds no requests, so what matters is that the
        // file was rewritten from it -- the seeded contents are gone.
        let on_disk = std::fs::read_to_string(&path).unwrap();
        std::fs::remove_dir_all(&dir).ok();

        assert!(
            !on_disk.contains("example.test"),
            "the file was rewritten from the collection: {on_disk:?}"
        );
        assert!(
            matches!(app.session.status, Some(crate::i18n::Status::Saved)),
            "and it reported success rather than an error"
        );
        assert!(
            !app.session.collections[ci].has_unsaved_edits(),
            "and the collection no longer counts as edited"
        );
        assert!(
            app.pending_pick.is_none(),
            "saving in place must not open a file dialog"
        );
    }

    #[test]
    fn choosing_an_export_format_renames_the_file() {
        // The writer is chosen by extension, so a format dropdown that leaves
        // the name ending `.csv` has not chosen anything.
        assert_eq!(
            super::retarget_extension("/tmp/report results.csv", "xlsx"),
            "/tmp/report results.xlsx"
        );
        // A name with dots in it keeps them: only the last segment is the
        // format.
        assert_eq!(
            super::retarget_extension("/tmp/run_v4.3.csv", "html"),
            "/tmp/run_v4.3.html"
        );
        // A bare name gains an extension rather than staying unwritable.
        assert_eq!(super::retarget_extension("results", "json"), "results.json");
        assert_eq!(super::retarget_extension("", "csv"), "results.csv");
    }

    /// The report editor wins when one is open: it is drawn over the request
    /// view, so it is what "save" is about.
    #[test]
    fn the_open_report_is_what_save_saves() {
        let mut app = app();
        assert_eq!(active_save_kind(&app), SaveKind::Collection);
        app.report_editor = Some(crate::gui::report_editor::ReportEditor::new(
            crate::gui::report_editor::ReportOrigin::Session(0),
            crate::report::Report::scratch("r"),
        ));
        assert_eq!(active_save_kind(&app), SaveKind::Report);
        assert!(
            !save_active_has_path(&app),
            "a scratch report has no file, so Save has to ask where"
        );
    }

    /// Saving a report writes its source and adopts the path, so the next
    /// Ctrl+S goes straight to the same file instead of asking again.
    #[test]
    fn saving_a_report_writes_its_source_and_adopts_the_path() {
        let mut app = app();
        let mut report = crate::report::Report::scratch("r");
        report.text = "# name: r\nREPORT smoke\n".into();
        app.report_editor = Some(crate::gui::report_editor::ReportEditor::new(
            crate::gui::report_editor::ReportOrigin::Session(0),
            report,
        ));
        app.session
            .reports
            .push(crate::persistence::PersistedReport {
                name: "r".into(),
                text: String::new(),
                path: None,
                git_origin: None,
                workspace_root: None,
                embedded_active: true,
            });

        let dir = std::env::temp_dir().join(format!("pb_gui_save_rep_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("r.trail");
        let saved = apply_save(&mut app, SaveKind::Report, &path);
        let text = std::fs::read_to_string(&path);
        std::fs::remove_dir_all(&dir).ok();

        assert!(saved.is_ok(), "saving should succeed: {saved:?}");
        assert_eq!(text.unwrap(), "# name: r\nREPORT smoke\n");
        let ed = app.report_editor.as_ref().unwrap();
        assert_eq!(ed.report.path.as_deref(), Some(path.as_path()));
        assert!(!ed.report.dirty);
        assert_eq!(
            app.session.reports[0].path.as_deref(),
            Some(path.to_string_lossy().as_ref())
        );
    }

    /// With nothing to snapshot the button reports why rather than writing an
    /// empty file that a later run would silently diff against.
    #[test]
    fn saving_a_baseline_without_a_run_is_refused() {
        let mut app = app();
        app.report_editor = Some(crate::gui::report_editor::ReportEditor::new(
            crate::gui::report_editor::ReportOrigin::Session(0),
            crate::report::Report::scratch("r"),
        ));
        let path = std::env::temp_dir().join("pb_gui_baseline_never_written.baseline");
        let err = save_report_baseline(&mut app, &path).expect_err("no result, no snapshot");
        assert_eq!(err, app.strings.report_baseline_no_result);
        assert!(!path.exists(), "nothing should have been written");
    }

    /// The declared output format leads the export dialog's filters, so the
    /// default choice is the one the report asked for.
    #[test]
    fn the_reports_own_output_format_leads_the_export_filters() {
        for (ext, expected) in [
            ("xlsx", "Excel"),
            ("json", "JSON"),
            ("html", "HTML"),
            ("pdf", "PDF"),
        ] {
            let filters = report_result_filters(ext);
            assert_eq!(filters[0].0, expected, "{ext} should lead");
            assert_eq!(filters.len(), 5, "every format stays available");
        }
        // Case is irrelevant: `# output: XLSX` is the same directive.
        assert_eq!(report_result_filters("XLSX")[0].0, "Excel");
    }

    /// With no (or an unwritable) format declared, the list keeps its usual
    /// order, so CSV remains the default it has always been.
    #[test]
    fn an_unknown_export_format_leaves_csv_leading() {
        for ext in ["", "csv", "docx"] {
            let filters = report_result_filters(ext);
            assert_eq!(filters[0].0, "CSV", "{ext:?} should leave CSV leading");
            assert_eq!(
                filters.iter().map(|f| f.0).collect::<Vec<_>>(),
                vec!["CSV", "JSON", "HTML", "Excel", "PDF"]
            );
        }
    }

    /// Escape is the way out of any dialog. Without it a modal can only be
    /// left by finding the right button, which on a confirmation that re-arms
    /// itself (every destructive one here does) means there is no way out at
    /// all for someone who opened it by accident.
    /// The sheet a dialog draws over the app swallows clicks, so the keyboard
    /// has to stand down to match: Ctrl+S with a git wizard open would
    /// otherwise save whatever tab happens to be behind it.
    #[test]
    fn every_dialog_takes_the_keyboard_with_it_not_just_the_mouse() {
        let mut a = app();
        assert!(!a.dialog_is_open(), "nothing is open to begin with");

        a.dialog = Some(Dialog::Rename {
            target: RenameTarget::Tab { ci: 0 },
            text: String::new(),
        });
        assert!(a.dialog_is_open());
        a.dialog = None;

        a.remote.open_load();
        assert!(a.dialog_is_open(), "the git wizard counts too");
        a.remote = Default::default();

        a.postman.open();
        assert!(a.dialog_is_open(), "and the Postman importer");
    }

    #[test]
    fn escape_closes_a_dialog_the_way_its_cancel_button_would() {
        let ctx = egui::Context::default();
        let mut a = app();

        let armed = |a: &mut GuiApp| {
            a.dialog = Some(Dialog::Rename {
                target: RenameTarget::Tab { ci: 0 },
                text: "whatever".to_string(),
            });
        };
        let frame_with = |a: &mut GuiApp, input: egui::RawInput| {
            let mut input = input;
            input.screen_rect = Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(900.0, 600.0),
            ));
            let _ = ctx.run_ui(input, |ui| show_dialog(a, ui.ctx()));
        };

        // An ordinary frame leaves it open — the dialog re-arms itself.
        armed(&mut a);
        frame_with(&mut a, egui::RawInput::default());
        assert!(a.dialog.is_some(), "a quiet frame leaves the dialog open");

        let mut esc = egui::RawInput::default();
        esc.events.push(egui::Event::Key {
            key: egui::Key::Escape,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: egui::Modifiers::NONE,
        });
        frame_with(&mut a, esc);
        assert!(a.dialog.is_none(), "Escape closes it");
    }

    /// Draw the menu bar once with the given input, so mnemonics are registered
    /// and the key handling runs exactly as it does in the real app.
    fn frame(app: &mut GuiApp, ctx: &egui::Context, input: egui::RawInput) {
        let mut input = input;
        input.screen_rect = Some(egui::Rect::from_min_size(
            egui::pos2(0.0, 0.0),
            egui::vec2(900.0, 600.0),
        ));
        let _ = ctx.run_ui(input, |ui| menu_bar(app, ui));
    }

    fn alt_held() -> egui::RawInput {
        egui::RawInput {
            modifiers: egui::Modifiers::ALT,
            ..Default::default()
        }
    }

    #[test]
    fn menu_mnemonics_are_unique_within_each_language() {
        // A duplicate would make one of the two menus unreachable from the
        // keyboard, and silently: the first match wins.
        for lang in [Language::English, Language::French, Language::Danish] {
            let s = crate::i18n::Strings::for_language(&lang);
            let keys = [
                s.gui_menu_file_key,
                s.gui_menu_edit_key,
                s.gui_menu_view_key,
                s.gui_menu_settings_key,
                s.gui_menu_help_key,
            ];
            for k in keys {
                assert_eq!(
                    k.chars().count(),
                    1,
                    "{lang:?} mnemonic {k:?} is not a single character"
                );
            }
            let mut seen: Vec<char> = keys.iter().filter_map(|k| mnemonic_char(k)).collect();
            seen.sort_unstable();
            let before = seen.len();
            seen.dedup();
            assert_eq!(before, seen.len(), "duplicate mnemonic in {lang:?}");
        }
    }

    #[test]
    fn pressing_alt_on_its_own_arms_the_menu_bar_and_a_second_alt_puts_it_away() {
        let ctx = egui::Context::default();
        let mut a = app();
        frame(&mut a, &ctx, alt_held());
        assert!(!a.alt_menus.is_armed(), "arming waits for the release");
        frame(&mut a, &ctx, egui::RawInput::default());
        assert!(a.alt_menus.is_armed());

        frame(&mut a, &ctx, alt_held());
        frame(&mut a, &ctx, egui::RawInput::default());
        assert!(!a.alt_menus.is_armed());
    }

    #[test]
    fn alt_used_as_a_chord_does_not_leave_the_bar_armed() {
        // Alt+F opens File outright; it must not also leave the bar waiting for
        // another letter once Alt comes back up.
        let ctx = egui::Context::default();
        let mut a = app();
        frame(&mut a, &ctx, egui::RawInput::default());

        let mut input = alt_held();
        input.events.push(egui::Event::Key {
            key: egui::Key::F,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: egui::Modifiers::ALT,
        });
        frame(&mut a, &ctx, input);
        frame(&mut a, &ctx, egui::RawInput::default());
        assert!(!a.alt_menus.is_armed());
    }

    #[test]
    fn a_mnemonic_opens_its_menu_both_as_a_chord_and_once_armed() {
        for chord in [true, false] {
            let ctx = egui::Context::default();
            let mut a = app();
            // One frame to register the buttons: egui ids are only known once
            // the widgets have been laid out.
            frame(&mut a, &ctx, egui::RawInput::default());
            let file = a.alt_menus.id_for('F').expect("File menu registered");

            let mut input = if chord {
                alt_held()
            } else {
                frame(&mut a, &ctx, alt_held());
                frame(&mut a, &ctx, egui::RawInput::default());
                assert!(a.alt_menus.is_armed());
                egui::RawInput::default()
            };
            let modifiers = if chord {
                egui::Modifiers::ALT
            } else {
                egui::Modifiers::NONE
            };
            input.events.push(egui::Event::Key {
                key: egui::Key::F,
                physical_key: None,
                pressed: true,
                repeat: false,
                modifiers,
            });
            frame(&mut a, &ctx, input);

            assert!(
                egui::Popup::is_id_open(&ctx, file.with("popup")),
                "chord={chord}: File menu should be open"
            );
            assert!(!a.alt_menus.is_armed(), "chord={chord}: opening disarms");
        }
    }

    #[test]
    fn escape_cancels_an_armed_menu_bar() {
        let ctx = egui::Context::default();
        let mut a = app();
        frame(&mut a, &ctx, alt_held());
        frame(&mut a, &ctx, egui::RawInput::default());
        assert!(a.alt_menus.is_armed());

        let mut input = egui::RawInput::default();
        input.events.push(egui::Event::Key {
            key: egui::Key::Escape,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: egui::Modifiers::NONE,
        });
        frame(&mut a, &ctx, input);
        assert!(!a.alt_menus.is_armed());
    }

    #[test]
    fn the_mnemonic_is_underlined_without_waiting_for_alt() {
        let ctx = egui::Context::default();
        let underlined = |title: &str, m: char| {
            let mut found = Vec::new();
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                let text = menu_title(ui, title, m);
                found = match text {
                    egui::WidgetText::LayoutJob(job) => job
                        .sections
                        .iter()
                        .filter(|s| s.format.underline != egui::Stroke::NONE)
                        .map(|s| {
                            job.text[usize::from(s.byte_range.start)..usize::from(s.byte_range.end)]
                                .to_string()
                        })
                        .collect::<Vec<_>>(),
                    // A plain string carries no formatting at all, which is how
                    // the "mnemonic isn't in the title" fallback comes back.
                    _ => Vec::new(),
                };
            });
            found
        };
        // The underline is what advertises the mnemonic, so it is there from the
        // first frame rather than only after the user has already found Alt.
        assert_eq!(underlined("Settings", 'S'), vec!["S".to_string()]);
        // Matched case-insensitively, and under the letter as the title spells
        // it rather than an uppercased copy of it.
        assert_eq!(underlined("File", 'F'), vec!["F".to_string()]);
        assert_eq!(underlined("edit", 'E'), vec!["e".to_string()]);
        // A mnemonic that isn't in the translated title underlines nothing at
        // all, rather than guessing at a character.
        assert_eq!(underlined("Aide", 'H'), Vec::<String>::new());
    }

    #[test]
    fn a_multibyte_title_underlines_the_right_character() {
        // The byte index came from searching an uppercased copy of the title,
        // which is only the same string when uppercasing preserves every byte
        // length. The "\u{fb00}" ligature is three bytes and uppercases to the
        // two bytes "FF", so every index past it was off by one: searching the
        // copy finds 'E' at byte 5, which in the original is the hyphen.
        let ctx = egui::Context::default();
        let mut found = Vec::new();
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            let text = menu_title(ui, "A\u{fb00}x-End", 'E');
            if let egui::WidgetText::LayoutJob(job) = text {
                found = job
                    .sections
                    .iter()
                    .filter(|s| s.format.underline != egui::Stroke::NONE)
                    .map(|s| {
                        job.text[usize::from(s.byte_range.start)..usize::from(s.byte_range.end)]
                            .to_string()
                    })
                    .collect();
            }
        });
        assert_eq!(found, vec!["E".to_string()], "underlined the wrong glyph");
    }
}