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
//! The GUI application: [`GuiApp`] wraps the shared [`Session`] with egui view
//! state and lays out the Postman-style panels every frame.
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, TryRecvError};
use std::time::Duration;
use eframe::egui::{self, Key, Modifiers};
use crate::i18n::Strings;
use crate::persistence::GuiView;
use crate::request::RequestView;
use crate::session::Session;
use super::report_editor::ReportOrigin;
use super::theme::GuiTheme;
use super::{
Focus, editor, environments, menu, postman, remote, report_editor, reports, requests, response,
};
/// Which section of the request editor (centre-top) is shown.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum EditorSection {
All,
Params,
Headers,
Body,
Auth,
Cookies,
Options,
Asserts,
Captures,
Computed,
Code,
}
/// Which section of the response viewer (centre-bottom) is shown.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ResponseSection {
Body,
Headers,
Asserts,
}
/// A modal dialog currently shown over the main UI.
pub enum Dialog {
/// Rename a request or collection tab.
Rename { target: RenameTarget, text: String },
/// Naming the parameter a right-clicked request field is being extracted
/// into. Carries where the text came from so the edit can be re-checked
/// against the request as it stands when the dialog is answered.
ExtractParameter {
ci: usize,
entry: usize,
target: super::editor::ExtractTarget,
value: String,
range: Option<std::ops::Range<usize>>,
name: String,
},
/// Building an `[Asserts]` line or a `[Captures]` row out of the response
/// on screen (right-click in the response viewer). See
/// [`super::probe::ProbeBuilder`].
ProbeBuilder(Box<super::probe::ProbeBuilder>),
/// The theme editor.
Theme(Box<super::menu::ThemeEditState>),
/// Simple text prompt (base URL, new env name, …).
Prompt { kind: PromptKind, text: String },
/// Closing a Workspace tab whose folder PaperBoy downloaded from git into
/// a throwaway directory: keep the folder (so the tab can be reopened
/// later) or delete it now? Never shown for a folder the user picked
/// themselves — the app must never delete one of those.
CloseGitWorkspace { ci: usize, root: std::path::PathBuf },
/// Quitting while some request edits exist only in memory. Confirming
/// closes the window for real; cancelling leaves everything as it was.
UnsavedQuit { count: usize, tabs: String },
/// Closing a tab that is holding request edits with nowhere on disk to go.
UnsavedCloseTab {
ci: usize,
name: String,
count: usize,
},
/// Exporting a report's results: a filename, and the format to write it in.
///
/// Its own dialog rather than the native save picker's filter dropdown,
/// because that dropdown only *filters* — picking "Excel" in it left the
/// name ending `.csv` and the format is chosen by the extension, so the
/// dropdown appeared to do nothing. Here the format and the name are the
/// same decision, sat next to each other, and changing one rewrites the
/// other. The native picker is still a Browse… away.
ExportResults { path: String },
/// A restored Workspace tab's downloaded folder has vanished since the
/// last session (typically `/tmp` swept between restarts). Offers to
/// redownload it, pinned to the exact commit it recorded.
WorkspaceReload {
ci: usize,
reload: Box<crate::persistence::PendingWorkspaceReload>,
},
/// Throw away in-memory edits and go back to what is on disk. `entry` is
/// `Some(idx)` for one request of the loaded file, `None` for the whole
/// file. Confirmed because a revert has no undo.
RevertToSaved {
ci: usize,
path: std::path::PathBuf,
entry: Option<usize>,
name: String,
},
/// Confirm deleting a request (context menu or the Delete key). Gated on the
/// `confirm_on_delete_request` preference; the delete itself stays undoable,
/// so the prompt is a guard against a stray keypress, not a point of no
/// return. `idx` is the entry's position in `collections[ci].entries`.
ConfirmDeleteRequest { ci: usize, idx: usize, name: String },
/// Confirm deleting a workspace file or folder *from disk*.
///
/// Always shown — it deliberately ignores the `confirm_on_delete_request`
/// preference, because that preference guards an *undoable* request delete
/// (Ctrl+Z brings it back), whereas removing a file or a whole folder from
/// disk has no undo at all. `file_count` is how many files a folder delete
/// would take (`1` for a file), so the prompt can say how much is at stake;
/// `unsaved` warns that in-memory edits under the item would be lost with
/// it.
DeleteWorkspaceItem {
ci: usize,
path: std::path::PathBuf,
is_dir: bool,
name: String,
file_count: usize,
unsaved: bool,
},
/// Confirm a "Run All" that would fire requests which may change server
/// state. Only raised when the collection holds at least one non-GET
/// request; a read-only collection runs with no friction. `total` is how
/// many requests will run, `non_get` how many of them are not GET.
ConfirmRunAll {
ci: usize,
total: usize,
non_get: usize,
},
/// The F1 keyboard-shortcuts overlay. Carries no state — its content is
/// derived from the shortcuts that exist — and is dismissed with Escape or
/// its close button like any other modal.
Shortcuts,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum OpenKind {
Collection,
Environment,
/// Open a `.trail` PaperTrail report in the report editor.
Report,
/// Open a folder as a Workspace (a filesystem tree of collections /
/// environments / reports), rather than a single file.
Workspace,
/// A `.json` file exported from Postman. The same load as a collection or
/// an environment — which of the two it is is read off the file — but
/// asked for in the user's own terms: they have an export, not a
/// "collection in Postman's JSON dialect".
PostmanExport,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SaveKind {
Collection,
/// Write the open report editor's `.trail` source to a chosen file.
Report,
/// Save the Global Environment with this id to a `.vars` file.
Environment(u64),
Response,
/// Export the open report editor's last run results (format by extension).
ReportResults,
/// Save the open report editor's last run as a `.baseline` snapshot, for a
/// later run to diff against via `BASELINE(FILE(…))`.
ReportBaseline,
}
#[derive(Clone)]
pub enum RenameTarget {
Request {
ci: usize,
idx: usize,
},
Tab {
ci: usize,
},
/// A workspace file or folder — its own name on disk, not a request inside
/// it. Reuses the rename dialog but is applied through the workspace's own
/// rename (a filesystem rename plus repointing everything that held the old
/// path), rather than by editing an in-memory title. The item's kind isn't
/// carried: renaming reads it off disk, and the dialog looks the same for a
/// file or a folder.
WorkspaceItem {
ci: usize,
path: std::path::PathBuf,
},
}
// Not `Copy`: `NewWorkspaceFolder` carries the folder the new one goes inside.
#[derive(Clone, PartialEq, Eq)]
pub enum PromptKind {
BaseUrl,
NewEnvName,
NewCollectionName,
/// Name for a new subfolder in a Workspace tab's tree, with the tab and the
/// folder it goes inside. Asked for in-app rather than through the
/// platform's dialog, as the file kinds are: a save dialog is built around
/// choosing a *file* name, and the folder pickers offer existing folders,
/// so neither asks the question "what should this new folder be called?"
/// as directly as a text box does.
NewWorkspaceFolder {
ci: usize,
dir: std::path::PathBuf,
},
}
/// Editable-code-view state for the request editor's Code section. Holds the
/// live text buffer the user edits (Hurl or resolved JSON) plus the identity of
/// the `(collection, entry, showing-Hurl)` it currently reflects. The buffer is
/// refreshed from the entry when you switch entry/representation or return to
/// the Code tab, but is otherwise the source of truth while you edit it (so
/// keystrokes are never clobbered by a re-render of the canonical text).
#[derive(Default)]
pub struct CodeEdit {
pub buf: String,
/// `(collection index, entry index, showing Hurl)` the buffer reflects, or
/// `None` when the Code tab isn't the active section.
pub key: Option<(usize, usize, bool)>,
/// The last parse error, shown beneath the editor; cleared on a good parse.
pub error: Option<String>,
}
pub struct GuiApp {
pub session: Session,
pub focus: Focus,
pub editor_section: EditorSection,
pub response_section: ResponseSection,
/// When true, the Response Body view shortens long string literals to a
/// `"head...tail"` overview (see [`crate::shared_utils::compact_long_strings`]).
/// Display-only: the Copy button always yields the full body.
pub response_compact: bool,
pub dialog: Option<Dialog>,
/// A native file/folder dialog currently open on a worker thread, with the
/// note of what to do once it answers. See [`super::filepick`] for why a
/// picker can't simply be called and awaited: doing so froze the window for
/// as long as the dialog was up, and stalled every other per-frame poll
/// with it.
pub pending_pick: Option<super::filepick::PendingPick<super::menu::PickAction>>,
/// Recomputed each frame from the active theme spec.
pub theme: GuiTheme,
/// Recomputed each frame from the active language.
pub strings: Strings,
/// Show the raw request as Hurl (vs. the resolved JSON preview) in the Code
/// section. Mirrors the terminal UI's `RequestView` toggle.
pub show_hurl: bool,
/// Editable-code-view buffer state for the request editor's Code section.
pub code_edit: CodeEdit,
/// An environment the Environments panel should expand and scroll to on the
/// next frame — set when one is opened from the workspace tree, where the
/// row that was clicked is nowhere near the panel that ends up holding it.
/// Cleared once the panel has had its chance to honour it.
pub reveal_env: Option<u64>,
/// Set when the Requests list's selection was moved by the keyboard, asking
/// the next render to scroll the newly selected row into view. One-shot:
/// cleared the frame the list honours it, so a later manual scroll isn't
/// yanked back. A keyboard move can land on a row that is off-screen (a long
/// collection, or a jump to first/last), where a mouse click never can.
pub reveal_selected: bool,
/// Filter text for the Environments panel's search box (a case-insensitive
/// substring of the environment name). Runtime-only, like the terminal
/// UI's — a filter is a way of finding something now, not a setting.
pub env_query: String,
/// Report row selected in the reports panel, if the reports view is open.
pub show_reports: bool,
/// The open PaperTrail report editor (Scratch-style blocks + source view),
/// if any. Opened from the reports list or a Workspace tree `.trail` file;
/// takes over the centre pane while present. See [`report_editor`].
pub report_editor: Option<report_editor::ReportEditor>,
/// Report runs that currently have no editor on screen, by
/// [`RunKey`](super::report_run::RunKey).
///
/// The editor is a view that gets dropped and rebuilt whenever the user
/// clicks a tab or opens another file; a run must survive that, both because
/// dropping its handle cancels the worker and because the rows it has
/// already collected are the whole point of having run it.
pub report_runs:
std::collections::HashMap<super::report_run::RunKey, super::report_run::ParkedRun>,
/// Edited reports whose editor is no longer on screen, by file path.
///
/// The editor is torn down and rebuilt from disk whenever the user clicks
/// another file, an environment, or a tab — so without this, editing a
/// report and glancing at anything else in the workspace silently threw
/// the edits away and handed back what the file still said. This is the
/// report half of [`Collection::workspace_pending`], and works the same
/// way: the unsaved text is parked when the view closes and taken back the
/// moment the same file is opened again.
///
/// [`Collection::workspace_pending`]: crate::collection::Collection::workspace_pending
pub report_pending: std::collections::HashMap<PathBuf, crate::report::Report>,
/// Git remote load/save UI state (self-contained in `remote.rs`).
pub remote: super::remote::RemoteUi,
pub postman: super::postman::PostmanUi,
/// An in-flight Workspace redownload (see [`Dialog::WorkspaceReload`]):
/// the tab it will rebind, the file that was selected before (relative to
/// the old, dead root) and the worker's result channel.
pub workspace_redownload: Option<(usize, Option<String>, Receiver<Result<PathBuf, String>>)>,
/// The PaperBoy logo texture, lazily uploaded on the first frame and shown
/// in the status bar. `None` until loaded (or if decoding ever fails).
pub logo: Option<egui::TextureHandle>,
/// Set when the user has moved a splitter or resized the window and the new
/// geometry has not been written to disk yet. Saving is deferred to the end
/// of the gesture (see [`GuiApp::record_layout`]) so a single drag doesn't
/// rewrite `state.json` once per frame.
layout_dirty: bool,
/// Set once the user has confirmed a quit that would discard unsaved
/// request edits, so the close request that follows isn't intercepted a
/// second time (which would make the window impossible to close).
pub(super) allow_close: bool,
/// Keyboard access to the top-level menus (Alt, then the mnemonic letter).
pub(super) alt_menus: super::menu::AltMenus,
}
/// The raw PNG bytes of the application logo, embedded at compile time so the
/// binary is self-contained (no runtime asset path to resolve). Used for both
/// the window/taskbar icon and the status-bar badge.
pub(super) const LOGO_PNG: &[u8] = include_bytes!("../../assets/paperboy_logo.png");
/// Decode the embedded logo into an `egui::IconData` for the window/taskbar
/// icon. Returns `None` if decoding fails (we then fall back to the platform
/// default rather than refusing to launch).
pub fn load_app_icon() -> Option<egui::IconData> {
let img = image::load_from_memory(LOGO_PNG).ok()?.to_rgba8();
let (width, height) = img.dimensions();
Some(egui::IconData {
rgba: img.into_raw(),
width,
height,
})
}
/// Decode the embedded logo into an egui image ready to upload as a texture.
fn logo_color_image() -> Option<egui::ColorImage> {
let img = image::load_from_memory(LOGO_PNG).ok()?.to_rgba8();
let (w, h) = img.dimensions();
Some(egui::ColorImage::from_rgba_unmultiplied(
[w as usize, h as usize],
img.as_raw(),
))
}
/// How a status message is marked: its icon and its colour.
///
/// The two say the same thing twice on purpose -- colour alone is no answer for
/// someone who cannot tell these two apart, and this line is where a failed
/// save is reported.
fn status_badge(status: &crate::i18n::Status, theme: &GuiTheme) -> (&'static str, egui::Color32) {
if status.is_ok() {
(super::icons::PASS, theme.ok)
} else {
(super::icons::WARNING, theme.err)
}
}
impl GuiApp {
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
// Register the Phosphor icon font so the tree/button icons render (see
// `gui::icons`). egui's bundled fonts don't cover them, so without this
// every icon shows as an empty "tofu" box.
//
// Light rather than Regular: icons repeat down the tree and across every
// toolbar, so their stroke weight sets how busy the chrome looks. At
// Regular they compete with the labels they sit beside — the eye lands
// on the icon first even though the *name* is what the user is looking
// for. Light keeps them legible while letting the text lead. Every
// variant shares the same codepoints, so `gui::icons` needs no change.
let mut fonts = egui::FontDefinitions::default();
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Light);
cc.egui_ctx.set_fonts(fonts);
// Larger default text so the client reads comfortably as a desktop app.
// egui 0.35 has no `Context::style`/`set_style`; scale every variant's
// text styles in place.
cc.egui_ctx.all_styles_mut(|style| {
for (_, font) in style.text_styles.iter_mut() {
font.size *= 1.08;
}
});
let session = Session::restored();
let session_view_is_hurl = session.default_request_view == RequestView::Hurl;
let strings = Strings::for_language(&session.language);
let theme = GuiTheme::from_spec(&session.active_theme_spec());
let mut app = Self {
session,
focus: Focus::List,
editor_section: EditorSection::All,
response_section: ResponseSection::Body,
response_compact: false,
reveal_env: None,
reveal_selected: false,
env_query: String::new(),
dialog: None,
pending_pick: None,
theme,
strings,
show_hurl: session_view_is_hurl,
code_edit: CodeEdit::default(),
show_reports: false,
report_editor: None,
report_runs: std::collections::HashMap::new(),
report_pending: std::collections::HashMap::new(),
remote: super::remote::RemoteUi::default(),
postman: super::postman::PostmanUi::default(),
workspace_redownload: None,
logo: None,
layout_dirty: false,
allow_close: false,
alt_menus: Default::default(),
};
app.restore_view();
app.restore_workspace_selection();
app
}
/// A `GuiApp` around a ready-made session, for tests that need to draw a
/// panel headlessly. `new` can't serve: it wants an `eframe` creation
/// context and it restores the *real* user's session from disk.
#[cfg(test)]
pub(crate) fn for_test(session: Session) -> Self {
let strings = Strings::for_language(&session.language);
let theme = GuiTheme::from_spec(&session.active_theme_spec());
Self {
session,
focus: Focus::List,
editor_section: EditorSection::All,
response_section: ResponseSection::Body,
response_compact: false,
reveal_env: None,
reveal_selected: false,
env_query: String::new(),
dialog: None,
pending_pick: None,
theme,
strings,
show_hurl: false,
code_edit: CodeEdit::default(),
show_reports: false,
report_editor: None,
report_runs: std::collections::HashMap::new(),
report_pending: std::collections::HashMap::new(),
remote: super::remote::RemoteUi::default(),
postman: super::postman::PostmanUi::default(),
workspace_redownload: None,
logo: None,
layout_dirty: false,
allow_close: false,
alt_menus: Default::default(),
}
}
/// Reopen the active Workspace tab on whatever node was last selected in
/// its tree.
///
/// A workspace tab's *collection* file is already restored by
/// [`crate::persistence::PersistedTab::into_collection`] (it re-reads the
/// file from disk), but a `.trail` report or a `.vars` environment opened
/// from the tree left no trace at all — the tab came back with an empty
/// right-hand pane and no hint of what had been open. `workspace_selected`
/// closes that gap; the path was already checked to still exist when the
/// state was loaded.
fn restore_workspace_selection(&mut self) {
let Some(selected) = self.workspace_selection() else {
return;
};
if crate::workspace::is_report_file(&selected) {
self.reopen_workspace_report(&selected);
} else if crate::workspace::is_env_file(&selected) {
self.session.open_workspace_environment(&selected);
}
}
/// The path the active tab's tree has selected, if it is a Workspace tab.
fn workspace_selection(&self) -> Option<std::path::PathBuf> {
self.session
.collections
.get(self.active_ci())
.filter(|c| c.workspace_root.is_some())
.and_then(|c| c.workspace_selected.clone())
}
/// Open the Workspace-tree report at `path` in the centre column.
fn reopen_workspace_report(&mut self, path: &std::path::Path) {
// A report *tab* being restored by `restore_view` outranks this: that
// is what the centre column was actually showing.
if self.report_editor.is_some() {
return;
}
match crate::report::Report::load_local(path) {
Ok(report) => {
self.open_report_editor(ReportOrigin::Workspace, report);
self.show_reports = false;
self.focus = Focus::Main;
}
// A report that has since become unreadable is not worth
// interrupting the launch over — the tree still shows it.
Err(_) => {}
}
}
/// Switch to tab `idx`, leaving the tab being left as it was found and
/// putting the one arrived at back the way it was.
///
/// A report opened from a Workspace tree belongs to that tab, so it is
/// closed on the way out (a standalone session report is the centre
/// column's own and stays). Coming *back* then has to reopen it, or leaving
/// a tab for a moment silently swapped the report you were editing for
/// whichever collection the tree happened to load last — which is what the
/// tab-switching path did before: it closed the editor and never reopened
/// one. The tree already records what was selected (`workspace_selected`),
/// the same field a restart restores from, so a tab switch is just a
/// restore of the tab being arrived at.
pub fn switch_to_tab(&mut self, idx: usize) {
self.session.activate_tab(idx);
if self
.report_editor
.as_ref()
.is_some_and(|e| e.is_workspace())
{
self.close_report_editor();
}
// Only the *report* half of the tab's selection is restored here, not
// the environment half: `open_workspace_environment` loads a fresh copy
// every time it is called, so replaying it on each tab switch would
// pile up "staging (2)", "staging (3)" globals. At launch there is
// nothing loaded yet, so restoring both is right there and only there.
if let Some(selected) = self.workspace_selection()
&& crate::workspace::is_report_file(&selected)
{
self.reopen_workspace_report(&selected);
}
self.focus = Focus::Tabs;
self.session.save();
}
/// Reopen the centre column on whatever it was showing last time.
///
/// Only session report tabs are restored here: a report opened from a
/// Workspace `.trail` file has no index in the session's report list, so it
/// is restored from the workspace tree instead (see
/// [`Self::restore_workspace_selection`]). A stale index falls back to the
/// reports list.
fn restore_view(&mut self) {
match self.session.gui.view {
GuiView::Requests => {}
GuiView::Reports => self.show_reports = true,
GuiView::Report(i) => {
self.show_reports = true;
let Some(report) = self.session.reports.get(i).cloned() else {
return;
};
self.open_report_editor(ReportOrigin::Session(i), report.into_report());
if self.session.gui.report_source_view
&& let Some(ed) = &mut self.report_editor
{
ed.view = report_editor::EditorView::Source;
}
}
}
}
/// Close the report editor, keeping its run alive.
///
/// Every path that takes the editor off screen goes through here rather
/// than assigning `None`, because assigning `None` drops the
/// [`RunHandle`](super::report_run::RunHandle) — which cancels the worker
/// and throws away the rows it had already collected.
pub fn close_report_editor(&mut self) {
let Some(mut ed) = self.report_editor.take() else {
return;
};
// Unsaved edits outlive the view that was showing them. Closing the
// editor is not a decision about the *document* — it happens on every
// click that puts something else in the centre column — so throwing
// the text away here made looking at anything else in the workspace a
// way to lose work with no warning and no undo.
if ed.report.dirty
&& let Some(path) = ed.report.path.clone()
{
self.report_pending.insert(path, ed.report.clone());
}
let key = ed.run_key();
let parked = ed.park_run();
if parked.is_worth_keeping() {
self.report_runs.insert(key, parked);
} else {
self.report_runs.remove(&key);
}
}
/// Keep every parked run moving, and repaint while any is still going.
///
/// A run that nobody is looking at still has to fold its streamed rows into
/// its grid, so that coming back to it shows where it actually got to
/// rather than where it was when you left.
fn poll_parked_runs(&mut self, ctx: &egui::Context) {
// The run being shown is polled by the editor itself.
let showing = self.report_editor.as_ref().map(|e| e.run_key());
let mut live = false;
for (key, parked) in self.report_runs.iter_mut() {
if Some(key) == showing.as_ref() {
continue;
}
live |= parked.pump();
}
if live {
ctx.request_repaint_after(Duration::from_millis(80));
}
}
/// Open `report` in the block editor, restoring the panel sizes the user
/// last dragged it to.
///
/// Every report opens through here — restored at startup, picked from the
/// reports list, created fresh, or opened from a Workspace tree — because a
/// resized palette or diagnostics panel that only came back on *one* of
/// those paths reads as the setting not being saved at all.
pub fn open_report_editor(&mut self, origin: ReportOrigin, report: crate::report::Report) {
// Whatever was open keeps its run *and* its unsaved edits, so this has
// to happen before the parked edits below are looked for — the report
// being opened may be the one just closed.
self.close_report_editor();
// A report edited and then navigated away from comes back as it was
// left. The caller has just read the file off disk (every path here
// does), which is the older of the two by definition.
let report = match report
.path
.as_ref()
.and_then(|p| self.report_pending.remove(p))
{
Some(parked) => parked,
None => report,
};
let mut ed = report_editor::ReportEditor::new(origin, report);
if let Some(h) = self.session.gui.report_diag_height {
ed.diag_h = h;
}
if let Some(w) = self.session.gui.report_palette_width {
ed.palette_w = w;
}
if let Some(h) = self.session.gui.report_detail_height {
ed.detail_h = h;
}
if let Some(h) = self.session.gui.report_summary_height {
ed.summary_h = h;
}
// And this report takes back its own run.
if let Some(parked) = self.report_runs.remove(&ed.run_key()) {
ed.adopt_run(parked);
}
self.report_editor = Some(ed);
}
/// Fold one freshly-measured panel size into the saved layout, flagging the
/// layout dirty when it actually moved. Sub-pixel jitter (egui lays panels
/// out in floats, so a "still" splitter wobbles fractionally) is ignored,
/// otherwise every frame would look like a resize.
fn record_size(dirty: &mut bool, slot: &mut Option<f32>, measured: f32) {
if slot.is_none_or(|old| (old - measured).abs() > 0.5) {
*slot = Some(measured);
*dirty = true;
}
}
/// Capture the window size and the current centre-column view, then write
/// the whole layout out once the user has finished dragging.
///
/// Deferring the save until no mouse button is down means one splitter drag
/// costs a single `state.json` write instead of one per frame, while still
/// landing on disk the moment the gesture ends rather than only at exit
/// (which a crash or a `kill` would skip).
fn record_layout(&mut self, ctx: &egui::Context, root_size: egui::Vec2) {
let mut dirty = self.layout_dirty;
// `inner_rect` is the window's true frame, but no Wayland compositor
// reports one back to the client, so fall back to the size of the root
// `Ui` — for the root viewport that spans the window's inner area, in
// the same logical points `with_inner_size` expects.
let size = ctx
.input(|i| i.viewport().inner_rect)
.map_or(root_size, |r| r.size());
{
let (w, h) = (size.x, size.y);
// Some compositors report a zero-sized viewport while the window is
// minimised; persisting that would reopen an invisible window.
if w >= super::MIN_WINDOW.0 && h >= super::MIN_WINDOW.1 {
let moved = self
.session
.gui
.window
.is_none_or(|(ow, oh)| (ow - w).abs() > 0.5 || (oh - h).abs() > 0.5);
if moved {
self.session.gui.window = Some((w, h));
dirty = true;
}
}
}
let view = match (&self.report_editor, self.show_reports) {
(Some(ed), _) => match ed.origin {
ReportOrigin::Session(i) => GuiView::Report(i),
// A workspace report is shown *inside* its workspace tab, so
// the view to come back to is that tab; which report it was
// showing is restored from the tree's own selection.
ReportOrigin::Workspace => GuiView::Requests,
},
(None, true) => GuiView::Reports,
(None, false) => GuiView::Requests,
};
if self.session.gui.view != view {
self.session.gui.view = view;
dirty = true;
}
if let Some(ed) = &self.report_editor {
let source = ed.view == report_editor::EditorView::Source;
if self.session.gui.report_source_view != source {
self.session.gui.report_source_view = source;
dirty = true;
}
Self::record_size(
&mut dirty,
&mut self.session.gui.report_diag_height,
ed.diag_h,
);
Self::record_size(
&mut dirty,
&mut self.session.gui.report_palette_width,
ed.palette_w,
);
Self::record_size(
&mut dirty,
&mut self.session.gui.report_detail_height,
ed.detail_h,
);
Self::record_size(
&mut dirty,
&mut self.session.gui.report_summary_height,
ed.summary_h,
);
}
self.layout_dirty = dirty;
if dirty && !ctx.input(|i| i.pointer.any_down()) {
self.session.save();
self.layout_dirty = false;
}
}
/// The active collection tab index, clamped into range.
pub fn active_ci(&self) -> usize {
self.session
.active_tab
.min(self.session.collections.len().saturating_sub(1))
}
/// Run the selected request of the active collection.
pub fn run_active(&mut self) {
let ci = self.active_ci();
self.session.run_entry(ci);
self.session.save();
}
/// Run every request of collection `ci` ("Run All"), asking first when the
/// collection holds any non-GET request. A read-only (all-GET) collection
/// runs with no friction; anything that might change server state raises a
/// confirmation that says how many requests will run and how many of them
/// are not GET, so double-click-to-send isn't the only thing standing
/// between a stray click and a collection full of writes.
pub fn request_run_all(&mut self, ci: usize) {
let (total, non_get) = self
.session
.collections
.get(ci)
.map(|c| super::requests::run_all_confirm_counts(&c.entries))
.unwrap_or((0, 0));
if non_get == 0 {
self.session.run_all_entries(ci);
} else {
self.dialog = Some(Dialog::ConfirmRunAll { ci, total, non_get });
}
}
/// Reopen the most recently deleted request in the active collection (Edit
/// ▸ Undo Delete Request), selecting it once it's back. Shares its history
/// and 20-entry cap with the terminal UI's `u` — see
/// [`crate::collection::Collection::restore_last_deleted`] — so a request
/// deleted from either front-end can be brought back from either.
pub fn undo_delete_request(&mut self) {
let ci = self.active_ci();
let col = &mut self.session.collections[ci];
let Some(idx) = col.restore_last_deleted() else {
return;
};
col.selected_entry = idx;
col.invalidate_request_json();
self.session.save();
}
/// Delete request `idx` of collection `ci`, honouring the
/// `confirm_on_delete_request` preference: raise the confirmation when it is
/// on, delete straight away when it is off. Every GUI delete path (the row's
/// context menu and the Requests-panel Delete key) goes through here so the
/// preference can't be respected by one and skipped by the other.
pub fn request_delete_request(&mut self, ci: usize, idx: usize) {
if self.session.confirm_on_delete_request {
let name = self.entry_display_name(ci, idx);
self.dialog = Some(Dialog::ConfirmDeleteRequest { ci, idx, name });
} else {
self.delete_request_now(ci, idx);
}
}
/// Remove request `idx` of collection `ci`, recording it for Undo Delete
/// Request, and keep the selection in range. The one place the actual
/// deletion happens, so the confirmed and unconfirmed paths behave alike.
pub fn delete_request_now(&mut self, ci: usize, idx: usize) {
let Some(col) = self.session.collections.get_mut(ci) else {
return;
};
if col.remove_entry_recording_undo(idx).is_some() {
if col.selected_entry >= col.entries.len() {
col.selected_entry = col.entries.len().saturating_sub(1);
}
col.invalidate_request_json();
self.session.save();
}
}
/// The name to show for request `idx` of collection `ci` in a prompt: its
/// leaf title, or its URL when it has no title yet.
fn entry_display_name(&self, ci: usize, idx: usize) -> String {
self.session
.collections
.get(ci)
.and_then(|c| c.entries.get(idx))
.map(|e| {
let leaf = crate::tree::entry_path(&e.title).pop().unwrap_or_default();
if leaf.trim().is_empty() {
e.url.clone()
} else {
leaf
}
})
.unwrap_or_default()
}
/// Close tab `ci`, first asking what to do with its folder when that folder
/// is a git download PaperBoy made itself. Every close path in the GUI goes
/// through here so a downloaded workspace can never be dropped silently,
/// leaving an orphaned temp folder behind with no way back to it.
pub fn request_close_tab(&mut self, ci: usize) {
// Edits first: a downloaded-workspace tab can be both, and losing
// unsaved work is the more serious of the two.
let count = self
.session
.collections
.get(ci)
.map_or(0, |c| c.unsaved_edit_count());
if count > 0 {
self.dialog = Some(Dialog::UnsavedCloseTab {
ci,
name: self.session.collections[ci].name.clone(),
count,
});
return;
}
self.close_tab_now(ci);
}
/// Close tab `ci`, having already settled what to do about any unsaved
/// edits. Still asks about a git-downloaded Workspace folder.
pub fn close_tab_now(&mut self, ci: usize) {
let downloaded = self
.session
.collections
.get(ci)
.filter(|c| c.workspace_downloaded_from_git)
.and_then(|c| c.workspace_root.clone());
match downloaded {
Some(root) if ci != 0 => {
self.dialog = Some(Dialog::CloseGitWorkspace { ci, root });
}
_ => self.session.close_tab(ci),
}
}
/// Ask about the next Workspace tab whose downloaded folder went missing,
/// one at a time so several affected tabs don't stack up modal dialogs.
/// Called every frame; a no-op once the queue is drained.
pub fn poll_workspace_reload_prompts(&mut self) {
if self.dialog.is_some() || self.workspace_redownload.is_some() {
return;
}
if let Some((ci, reload)) = self.session.pending_workspace_reloads.pop_front() {
self.dialog = Some(Dialog::WorkspaceReload {
ci,
reload: Box::new(reload),
});
}
}
/// Start redownloading tab `ci`'s Workspace, pinned to the exact commit it
/// recorded. Never prompts for a token (tokens are deliberately never
/// persisted), so a private repo fails here with an auth error and the user
/// must reload it through "Load workspace from Git…" instead.
pub fn start_workspace_redownload(
&mut self,
ci: usize,
reload: crate::persistence::PendingWorkspaceReload,
) {
let rx = crate::tui::remote::spawn_workspace_redownload(reload.origin);
self.workspace_redownload = Some((ci, reload.relative_selected_path, rx));
}
/// Drive an in-flight Workspace redownload (called every frame). On success
/// the tab is rebound to the fresh folder and the previously-open file
/// re-selected; a failure — most often the recorded commit no longer being
/// reachable (force-push, rebase, deleted branch/tag) — is reported and the
/// tab simply stays empty.
pub fn poll_workspace_redownload(&mut self) {
let Some((ci, relative, rx)) = self.workspace_redownload.take() else {
return;
};
match rx.try_recv() {
Ok(Ok(root)) => self
.session
.rebind_redownloaded_workspace(ci, root, relative),
Ok(Err(e)) => self.session.status = Some(crate::i18n::Status::WorkspaceReloadFailed(e)),
Err(TryRecvError::Empty) => {
// Still running — put it back for the next frame.
self.workspace_redownload = Some((ci, relative, rx));
}
Err(TryRecvError::Disconnected) => {}
}
}
/// A stroke used to outline the focused panel (accent) vs. others (dim).
///
/// The width is **constant** across states — only the colour changes — so
/// focusing a panel never changes its frame's footprint and therefore never
/// nudges the panel's contents by a pixel. (An `egui` `Frame` counts its
/// stroke width as part of its size, so varying the width would shift the
/// body inward on focus.)
pub fn focus_stroke(&self, panel: Focus) -> egui::Stroke {
let color = if self.focus == panel {
self.theme.accent
} else {
self.theme.raised()
};
egui::Stroke::new(1.6, color)
}
/// Wrap a panel body in a titled, focus-aware frame and register a click on
/// it as focusing that panel.
/// A red band above the request editor naming every `{{ VAR }}` the selected
/// request references that nothing defines.
///
/// Derived state, recomputed each frame rather than stored: it is the exact
/// answer for the request that is on screen *now*, so it appears the moment
/// the typo is made and vanishes the moment it is fixed. That is also why
/// there is no dismiss button — there is nothing to dismiss, only something
/// to fix. Colouring the tokens red in the editor (see `editor.rs`) says
/// *where*; this says *that*, for the tokens scrolled out of view.
///
/// The headline and the names, and nothing else. A line of advice under
/// them ("add them to an environment, or check the spelling") only told
/// someone looking at a list of their own variable names what they already
/// knew, in small dim type, and pushed the request itself further down the
/// screen every time it appeared.
///
/// The one exception is a loaded environment that defines them but is
/// neither active nor linked: that is not advice, it is the answer, and the
/// list of names cannot say it.
fn undefined_vars_banner(&mut self, ui: &mut egui::Ui) {
let ci = self.active_ci();
let Some(col) = self.session.collections.get(ci) else {
return;
};
let env = self.session.effective_env(ci);
let missing = crate::request::undefined_request_keys(col, env.as_ref());
if missing.is_empty() {
return;
}
let in_envs = self.session.envs_defining_keys(ci, &missing);
let s = &self.strings;
let headline = if missing.len() == 1 {
s.gui_undefined_banner_one.to_string()
} else {
s.gui_undefined_banner_many
.replace("{n}", &missing.len().to_string())
};
let hint = (!in_envs.is_empty()).then(|| {
s.env_undefined_in_loaded_env
.replace("{envs}", &in_envs.join(", "))
});
let th = self.theme;
// Drawn inline at the top of the centre panel rather than in a
// `Panel::top`: a panel would reserve a fixed strip and clip the list
// of names, and this band's height depends on how many names there are.
egui::Frame::new()
.fill(th.panel)
.stroke(egui::Stroke::new(1.0, th.err))
.inner_margin(6.0)
.corner_radius(4.0)
.show(ui, |ui| {
ui.set_min_width(ui.available_width());
ui.label(egui::RichText::new(headline).color(th.err).strong());
ui.horizontal_wrapped(|ui| {
ui.label(
egui::RichText::new(missing.join(", "))
.color(th.err)
.monospace(),
);
});
if let Some(hint) = hint {
ui.horizontal_wrapped(|ui| {
ui.label(egui::RichText::new(hint).color(th.err));
});
}
});
ui.add_space(4.0);
}
/// Names the selected request when it carries both a raw body and form
/// fields, which Hurl cannot send together.
///
/// Beside the undefined-variables banner and for the same reason: the
/// Body section says it in place and offers the fix, but a user who is
/// looking at Headers (or at nothing in particular) would otherwise press
/// Send, watch a 200 come back, and never learn that none of their form
/// fields left the machine. Recomputed each frame, like the banner above
/// it, so it appears and disappears with the request itself.
fn body_form_conflict_banner(&mut self, ui: &mut egui::Ui) {
let ci = self.active_ci();
let Some(col) = self.session.collections.get(ci) else {
return;
};
if crate::request::body_form_conflicts(col).is_empty() {
return;
}
let th = self.theme;
let s = &self.strings;
egui::Frame::new()
.fill(th.panel)
.stroke(egui::Stroke::new(1.0, th.err))
.inner_margin(6.0)
.corner_radius(4.0)
.show(ui, |ui| {
ui.set_min_width(ui.available_width());
ui.label(
egui::RichText::new(s.gui_body_conflict_headline)
.color(th.err)
.strong(),
);
ui.label(egui::RichText::new(s.gui_body_conflict_detail).color(th.text));
});
ui.add_space(4.0);
}
pub fn panel_frame<R>(
&mut self,
ui: &mut egui::Ui,
panel: Focus,
add_contents: impl FnOnce(&mut GuiApp, &mut egui::Ui) -> R,
) -> R {
let stroke = self.focus_stroke(panel);
// Register a background click-sense over the whole panel *before* its
// contents, so it sits behind the interior widgets: a click on empty
// space focuses the panel, but a click that lands on a list row, button
// or field goes to that widget instead (egui routes a click to the
// top-most — i.e. last-registered — widget under the pointer, so the
// background must be registered first).
let bg_id = ui.id().with(("panel_bg", panel));
let bg = ui.interact(ui.max_rect(), bg_id, egui::Sense::click());
let frame = egui::Frame::new()
.stroke(stroke)
.fill(self.theme.panel)
.inner_margin(6.0)
.corner_radius(4.0);
let resp = frame.show(ui, |ui| {
ui.set_min_size(ui.available_size());
add_contents(self, ui)
});
if bg.clicked() {
self.focus = panel;
}
resp.inner
}
/// Whether a dialog is up. Every one of them covers the app with a sheet
/// that swallows clicks, so the keyboard has to stand down to match —
/// otherwise Ctrl+S while a git wizard is open saves whatever happens to be
/// behind it, which is not what the person typing meant.
pub fn dialog_is_open(&self) -> bool {
self.dialog.is_some() || self.remote.is_open() || self.postman.is_open()
}
fn handle_global_keys(&mut self, ctx: &egui::Context) {
if self.dialog_is_open() {
return; // let the modal own the keyboard
}
// Whether a widget (a text field, most importantly) held the keyboard at
// the end of the previous frame. The list keys and the `?` help key must
// stand down while something is being typed into, or Delete/arrows/`?`
// would edit that text instead of driving the panel behind it.
let no_widget_focus = ctx.memory(|m| m.focused().is_none());
// Tab / Shift+Tab cycle the focused *panel*, exactly like the terminal
// UI. We pull Tab key-presses straight out of the event queue rather
// than using `consume_key`: its `Modifiers::NONE` pattern also matches
// Shift+Tab (egui's `matches_logically` only rejects *missing* pattern
// modifiers, not *extra* ones), so a plain-Tab check would swallow
// Shift+Tab and both would cycle forwards.
let dir = ctx.input_mut(|i| {
let mut dir: Option<bool> = None;
i.events.retain(|e| match e {
egui::Event::Key {
key: Key::Tab,
pressed: true,
modifiers,
..
} => {
dir = Some(!modifiers.shift); // Shift+Tab → backwards
false // consume it
}
_ => true,
});
dir
});
// egui records its *own* Tab/Shift+Tab focus-traversal direction in
// `Memory::begin_pass`, which runs *before* this handler — so draining
// the events above isn't enough to stop it walking focus across every
// interactive widget (the tab bar, buttons, fields, …). Cancel that
// direction every frame so Tab only ever moves our panel focus, never
// egui's widget focus.
ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
if let Some(forward) = dir {
self.focus = self.focus.cycle(forward);
}
// Ctrl+Enter or F5 sends the current request (parity with the TUI's F5).
let send = ctx.input_mut(|i| {
i.consume_key(Modifiers::COMMAND, Key::Enter) || i.consume_key(Modifiers::NONE, Key::F5)
});
if send {
self.run_active();
}
// Ctrl+S saves whatever is in front of the user, by exactly the code
// the File > Save entry runs -- the shortcut and the menu item must not
// be able to disagree about what "save" means.
if ctx.input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::S)) {
super::menu::save_active(self);
}
// Ctrl+Shift+S is Save As: the same target, but always asking where.
if ctx.input_mut(|i| i.consume_key(Modifiers::COMMAND | Modifiers::SHIFT, Key::S)) {
let kind = super::menu::active_save_kind(self);
super::menu::save_via_picker(self, kind);
}
// Ctrl+W closes the active tab.
if ctx.input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::W)) {
self.request_close_tab(self.active_ci());
}
// Ctrl+Z undoes the last request delete, by the exact code the Edit ▸
// Undo Delete Request menu item runs so the two can't disagree.
//
// Gated on the report editor not being on screen: it has its own Ctrl+Z
// (block-structure undo, and egui's own text undoer in the source view),
// handled later in the frame inside `report_editor::ui`. Consuming the
// key here would take it away from that editor while it is the surface
// the keyboard is aimed at, so the global binding stands down whenever
// the report editor is up and only claims Ctrl+Z otherwise.
//
// Gated on nothing being typed into for the same reason: every text
// field in the window has its own Ctrl+Z, and a global binding that
// consumed the key first took undo away from all of them -- typing in a
// URL, a header or a generated expression and pressing Ctrl+Z resurrected
// a deleted request instead of undoing what had just been typed.
if self.report_editor.is_none()
&& no_widget_focus
&& ctx.input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::Z))
{
self.undo_delete_request();
}
// F1 opens the keyboard-shortcuts overlay. `dialog_is_open` gated this
// whole handler, so it can't fire while another modal is up — which is
// what keeps the overlay from fighting the other dialogs.
let help = ctx.input_mut(|i| {
i.consume_key(Modifiers::NONE, Key::F1)
// `?` is the other conventional help key, but it is also a
// character someone may be typing into a URL or body, so only
// honour it when no widget owns the keyboard.
|| (no_widget_focus && i.consume_key(Modifiers::SHIFT, Key::Questionmark))
});
if help {
self.dialog = Some(Dialog::Shortcuts);
}
// Requests-panel keys, but only when that panel holds focus and nothing
// is being typed into: Delete or an arrow while a rename field, the
// list filter or a URL cell has the keyboard must edit that text, not
// reach past it to move or destroy a request. egui reports the focus
// held at the end of the previous frame, which is exactly the state
// these keys should answer to.
if self.focus == Focus::List && no_widget_focus {
self.handle_list_keys(ctx);
}
}
/// Keyboard for the Requests panel: move the selection (Up/Down, Home/End),
/// run it (Enter), rename it (F2) or delete it (Delete). Only reached when
/// the panel holds focus and no widget owns the keyboard (see the call site
/// in [`Self::handle_global_keys`]).
///
/// A Workspace tab's list is not an ordinary request list but a filesystem
/// tree of folders, collection files, reports and environments with no
/// single "selected request" — so it has a keyboard of its own, one that
/// also has to expand and collapse rows and act on whichever kind the cursor
/// is on. That lives in [`super::requests::handle_ws_tree_keys`], and this
/// hands straight over to it; everything below is for an ordinary
/// collection.
fn handle_list_keys(&mut self, ctx: &egui::Context) {
let ci = self.active_ci();
let Some(col) = self.session.collections.get(ci) else {
return;
};
if col.is_workspace() {
super::requests::handle_ws_tree_keys(self, ctx, ci);
return;
}
let order = super::requests::nav_entry_order(&self.session.collections[ci]);
if order.is_empty() {
return; // nothing to select, run, rename or delete
}
let (up, down, home, end, enter, f2, del) = ctx.input_mut(|i| {
(
i.consume_key(Modifiers::NONE, Key::ArrowUp),
i.consume_key(Modifiers::NONE, Key::ArrowDown),
i.consume_key(Modifiers::NONE, Key::Home),
i.consume_key(Modifiers::NONE, Key::End),
i.consume_key(Modifiers::NONE, Key::Enter),
i.consume_key(Modifiers::NONE, Key::F2),
i.consume_key(Modifiers::NONE, Key::Delete),
)
});
// Where the current selection sits in the on-screen order, so a move is
// relative to what the user sees rather than the raw `entries` order.
let sel = self.session.collections[ci].selected_entry;
let pos = order.iter().position(|&i| i == sel).unwrap_or(0);
let last = order.len() - 1;
let target = if up {
Some(pos.saturating_sub(1))
} else if down {
Some((pos + 1).min(last))
} else if home {
Some(0)
} else if end {
Some(last)
} else {
None
};
if let Some(p) = target {
let idx = order[p];
let col = &mut self.session.collections[ci];
col.selected_entry = idx;
col.list_cursor = idx;
col.invalidate_request_json();
// Ask the next render to bring the row into view (see
// `reveal_selected`); a jump to first/last, or a step in a long
// collection, can land off-screen.
self.reveal_selected = true;
}
if enter {
self.run_active();
}
if f2 {
let idx = self.session.collections[ci].selected_entry;
if let Some(entry) = self.session.collections[ci].entries.get(idx) {
let text = entry.title.clone();
self.dialog = Some(Dialog::Rename {
target: RenameTarget::Request { ci, idx },
text,
});
}
}
if del {
let idx = self.session.collections[ci].selected_entry;
self.request_delete_request(ci, idx);
}
}
fn tab_strip(&mut self, ui: &mut egui::Ui) {
let focused = self.focus == Focus::Tabs;
let lbl_rename = self.strings.gui_rename_ellipsis;
let lbl_close = self.strings.gui_close_tab;
let mut open_rename: Option<(usize, String)> = None;
let mut close_tab: Option<usize> = None;
ui.horizontal(|ui| {
ui.add_space(2.0);
let active = self.active_ci();
let names: Vec<(usize, String, bool, bool, bool)> = self
.session
.collections
.iter()
.enumerate()
.map(|(i, c)| {
(
i,
c.name.clone(),
c.git_origin.is_some(),
c.is_workspace(),
// A Workspace tab may also be holding parked edits for
// files it isn't currently showing, so ask the
// collection rather than just scanning `entries`.
c.has_unsaved_edits() || !c.workspace_pending.is_empty(),
)
})
.collect();
for (i, name, from_git, is_ws, edited) in names {
let selected = i == active;
let label = if is_ws {
format!("{} {name}", super::icons::FOLDER)
} else if from_git {
format!("{} {name}", super::icons::GIT)
} else {
name.clone()
};
let label = if edited {
format!("{label} {}", super::icons::EDITED)
} else {
label
};
let mut text = egui::RichText::new(label);
if selected {
text = text.strong().color(self.theme.text);
} else {
text = text.color(self.theme.dim);
}
// The tab carries its own close button, as every tab strip
// people already use does. It is reserved *inside* the tab's
// own frame (an atom with a size and no content), so the strip
// doesn't reflow when one appears, and it is painted in the
// dim colour used for everything that is present but not being
// asked about — closing a tab is not an error, and a red ✕ on
// every tab reads as one. The built-in Request tab can't be
// closed, so it doesn't reserve the room.
let closable = i != 0;
let close_id = ui.id().with(("tab_close", i));
let mark = ui.text_style_height(&egui::TextStyle::Body) * 0.85;
let mut atoms = egui::Atoms::new(text);
if closable {
atoms.push_right(egui::Atom::custom(close_id, egui::vec2(mark, mark)));
}
let laid = egui::Button::selectable(selected, atoms)
.frame_when_inactive(true)
.atom_ui(ui);
let close_rect = laid.rect(close_id);
let resp = laid.response;
// Interacted after the tab, so the ✕ wins the pointer where
// the two overlap; the tab's own click is then ignored, or
// closing a tab would also switch to it on the way out.
let closed = close_rect.map(|rect| {
let hit = ui
.interact(rect, close_id, egui::Sense::click())
.on_hover_text(lbl_close);
let colour = if hit.hovered() {
self.theme.text
} else {
self.theme.dim
};
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
super::icons::CLOSE,
egui::FontId::new(mark, egui::FontFamily::Proportional),
colour,
);
hit.clicked()
});
if closed == Some(true) {
close_tab = Some(i);
} else if resp.clicked() {
self.switch_to_tab(i);
}
// Middle-click closes a tab (not the built-in Request tab).
if closable && resp.middle_clicked() {
self.request_close_tab(i);
}
// Right-click: rename the collection, or close it (parity with
// the TUI's rename-collection and close-tab actions).
resp.context_menu(|ui| {
if ui.button(lbl_rename).clicked() {
open_rename = Some((i, name.clone()));
ui.close();
}
if i != 0 && ui.button(lbl_close).clicked() {
close_tab = Some(i);
ui.close();
}
});
if selected && focused {
resp.highlight();
}
}
if ui
.button("+")
.on_hover_text(self.strings.gui_new_collection)
.clicked()
{
self.session.add_collection(self.strings.gui_untitled);
self.session.save();
}
});
if let Some((ci, text)) = open_rename {
self.dialog = Some(Dialog::Rename {
target: RenameTarget::Tab { ci },
text,
});
}
if let Some(i) = close_tab {
self.request_close_tab(i);
}
}
/// The transient status message ("Saved", "Could not write file: …"),
/// drawn on the menu row where the terminal UI puts it.
///
/// Deliberately not down in the status bar with the logo, the theme name
/// and the active environment. Those never change unless the user changes
/// them, so nothing down there is ever worth a second look -- and a message
/// that appears for a moment, among things trained to be ignored, at the
/// far end of the window from the request just sent, was missed. Up here it
/// shares the row the user is already using.
///
/// Coloured and marked by outcome, with the icon repeating what the colour
/// says for anyone who cannot tell the two apart.
pub(super) fn status_message(&mut self, ui: &mut egui::Ui) {
let Some(status) = self.session.status.as_ref() else {
return;
};
let (icon, color) = status_badge(status, &self.theme);
let text = status.text(&self.strings);
// Clickable, because the terminal UI advertises a copy key for this
// line and a long parse error is exactly what someone wants to paste
// somewhere. The message is left on screen afterwards rather than
// replaced with "copied": what was copied is the thing worth still
// being able to read.
if ui
.add(
egui::Label::new(
egui::RichText::new(format!("{icon} {text}"))
.color(color)
.strong(),
)
.sense(egui::Sense::click()),
)
.on_hover_text(self.strings.gui_status_copy_hint)
.clicked()
{
ui.ctx().copy_text(text);
}
}
fn status_bar(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
// The PaperBoy logo badge, lazily uploaded on first use. Drawn at
// the text's own height so it sits inline with the status message.
let logo = self.logo.get_or_insert_with(|| {
let img = logo_color_image().unwrap_or_else(|| {
egui::ColorImage::new([1, 1], vec![egui::Color32::TRANSPARENT])
});
ui.ctx()
.load_texture("paperboy_logo", img, egui::TextureOptions::LINEAR)
});
let h = ui.text_style_height(&egui::TextStyle::Body);
ui.add(egui::Image::new((logo.id(), egui::vec2(h, h))));
ui.add_space(4.0);
// An import that was sent to the background reports from here, and
// clicking it is the way back to the dialog. Computed before the
// click so `self.postman` isn't borrowed twice.
if let Some(line) = self.postman.background_line(&self.strings) {
ui.separator();
if ui
.add(
egui::Label::new(
egui::RichText::new(format!("{} {line}", super::icons::RUNNING))
.color(self.theme.accent),
)
.sense(egui::Sense::click()),
)
.on_hover_text(self.strings.postman_background_reveal)
.clicked()
{
self.postman.reveal();
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let spec = self.session.active_theme_spec();
ui.colored_label(
self.theme.dim,
format!("{} {}", self.strings.gui_theme_status_label, spec.name),
);
ui.separator();
// The always-visible answer to "which environment am I about
// to send this with?". The name is drawn in the "ok" colour and
// bold — the rest of the status bar is uniformly dim, so an
// active environment is the one thing here that stands out.
let env = self
.session
.active_env_id
.and_then(|id| self.session.global_envs.iter().find(|e| e.id == id));
match env {
Some(env) => ui.label(
egui::RichText::new(format!("{} {}", super::icons::PASS, env.name))
.color(self.theme.ok)
.strong(),
),
None => ui.colored_label(self.theme.dim, self.strings.gui_none_dash),
};
ui.colored_label(self.theme.dim, self.strings.gui_env_label);
});
});
}
}
impl GuiApp {
/// Open a native file dialog on a worker thread, to be collected by
/// [`super::menu::poll_pending_pick`] once it answers.
///
/// Ignored when a dialog is already open. Before the pickers were moved off
/// the frame loop this couldn't arise -- a blocked window accepts no
/// further clicks -- but a live window will happily let the user press
/// Browse twice, and two native choosers fighting over one destination
/// field is worse than the second click doing nothing.
pub fn request_pick(
&mut self,
kind: super::filepick::PickKind,
title: &str,
dir: Option<&std::path::Path>,
action: super::menu::PickAction,
) {
if self.pending_pick.is_some() {
return;
}
// A caller's own seed wins — it knows the field's current value, or the
// folder the thing being picked belongs beside. Only when it hasn't got
// one (or it no longer exists) does the dialog fall back to wherever the
// user last browsed, which beats opening on the process's working
// directory.
let remembered = self
.session
.picker_dir(crate::session::PickerKind::Other)
.map(std::path::Path::to_path_buf);
let dir = dir
.filter(|d| d.is_dir())
.map(std::path::Path::to_path_buf)
.or(remembered);
self.pending_pick = Some(super::filepick::spawn(kind, title, dir.as_deref(), action));
}
}
impl eframe::App for GuiApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.draw(ui);
}
fn on_exit(&mut self) {
self.session.save();
}
}
impl GuiApp {
/// One whole frame of application UI.
///
/// Split out of the `eframe::App` impl so tests can drive a complete frame:
/// `eframe::Frame` can't be built outside `eframe`, but a bare
/// `egui::Context` needs nothing at all, and whole-frame rendering is the
/// only way to catch problems that live *between* panels (widget id
/// clashes, for one).
pub(super) fn draw(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
// Refresh theme + strings from the session (cheap; picks up live edits).
let spec = self.session.active_theme_spec();
self.theme = GuiTheme::from_spec(&spec);
self.theme.apply(&ctx);
self.strings = Strings::for_language(&self.session.language);
// Drain background work (secret resolution, captures, Run All) and keep
// animating while anything is in flight.
let busy = self.session.poll();
if busy {
ctx.request_repaint_after(Duration::from_millis(80));
}
super::menu::poll_pending_pick(self);
self.poll_parked_runs(&ctx);
self.handle_global_keys(&ctx);
self.intercept_close(&ctx);
// egui 0.35: the app is handed a root `Ui` and every region is an
// `egui::Panel` nested into it (outermost added first, CentralPanel
// last). `.resizable(true)` panels get native drag-to-resize handles —
// the GUI's replacement for the terminal UI's `<`/`>` and `+`/`-` keys.
// Panels remember their dragged size in egui's own memory, which is not
// persisted, so read the sizes back out of the responses each frame and
// keep them in `state.json` ourselves.
let mut measured_env = None;
let mut measured_response = None;
let root_size = ui.max_rect().size();
egui::Panel::top("menu_bar").show(ui, |ui| menu::menu_bar(self, ui));
egui::Panel::top("tab_strip").show(ui, |ui| self.tab_strip(ui));
egui::Panel::bottom("status_bar").show(ui, |ui| self.status_bar(ui));
// Left column: Requests (top) + Global Environments (bottom). A width
// the user dragged wins; otherwise fall back to a pixel width derived
// from the terminal UI's column count so the two front-ends open on a
// comparable layout the first time.
let left_default = self
.session
.gui
.left_width
.unwrap_or_else(|| (self.session.list_width as f32 * 8.0).clamp(220.0, 460.0));
let left = egui::Panel::left("left_col")
.resizable(true)
.default_size(left_default)
// 200px keeps the environment editor's fixed-width variable grid
// within the panel: request/folder/env names truncate and the
// action buttons wrap, but the grid (key field + value + remove)
// has a hard minimum around 185px. Bounding the panel there means
// no content ever exceeds it, so dragging the splitter narrower
// can't leave the unpainted "black strip".
.min_size(200.0)
.max_size(560.0)
.show(ui, |ui| {
let avail = ui.available_height();
let env_h = self.session.gui.env_height.unwrap_or_else(|| {
(avail * self.session.response_pct as f32 / 100.0)
.clamp(120.0, (avail - 120.0).max(120.0))
});
// Permissive vertical limit: keep at least ~80px of the
// Requests panel above visible (looser than the side-to-side
// 180px minimum) so the bottom panel can't fully cover the top.
let env_max = (avail - 80.0).max(80.0);
let env = egui::Panel::bottom("env_panel")
.resizable(true)
.default_size(env_h)
.min_size(80.0)
.max_size(env_max)
.show(ui, |ui| {
self.panel_frame(ui, Focus::GlobalEnv, |app, ui| {
environments::ui(app, ui);
});
});
measured_env = Some(env.response.rect.height());
egui::CentralPanel::default().show(ui, |ui| {
self.panel_frame(ui, Focus::List, |app, ui| {
requests::ui(app, ui);
});
});
});
// Centre: request editor (top) + response (bottom), the reports view,
// or the open PaperTrail report editor (blocks / source).
egui::CentralPanel::default().show(ui, |ui| {
if self.report_editor.is_some() {
self.panel_frame(ui, Focus::Main, |app, ui| report_editor::ui(app, ui));
return;
}
if self.show_reports {
self.panel_frame(ui, Focus::Main, |app, ui| reports::ui(app, ui));
return;
}
self.undefined_vars_banner(ui);
self.body_form_conflict_banner(ui);
let avail = ui.available_height();
let resp_h = self.session.gui.response_height.unwrap_or_else(|| {
(avail * self.session.response_pct as f32 / 100.0)
.clamp(140.0, (avail - 140.0).max(140.0))
});
// Keep at least ~80px of the editor above visible (permissive
// vertical cap, looser than the horizontal 180px minimum).
let resp_max = (avail - 80.0).max(80.0);
let resp = egui::Panel::bottom("response_panel")
.resizable(true)
.default_size(resp_h)
.min_size(80.0)
.max_size(resp_max)
.show(ui, |ui| {
self.panel_frame(ui, Focus::Response, |app, ui| {
response::ui(app, ui);
});
});
measured_response = Some(resp.response.rect.height());
egui::CentralPanel::default().show(ui, |ui| {
self.panel_frame(ui, Focus::Main, |app, ui| {
editor::ui(app, ui);
});
});
});
let mut dirty = self.layout_dirty;
Self::record_size(
&mut dirty,
&mut self.session.gui.left_width,
left.response.rect.width(),
);
if let Some(h) = measured_env {
Self::record_size(&mut dirty, &mut self.session.gui.env_height, h);
}
if let Some(h) = measured_response {
Self::record_size(&mut dirty, &mut self.session.gui.response_height, h);
}
self.layout_dirty = dirty;
self.record_layout(&ctx, root_size);
menu::show_dialog(self, &ctx);
remote::show(self, &ctx);
postman::show(self, &ctx);
self.poll_workspace_redownload();
self.poll_workspace_reload_prompts();
if self.workspace_redownload.is_some() {
// The download runs on a worker thread, so nothing would otherwise
// wake the UI when it finishes.
ctx.request_repaint_after(Duration::from_millis(100));
}
report_id_clashes(&ctx);
}
/// Refuse a window close that would silently discard request edits, and put
/// the warning up instead.
///
/// The window manager's close is a *request*: `CancelClose` withdraws it for
/// this frame, which is the only chance to ask — `on_exit` runs too late to
/// stop anything. `allow_close` lets the confirmed close straight through
/// rather than looping on the same question forever.
fn intercept_close(&mut self, ctx: &egui::Context) {
if !ctx.input(|i| i.viewport().close_requested()) || self.allow_close {
return;
}
// Only what a quit would actually destroy: a plain tab's edits are
// saved with the session and are still there (still flagged) next start,
// so warning about them cried wolf every single time.
let count: usize = self
.session
.collections
.iter()
.map(|c| c.edits_lost_on_exit())
.sum();
if count == 0 {
return;
}
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
// Don't stack this on top of whatever else is open; the close was
// already refused, so the user can simply try again.
if self.dialog.is_none() {
let tabs = self
.session
.collections
.iter()
.filter(|c| c.edits_lost_on_exit() > 0)
.map(|c| c.name.clone())
.collect::<Vec<_>>()
.join(", ");
self.dialog = Some(Dialog::UnsavedQuit { count, tabs });
}
}
/// Write out every edit that quitting would otherwise destroy, and report
/// how many files were written. Backs "Save all changes" on the quit
/// dialog.
///
/// The set of files is [`Collection::edits_lost_on_exit`]'s, not
/// [`Collection::unsaved_edit_count`]'s: an ordinary tab's edits survive a
/// quit inside the session state, so writing them out to a `.hurl` on the
/// way past would be making a decision -- where the file goes, and that the
/// edit is finished -- that the user never asked this button to make.
///
/// A failure stops at the offending file rather than pressing on, so the
/// caller can name it. Files already written stay written and are no longer
/// flagged, so answering the dialog again retries only what is left.
pub(super) fn save_all_unsaved_edits(&mut self) -> Result<usize, String> {
let mut written = 0usize;
for c in &mut self.session.collections {
written += c.save_workspace_edits()?;
}
self.session.save();
self.session.status = Some(crate::i18n::Status::SavedFiles(written));
Ok(written)
}
}
/// Print any widget-id clash `egui` flagged this frame, when
/// `PAPERBOY_ID_CLASH=1` is set.
///
/// `egui` reports a clash by stroking a red rectangle around the offender and
/// writing a `🔥 …` note beside it — it neither logs nor returns anything, so a
/// user who sees the red flash has no way to say *which* widget it was. Reading
/// the debug layer back out turns that flash into a line on stderr naming the
/// widget, which is the only practical way to chase a clash that only shows up
/// in someone else's session.
///
/// Only compiled in debug builds, because that is the only place `egui` runs
/// the check at all (`Options::warn_on_id_clash` is `cfg!(debug_assertions)`).
#[cfg(debug_assertions)]
fn report_id_clashes(ctx: &egui::Context) {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("PAPERBOY_ID_CLASH").is_some()) {
return;
}
fn walk(shape: &egui::epaint::Shape, out: &mut Vec<String>) {
match shape {
egui::epaint::Shape::Text(t) if t.galley.text().contains('\u{1f525}') => {
out.push(t.galley.text().to_string());
}
egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let mut found = Vec::new();
ctx.graphics(|g| {
if let Some(list) = g.get(egui::LayerId::debug()) {
for c in list.all_entries() {
walk(&c.shape, &mut found);
}
}
});
for f in found {
eprintln!("[paperboy] egui id clash: {f}");
}
}
#[cfg(not(debug_assertions))]
fn report_id_clashes(_ctx: &egui::Context) {}
#[cfg(test)]
mod tests {
use super::*;
/// A message that appears for a moment has to appear where the user is
/// looking. At the foot of the window it sat among the logo, the theme name
/// and the environment -- none of which ever change on their own, so
/// nothing down there is worth a second look -- and as far from the request
/// just sent as the window allows. The terminal UI puts it on the menu row,
/// and so does this.
#[test]
fn the_status_message_is_drawn_on_the_menu_row() {
super::super::requests::tests::redirect_saved_state();
let mut app = GuiApp::for_test(Session::default());
app.session.status = Some(crate::i18n::Status::Error("disc on fire".into()));
let ctx = egui::Context::default();
let mut input = egui::RawInput::default();
let height = 800.0;
input.screen_rect = Some(egui::Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(1200.0, height),
));
let out = ctx.run_ui(input, |ui| app.draw(ui));
let mut found = Vec::new();
fn walk(shape: &egui::Shape, needle: &str, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Text(t) if t.galley.text().contains(needle) => {
out.push(t.visual_bounding_rect())
}
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, needle, out)),
_ => {}
}
}
for c in &out.shapes {
walk(&c.shape, "disc on fire", &mut found);
}
let rect = found
.first()
.unwrap_or_else(|| panic!("the status message was not painted at all"));
assert!(
rect.top() < 80.0,
"the message should ride the menu row, but was painted at y={} of {height}",
rect.top()
);
// The frame really is laid out full-height, so that coordinate means
// something: the theme name -- which belongs at the foot of the window
// and stays there -- is painted right at the bottom of the same frame.
let mut bottom = Vec::new();
for c in &out.shapes {
walk(&c.shape, app.strings.gui_theme_status_label, &mut bottom);
}
let theme_rect = bottom
.first()
.unwrap_or_else(|| panic!("the status bar was not painted"));
assert!(
theme_rect.top() > height - 80.0,
"the ambient status bar should still be at the foot: y={}",
theme_rect.top()
);
}
/// The terminal UI has always drawn this line in the outcome's colour;
/// the GUI drew every message in the one dim grey the rest of the bar uses,
/// so a failed save read like a note about which theme was loaded.
#[test]
fn a_status_message_is_marked_by_its_outcome() {
let theme = GuiTheme::from_spec(&crate::theme::default_preset());
let (ok_icon, ok_color) = status_badge(&crate::i18n::Status::Saved, &theme);
let (bad_icon, bad_color) = status_badge(&crate::i18n::Status::Error("no".into()), &theme);
assert_eq!(ok_color, theme.ok);
assert_eq!(bad_color, theme.err);
assert_ne!(
bad_color, theme.dim,
"a failure has to be told apart from the rest of the status bar"
);
assert_ne!(
ok_icon, bad_icon,
"colour alone is no answer for someone who cannot tell these two apart"
);
}
fn edited_collection(name: &str) -> crate::collection::Collection {
let mut e = crate::hurl::HurlEntry::default();
e.title = "req".into();
e.method = "GET".into();
e.url = "https://example.com".into();
e.modified = true;
crate::collection::Collection::new(name.to_string(), vec![e])
}
/// The same, but bound to a Workspace folder — the one kind of tab whose
/// edits a quit really does destroy, since its entries are re-read from
/// disk on restore rather than restored from the session state.
fn edited_workspace_collection(name: &str) -> crate::collection::Collection {
let mut c = edited_collection(name);
c.workspace_root = Some(std::path::PathBuf::from("/tmp/paperboy-test-ws"));
c
}
/// Every closable tab carries its own ✕, and clicking it closes that tab
/// rather than merely switching to it.
///
/// The built-in Request tab is not closable, so it must not show one — an
/// ✕ that does nothing is worse than no ✕ at all.
#[test]
fn a_tab_is_closed_by_the_mark_in_its_own_corner() {
let mut session = crate::session::Session::default();
session.add_collection("scratch");
assert_eq!(session.tab_count(), 2);
let mut app = GuiApp::for_test(session);
app.session.activate_tab(0);
let ctx = egui::Context::default();
app.theme.apply(&ctx);
let input = || egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(900.0, 200.0),
)),
..Default::default()
};
// Where the marks are painted. Two frames: egui sizes the strip on the
// first and only paints it settled on the second.
let mut marks: Vec<egui::Rect> = Vec::new();
for _ in 0..2 {
let out = ctx.run_ui(input(), |ui| app.tab_strip(ui));
marks = close_marks(&out.shapes);
}
assert_eq!(
marks.len(),
1,
"one mark, on the one closable tab — not on the Request tab"
);
let at = marks[0].center();
let mut i = input();
i.events.push(egui::Event::PointerMoved(at));
i.events.push(egui::Event::PointerButton {
pos: at,
button: egui::PointerButton::Primary,
pressed: true,
modifiers: Default::default(),
});
i.events.push(egui::Event::PointerButton {
pos: at,
button: egui::PointerButton::Primary,
pressed: false,
modifiers: Default::default(),
});
let _ = ctx.run_ui(i, |ui| app.tab_strip(ui));
assert_eq!(app.session.tab_count(), 1, "the tab is gone");
assert!(
app.dialog.is_none(),
"an untouched tab closes without asking"
);
assert_eq!(
app.active_ci(),
0,
"and the ✕ didn't switch to it on the way"
);
}
/// The rects of every close mark painted in a frame.
fn close_marks(shapes: &[egui::epaint::ClippedShape]) -> Vec<egui::Rect> {
fn walk(s: &egui::epaint::Shape, out: &mut Vec<egui::Rect>) {
match s {
egui::epaint::Shape::Text(t) if t.galley.text() == super::super::icons::CLOSE => {
out.push(t.visual_bounding_rect())
}
egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let mut out = Vec::new();
for c in shapes {
walk(&c.shape, &mut out);
}
out
}
/// "Save all changes" has to leave nothing behind for the dialog to object
/// to a second time -- otherwise the button would appear to do nothing.
#[test]
fn saving_all_changes_writes_the_workspace_file_and_clears_the_quit_warning() {
let dir = std::env::temp_dir().join(format!(
"paperboy_gui_save_all_{}_{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("health.hurl");
std::fs::write(&file, "GET https://example.com/health\n").unwrap();
// save_all_unsaved_edits() persists the session, which would otherwise
// land on the developer's own state.json.
super::requests::tests::redirect_saved_state();
let mut session = Session::default();
session.collections.clear();
let mut col = edited_workspace_collection("ws");
col.workspace_root = Some(dir.clone());
col.path = Some(file.clone());
col.entries[0].url = "https://example.com/health/v2".into();
session.collections.push(col);
let mut app = GuiApp::for_test(session);
assert_eq!(
app.session.collections[0].edits_lost_on_exit(),
1,
"the fixture starts with exactly the edit the dialog would warn about"
);
let written = app
.save_all_unsaved_edits()
.expect("the temporary file is writable");
assert_eq!(written, 1, "the one edited file was written");
let on_disk = std::fs::read_to_string(&file).unwrap();
assert!(
on_disk.contains("https://example.com/health/v2"),
"the edit reached the file rather than just being marked saved: {on_disk}"
);
assert_eq!(
app.session.collections[0].edits_lost_on_exit(),
0,
"so a second close request would go straight through"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Closing a tab that is holding edits with nowhere on disk to go asks
/// first — the tab is still there afterwards.
#[test]
fn closing_a_tab_with_unsaved_edits_asks_before_throwing_them_away() {
let mut session = Session::default();
session.collections.clear();
// Tab 0 is the built-in Request tab and is never closable, so the
// fixture puts both tabs under test after it.
session.collections.push(crate::collection::Collection::new(
"home".to_string(),
Vec::new(),
));
session.collections.push(edited_collection("dirty"));
session.collections.push(crate::collection::Collection::new(
"clean".to_string(),
Vec::new(),
));
let mut app = GuiApp::for_test(session);
app.request_close_tab(1);
assert!(
matches!(
&app.dialog,
Some(Dialog::UnsavedCloseTab {
ci: 1,
count: 1,
..
})
),
"the warning should name the tab and how much is at stake"
);
assert_eq!(
app.session.collections.len(),
3,
"nothing may be closed until the question is answered"
);
// A tab with nothing unsaved closes straight away, no question asked.
app.dialog = None;
app.request_close_tab(2);
assert!(app.dialog.is_none(), "a clean tab must not be nagged about");
assert_eq!(app.session.collections.len(), 2);
}
/// The window manager's close is only a *request*: PaperBoy has to refuse
/// it and ask, because `on_exit` runs far too late to stop anything.
#[test]
fn quitting_with_unsaved_edits_is_refused_until_it_is_confirmed() {
fn close_request() -> egui::RawInput {
let mut input = egui::RawInput::default();
input
.viewports
.entry(egui::ViewportId::ROOT)
.or_default()
.events
.push(egui::ViewportEvent::Close);
input
}
fn cancelled(out: &egui::FullOutput) -> bool {
out.viewport_output
.values()
.any(|v| v.commands.contains(&egui::ViewportCommand::CancelClose))
}
let mut session = Session::default();
session.collections.clear();
session
.collections
.push(edited_workspace_collection("dirty"));
let mut app = GuiApp::for_test(session);
let ctx = egui::Context::default();
let out = ctx.run_ui(close_request(), |ui| app.intercept_close(ui.ctx()));
assert!(cancelled(&out), "the close must be withdrawn, not honoured");
assert!(
matches!(&app.dialog, Some(Dialog::UnsavedQuit { count: 1, .. })),
"and the user asked about the edit that would be lost"
);
// Confirming sets `allow_close`; the close that follows must go through,
// or the window could never be closed at all.
app.allow_close = true;
app.dialog = None;
let out = ctx.run_ui(close_request(), |ui| app.intercept_close(ui.ctx()));
assert!(!cancelled(&out), "a confirmed quit must not be intercepted");
assert!(app.dialog.is_none(), "and must not ask a second time");
}
/// Does any text painted this frame contain `needle`? Shapes nest (a
/// `Frame` emits a `Shape::Vec`), so this has to recurse rather than scan
/// the top level.
fn painted(out: &egui::FullOutput, needle: &str) -> bool {
fn walk(shape: &egui::Shape, needle: &str) -> bool {
match shape {
egui::Shape::Text(t) => t.galley.text().contains(needle),
egui::Shape::Vec(v) => v.iter().any(|s| walk(s, needle)),
_ => false,
}
}
out.shapes.iter().any(|c| walk(&c.shape, needle))
}
/// Paint the banner once with a real screen rect — without one, egui has no
/// room to lay anything out and paints nothing at all.
fn banner_frame(app: &mut GuiApp) -> egui::FullOutput {
let ctx = egui::Context::default();
let mut input = egui::RawInput::default();
input.screen_rect = Some(egui::Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(640.0, 480.0),
));
ctx.run_ui(input, |ui| app.undefined_vars_banner(ui))
}
fn app_referencing(url: &str) -> GuiApp {
let mut e = crate::hurl::HurlEntry::default();
e.title = "req".into();
e.method = "GET".into();
e.url = url.into();
let mut session = Session::default();
session.collections.clear();
session
.collections
.push(crate::collection::Collection::new("c".to_string(), vec![e]));
GuiApp::for_test(session)
}
/// The whole point of feature: a variable nothing defines used to be
/// invisible — it rendered as ordinary body text and the run just 401'd.
#[test]
fn undefined_variables_are_named_in_a_banner() {
let mut app = app_referencing("https://x/{{ tokn }}");
let out = banner_frame(&mut app);
assert!(
painted(&out, "tokn"),
"the offending variable must be named, not just counted"
);
}
/// ...and it must be silent otherwise, or it becomes wallpaper.
#[test]
fn a_request_with_no_variables_gets_no_banner() {
let mut app = app_referencing("https://x/plain");
let out = banner_frame(&mut app);
assert!(
!painted(&out, "undefined"),
"nothing is wrong, so nothing should be said"
);
}
/// Nothing unsaved, nothing to say — the window closes without a word.
#[test]
fn quitting_with_everything_saved_is_not_interrupted() {
let mut session = Session::default();
session.collections.clear();
session.collections.push(crate::collection::Collection::new(
"clean".to_string(),
Vec::new(),
));
let mut app = GuiApp::for_test(session);
let ctx = egui::Context::default();
let mut input = egui::RawInput::default();
input
.viewports
.entry(egui::ViewportId::ROOT)
.or_default()
.events
.push(egui::ViewportEvent::Close);
let out = ctx.run_ui(input, |ui| app.intercept_close(ui.ctx()));
assert!(
!out.viewport_output
.values()
.any(|v| v.commands.contains(&egui::ViewportCommand::CancelClose)),
"a clean session must never have its quit interrupted"
);
assert!(app.dialog.is_none());
}
// --- Keyboard for the Requests panel, Ctrl+Z undo, and the F1 overlay. ---
fn req(title: &str) -> crate::hurl::HurlEntry {
let mut e = crate::hurl::HurlEntry::default();
e.title = title.into();
e.method = "GET".into();
e.url = "https://example.com".into();
e
}
/// Feed one key press through the global key handler exactly as a frame
/// would, so `consume_key` and the previous-frame focus read the real
/// input path rather than a hand-poked flag.
fn press(app: &mut GuiApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) {
let mut input = egui::RawInput::default();
input.events.push(egui::Event::Key {
key,
physical_key: None,
pressed: true,
repeat: false,
modifiers,
});
input.modifiers = modifiers;
let _ = ctx.run_ui(input, |ui| app.handle_global_keys(ui.ctx()));
}
#[test]
fn the_requests_panel_moves_its_selection_with_the_arrow_and_end_keys() {
let mut session = Session::default();
session.collections[0].entries = vec![req("a"), req("b"), req("c")];
session.collections[0].selected_entry = 0;
let mut app = GuiApp::for_test(session);
app.focus = Focus::List;
let ctx = egui::Context::default();
press(&mut app, &ctx, Key::ArrowDown, Modifiers::NONE);
assert_eq!(app.session.collections[0].selected_entry, 1);
assert!(
app.reveal_selected,
"a keyboard move asks the row into view for the next render"
);
press(&mut app, &ctx, Key::End, Modifiers::NONE);
assert_eq!(app.session.collections[0].selected_entry, 2);
press(&mut app, &ctx, Key::ArrowDown, Modifiers::NONE);
assert_eq!(
app.session.collections[0].selected_entry, 2,
"Down at the bottom clamps rather than wrapping"
);
press(&mut app, &ctx, Key::Home, Modifiers::NONE);
assert_eq!(app.session.collections[0].selected_entry, 0);
}
#[test]
fn the_requests_panel_keys_stand_down_unless_it_holds_focus() {
let mut session = Session::default();
session.collections[0].entries = vec![req("a"), req("b")];
let mut app = GuiApp::for_test(session);
app.focus = Focus::Main; // some other panel has focus
let ctx = egui::Context::default();
press(&mut app, &ctx, Key::ArrowDown, Modifiers::NONE);
assert_eq!(
app.session.collections[0].selected_entry, 0,
"arrows belong to whatever panel is focused, not always the list"
);
}
#[test]
fn f2_renames_and_delete_asks_first_from_the_requests_panel() {
let mut session = Session::default();
session.collections[0].entries = vec![req("a"), req("b")];
session.collections[0].selected_entry = 1;
let mut app = GuiApp::for_test(session);
app.focus = Focus::List;
let ctx = egui::Context::default();
press(&mut app, &ctx, Key::F2, Modifiers::NONE);
assert!(
matches!(app.dialog, Some(Dialog::Rename { .. })),
"F2 opens the rename dialog for the selection"
);
app.dialog = None;
press(&mut app, &ctx, Key::Delete, Modifiers::NONE);
assert!(
matches!(
app.dialog,
Some(Dialog::ConfirmDeleteRequest { idx: 1, .. })
),
"Delete asks before removing anything"
);
assert_eq!(
app.session.collections[0].entries.len(),
2,
"and nothing is gone until the prompt is answered"
);
}
#[test]
fn delete_from_the_requests_panel_is_immediate_when_the_preference_is_off() {
let mut session = Session::default();
session.collections[0].entries = vec![req("a"), req("b")];
session.collections[0].selected_entry = 0;
session.confirm_on_delete_request = false;
let mut app = GuiApp::for_test(session);
app.focus = Focus::List;
let ctx = egui::Context::default();
press(&mut app, &ctx, Key::Delete, Modifiers::NONE);
assert!(app.dialog.is_none(), "no prompt when the guard is off");
assert_eq!(
app.session.collections[0]
.entries
.iter()
.map(|e| e.title.as_str())
.collect::<Vec<_>>(),
vec!["b"],
"the selected request is gone straight away"
);
}
#[test]
fn a_workspace_tree_is_keyboard_driven_but_stands_down_for_dialogs() {
// A real workspace fixture (the plain-list tests use hand-built
// collections, but the tree scans the filesystem), so its rows are the
// ones the keyboard actually steps through.
crate::gui::requests::tests::redirect_saved_state();
let dir = crate::gui::requests::tests::ws_tmp("appkeyws");
let mut session = Session::default();
session.collections.clear();
let ci = session.open_workspace(dir.clone());
session.active_tab = ci;
let mut app = GuiApp::for_test(session);
app.focus = Focus::List;
let ctx = egui::Context::default();
assert!(
app.session.collections[ci].ws_rows().len() >= 2,
"the fixture lists at least two top-level rows for Down to move between"
);
app.session.collections[ci].list_cursor = 0;
// The tree now has a keyboard: through the real global-key path the
// arrows move its cursor, the same as the plain list's.
press(&mut app, &ctx, Key::ArrowDown, Modifiers::NONE);
assert_eq!(
app.session.collections[ci].list_cursor, 1,
"a workspace tree steps its cursor with the arrows now"
);
// With a dialog up, the whole handler stands down, so the cursor holds
// still. This is the guarantee that keeps a Delete keystroke from
// reaching past a dialog the user is typing in to the file behind it.
app.dialog = Some(Dialog::Prompt {
kind: PromptKind::BaseUrl,
text: String::new(),
});
press(&mut app, &ctx, Key::ArrowDown, Modifiers::NONE);
assert_eq!(
app.session.collections[ci].list_cursor, 1,
"an open dialog freezes the tree keys entirely"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Every text field in the window has its own Ctrl+Z. The global binding
/// consumed the key before any of them saw it, so undo did not work in a
/// URL, a header cell or a generated expression -- it resurrected the last
/// deleted request instead, which is not what the keyboard was aimed at.
#[test]
fn ctrl_z_belongs_to_whatever_is_being_typed_into() {
let mut session = Session::default();
session.collections[0].entries = vec![req("a"), req("b")];
session.confirm_on_delete_request = false;
let mut app = GuiApp::for_test(session);
app.delete_request_now(0, 1);
let ctx = egui::Context::default();
ctx.memory_mut(|m| m.request_focus(egui::Id::new("a-text-field")));
press(&mut app, &ctx, Key::Z, Modifiers::COMMAND);
assert_eq!(
app.session.collections[0].entries.len(),
1,
"the field being typed into owns Ctrl+Z"
);
}
#[test]
fn ctrl_z_undoes_a_request_delete_but_stands_down_for_the_report_editor() {
let mut session = Session::default();
session.collections[0].entries = vec![req("a"), req("b")];
session.confirm_on_delete_request = false;
let mut app = GuiApp::for_test(session);
app.delete_request_now(0, 1);
assert_eq!(app.session.collections[0].entries.len(), 1, "\"b\" is gone");
// While the report editor owns the surface, Ctrl+Z is its own (block
// undo / the source view's text undoer), so the global binding must not
// steal it — the delete stays undone.
app.open_report_editor(ReportOrigin::Workspace, crate::report::Report::scratch("r"));
let ctx = egui::Context::default();
press(&mut app, &ctx, Key::Z, Modifiers::COMMAND);
assert_eq!(
app.session.collections[0].entries.len(),
1,
"Ctrl+Z belongs to the report editor while it is up"
);
// With the report editor closed, Ctrl+Z restores the deleted request.
app.close_report_editor();
press(&mut app, &ctx, Key::Z, Modifiers::COMMAND);
assert_eq!(
app.session.collections[0].entries.len(),
2,
"Ctrl+Z brings the request back once the editor is gone"
);
}
#[test]
fn f1_opens_the_shortcuts_overlay_and_respects_open_dialogs() {
let mut app = GuiApp::for_test(Session::default());
let ctx = egui::Context::default();
press(&mut app, &ctx, Key::F1, Modifiers::NONE);
assert!(
matches!(app.dialog, Some(Dialog::Shortcuts)),
"F1 raises the shortcuts overlay"
);
// With a modal already up, the handler stands down entirely, so F1
// can't stack a second one on top of it.
app.dialog = Some(Dialog::Prompt {
kind: PromptKind::BaseUrl,
text: String::new(),
});
press(&mut app, &ctx, Key::F1, Modifiers::NONE);
assert!(
matches!(app.dialog, Some(Dialog::Prompt { .. })),
"F1 doesn't fight an open dialog"
);
}
}
#[cfg(test)]
mod report_run_persistence_tests {
use super::*;
use crate::gui::report_editor::ReportOrigin;
use crate::gui::report_run::{RunKey, RunUpdate};
use crate::report::Report;
use crate::report::model::{ReportResult, ReportRow};
use crate::session::Session;
fn app() -> GuiApp {
GuiApp::for_test(Session::default())
}
fn report(name: &str) -> Report {
let mut r = Report::scratch(name);
r.path = Some(std::path::PathBuf::from(format!("/tmp/{name}.trail")));
r
}
fn result_with(cell: &str) -> ReportResult {
let mut res = ReportResult::default();
let mut row = ReportRow::default();
row.cells.insert("A".to_string(), cell.to_string());
res.rows.push(row);
res
}
/// Clicking a tab used to close a Workspace report editor, and closing it
/// dropped the `RunHandle` — which cancels the worker. A report you left for
/// a moment came back cancelled and empty. The run has to outlive the view.
#[test]
fn closing_the_editor_neither_cancels_the_run_nor_loses_the_rows() {
let mut app = app();
app.open_report_editor(ReportOrigin::Workspace, report("nightly"));
let (handle, _tx) = crate::gui::report_run::test_handle();
let ed = app.report_editor.as_mut().expect("editor is open");
ed.result = Some(result_with("first"));
ed.run = Some(handle);
app.close_report_editor();
assert!(app.report_editor.is_none(), "the view is gone");
let parked = app
.report_runs
.get(&RunKey::Path("/tmp/nightly.trail".into()))
.expect("but the run was kept");
assert!(
!parked.run.as_ref().expect("still holding it").cancelled(),
"the worker keeps going: dropping the handle is what cancels it"
);
assert_eq!(parked.result.as_ref().expect("rows kept").rows.len(), 1);
}
/// A Workspace tab's report is the tab's, so leaving the tab and coming
/// back has to land on it again. It used to be closed on the way out and
/// never reopened, so the tab came back showing whichever collection the
/// tree had loaded — a report you glanced away from was silently swapped
/// for something else.
#[test]
fn a_workspace_tab_comes_back_to_the_report_it_was_on() {
super::super::requests::tests::redirect_saved_state();
let dir = std::env::temp_dir().join(format!("pb-tab-restore-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let trail = dir.join("nightly.trail");
std::fs::write(&trail, "REPORT REQUEST login AS Login\n").unwrap();
let mut session = Session::default();
let mut col = crate::collection::Collection::new("ws".to_string(), Vec::new());
col.workspace_root = Some(dir.clone());
col.workspace_selected = Some(trail.clone());
session.collections.push(col);
let ws = session.collections.len() - 1;
let mut app = GuiApp::for_test(session);
app.switch_to_tab(ws);
assert!(
app.report_editor.is_some(),
"arriving at the tab opens what its tree had selected"
);
app.switch_to_tab(0);
assert!(
app.report_editor.is_none(),
"leaving it closes the editor, since the report belongs to that tab"
);
app.switch_to_tab(ws);
let ed = app
.report_editor
.as_ref()
.expect("and coming back reopens it");
assert_eq!(
ed.path(),
Some(trail.as_path()),
"the same report, not another file"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// …and coming back to the report picks it up where it got to, rather than
/// showing an empty grid.
#[test]
fn reopening_a_report_takes_its_run_back() {
let mut app = app();
app.open_report_editor(ReportOrigin::Workspace, report("nightly"));
let (handle, tx) = crate::gui::report_run::test_handle();
let ed = app.report_editor.as_mut().expect("editor is open");
ed.result = Some(result_with("first"));
ed.run = Some(handle);
app.close_report_editor();
// A row arrives while nobody is looking, and the parked run folds it in.
let mut row = ReportRow::default();
row.cells.insert("A".to_string(), "second".to_string());
tx.send(RunUpdate::Row(Box::new(row)))
.expect("worker sends");
let ctx = egui::Context::default();
let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
app.poll_parked_runs(ui.ctx())
});
app.open_report_editor(ReportOrigin::Workspace, report("nightly"));
let ed = app.report_editor.as_ref().expect("editor is back");
assert!(ed.run.is_some(), "still streaming");
assert!(ed.result.is_some(), "and showing what it collected");
assert!(
!app.report_runs
.contains_key(&RunKey::Path("/tmp/nightly.trail".into())),
"the run is held in one place at a time, not two"
);
}
/// Editing a report and then clicking anything else in the workspace — an
/// environment, another collection, another tab — tears the editor down
/// and rebuilds it from the file on disk. Without somewhere for the
/// unsaved text to wait, that silently threw the edits away and handed
/// back what the file still said, with no warning and nothing to undo.
#[test]
fn an_edited_report_survives_looking_at_something_else() {
let mut app = app();
app.open_report_editor(ReportOrigin::Workspace, report("nightly"));
let ed = app.report_editor.as_mut().expect("editor is open");
ed.report.text = "# name: nightly\nREPORT REQUEST typed_by_hand\n".to_string();
ed.report.dirty = true;
// Whatever the user clicked takes the centre column.
app.close_report_editor();
assert!(app.report_editor.is_none(), "the editor really did close");
// And back. Every path that reopens one reads the file off disk, which
// is what `report()` stands in for here.
app.open_report_editor(ReportOrigin::Workspace, report("nightly"));
let ed = app.report_editor.as_ref().expect("the editor is back");
assert!(
ed.report.text.contains("typed_by_hand"),
"the edits come back, not the file: {:?}",
ed.report.text
);
assert!(
ed.report.dirty,
"and they are still unsaved, so Save is still offered"
);
assert!(
app.report_pending.is_empty(),
"and they are held in one place at a time, not two"
);
}
/// Only *unsaved* text is worth keeping. A report closed with nothing
/// outstanding must come back from disk, or a later change made outside
/// PaperBoy would be masked forever by a stale copy of the same file.
#[test]
fn an_unedited_report_is_not_parked() {
let mut app = app();
app.open_report_editor(ReportOrigin::Workspace, report("nightly"));
app.close_report_editor();
assert!(app.report_pending.is_empty());
}
/// A report is loaded afresh from disk each time it is opened from a
/// Workspace tree, so its `id` differs on the way back in — the run has to
/// be filed under something that survives, which is the path.
#[test]
fn a_reloaded_report_is_recognised_as_the_same_one() {
let a = report("nightly");
let b = report("nightly");
assert_ne!(a.id, b.id, "a fresh load really does mint a new id");
assert_eq!(RunKey::of(&a), RunKey::of(&b), "but it is the same report");
// An unsaved scratch report has no path to be known by, so it falls back
// to the id it keeps for as long as the session holds it.
let scratch = Report::scratch("untitled");
assert_eq!(RunKey::of(&scratch), RunKey::Id(scratch.id));
}
/// Opening a *different* report parks the first one's run rather than
/// cancelling it, so two reports can be in flight at once.
#[test]
fn opening_another_report_leaves_the_first_one_running() {
let mut app = app();
app.open_report_editor(ReportOrigin::Workspace, report("first"));
let (handle, _tx) = crate::gui::report_run::test_handle();
app.report_editor.as_mut().unwrap().run = Some(handle);
app.open_report_editor(ReportOrigin::Workspace, report("second"));
let parked = app
.report_runs
.get(&RunKey::Path("/tmp/first.trail".into()))
.expect("the first run was parked");
assert!(!parked.run.as_ref().unwrap().cancelled());
}
/// An editor with nothing to keep leaves nothing behind — the parking area
/// is for runs, not for every report ever opened.
#[test]
fn closing_an_editor_that_never_ran_parks_nothing() {
let mut app = app();
app.open_report_editor(ReportOrigin::Workspace, report("idle"));
app.close_report_editor();
assert!(app.report_runs.is_empty());
}
}
#[cfg(test)]
mod pick_guard_tests {
use super::*;
/// A live window lets the user press Browse again while the first chooser
/// is still up; the second press must not open a rival dialog.
#[test]
fn a_second_request_is_ignored_while_one_is_open() {
let mut app = GuiApp::for_test(crate::session::Session::default());
app.request_pick(
super::super::filepick::PickKind::Folder,
"first",
None,
super::super::menu::PickAction::GitWorkspaceDir,
);
assert!(app.pending_pick.is_some());
app.request_pick(
super::super::filepick::PickKind::Folder,
"second",
None,
super::super::menu::PickAction::PostmanDest,
);
// Still the first: the guard refuses rather than replacing, so the
// dialog the user is looking at is the one that will be honoured.
assert!(matches!(
app.pending_pick.as_ref().and_then(|p| p.action()),
Some(super::super::menu::PickAction::GitWorkspaceDir)
));
}
}