1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
|
//! The session: its state and its one dispatch. A step takes an event
//! (update), serves the 9P tree's requests (serveFs) and drains its effects
//! into the host (pump, settle, step); the host's replies come back as the
//! calls below (setCwd, acknowledgeShell, saveFailed, the views' and fonts'
//! answers); the clock is its deadlines alone (nextWake, advance). Its nouns
//! live in their own files (panes.zig, layout.zig, keys.zig, Jump.zig,
//! Effect.zig, lsp/Ask.zig, colors.zig), a few called from everywhere kept
//! here as declaration aliases.
const std = @import("std");
const pardes = @import("pardes.zig");
const BOX_H = pardes.BOX_H;
const Builtin = pardes.Builtin;
const COLBAR_H = pardes.COLBAR_H;
const CellPixels = pardes.CellPixels;
const ChromeTheme = pardes.ChromeTheme;
const Color = pardes.Color;
const Effect = pardes.Effect;
const Event = pardes.Event;
const FontRole = pardes.FontRole;
const FrameStats = pardes.FrameStats;
const Handover = pardes.Handover;
const Host = pardes.Host;
const Placement = pardes.Placement;
const Jump = pardes.Jump;
const Frontend = @import("Event.zig").Frontend;
const Ask = pardes.lsp.Ask;
const Key = pardes.Key;
const Loc = Jump.Loc;
const MAX_COLS = pardes.MAX_COLS;
const MAX_JUMPS = pardes.MAX_JUMPS;
const MAX_PANES = pardes.MAX_PANES;
const MAX_TAG_ROWS = pardes.MAX_TAG_ROWS;
const Macro = pardes.Macro;
const Messages = pardes.Messages;
const Mouse = pardes.Mouse;
const Pane = pardes.Pane;
const Pipe = pardes.Pipe;
const PtySignal = pardes.PtySignal;
const Rect = pardes.Rect;
const Registers = pardes.Registers;
const RowMetrics = pardes.RowMetrics;
const Store = @import("Store.zig");
const Db = pardes.Db;
const Stream = pardes.Stream;
const Surface = pardes.Surface;
const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
const TOPBAR_H = pardes.TOPBAR_H;
const TagHit = pardes.TagHit;
const Text = pardes.panes.Text;
const Theme = pardes.Theme;
const builtins = pardes.builtins;
const colors = pardes.colors;
const column_weight_unit = layout.column_weight_unit;
const config = pardes.config;
const ctlfs = pardes.ctlfs;
const draw = pardes.draw;
const dump = pardes.dump;
const edit = pardes.edit;
const effect_path_cap = pardes.effect_path_cap;
const effect_write_cap = pardes.effect_write_cap;
const exec = pardes.exec;
const filesystem = pardes.filesystem;
const font_picker = pardes.font_picker;
const fonts = pardes.fonts;
const frame_ns = pardes.frame_ns;
const host_io = pardes.host_io;
const layout = pardes.layout;
const limits = memory.limits;
const locations = @import("locations.zig");
const look = pardes.look;
const lsp = pardes.lsp;
const memory = pardes.memory;
const modal = pardes.modal;
const mouse = pardes.mouse;
const newer_build_words = pardes.newer_build_words;
const pager = pardes.pager;
const platform = pardes.platform;
const recent_files = @import("recent.zig");
const sel_slot = pardes.sel_slot;
const syntax = pardes.syntax;
const tagline = pardes.tagline;
const tape = pardes.tape;
const test_api = pardes.test_api;
const themes = pardes.themes;
const turn = &pardes.turn;
const Views = pardes.views;
const Pardes = @This();
/// One client's view of the session (views.zig): its screen and layout,
/// its focus, its pointer and gestures, its jumps, its key prefixes.
pub const View = struct {
pub const replica = .{ .len = .{ .{ "leader_keys", "leader_n" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } } };
screen_w: u16 = 0,
screen_h: u16 = 0,
cell_pixels: CellPixels = .{},
row_metrics: RowMetrics = .{},
ncol: usize = 0,
cols: [MAX_COLS]Column = @splat(.{}),
/// Each column's tag and the workspace's: Texts like a pane's tag, with
/// no prefix, showing a default until someone edits them. Not the
/// Column's: a view opened takes the live one's columns (Views.open) but
/// tags of its own.
col_tags: [MAX_COLS]Text = @splat(.{ .what = .column }),
rects: [MAX_PANES]Rect = @splat(.{}),
col_x: [MAX_COLS]u16 = @splat(0),
col_w: [MAX_COLS]u16 = @splat(0),
active: usize = 0,
/// The places jumped from (Jump.zig).
jumps: Jump = .{},
/// acme's activecol (dat.c:37), by column serial, 0 for none: the
/// column last typed in (acme.c:487), clicked in with the select button
/// (acme.c:659), dropped into by a grip (acme.c:640), or given a new
/// pane (util.c:467). Where the acme placement puts new panes
/// (exec.placeNew). A Look click moves the keyboard but not this.
active_column: u32 = 0,
/// The live view's frontend (Event.frontend): a window, what it draws and
/// the words it takes (builtins.zig `here`); it starts as
/// `Options.windowed` says.
frontend: Frontend = .{ .windowed = false },
drag: mouse.Drag = .none,
/// A press a terminal's program took (mouse.programMouse): its drags
/// and release are the program's too, wherever the pointer goes.
mouse_grab: ?mouse.Grab = null,
/// Whether the host window has the keyboard (Event.focus), and the pane
/// whose program was last told it has it (reportFocus).
window_focused: bool = true,
focus_told: ?struct { id: usize, serial: u32 } = null,
hover_col: u16 = 0,
hover_row: u16 = 0,
pointer_raw_col: u16 = 0,
pointer_raw_row: u16 = 0,
pointer_body_hit: ?Mouse.BodyHit = null,
pointer_tag_hit: ?TagHit = null,
raw_hover_intent: bool = false,
/// A pixel shell's window, which hears the pointer leave it: only then
/// does /status say whether the pointer is over it (a terminal's mouse
/// reports never say it left, so a tty would claim it for ever).
pointer_inside: bool = false,
/// The last plain B1 click, for acme's double-click (text.c:881,
/// textselect: a second click at the same point within 500 ms).
last_click: ?struct { id: usize, on_tag: bool, row: i32, col: i32, ms: i64 } = null,
/// The button an Alt- or Super-click of button 1 stands for, from its
/// press through its release (mouse.emulateButton).
click_as: ?Mouse.Button = null,
/// A B1 chord's edits share the undo point it took (mouse.zig).
chord_hold: bool = false,
wheel_guard: u8 = 0,
/// A key that waits for the next: the leader (SPC) or the window prefix
/// (Ctrl-w), one at a time.
prefix: enum { none, leader, window } = .none,
/// The register the running normal command names (`"<reg>`); 0 for the
/// default one.
register: u21 = 0,
/// Window mode's outlined pane (layout.windowKey); null outside it.
window_pick: ?usize = null,
leader_keys: [4]u8 = undefined,
leader_n: u8 = 0,
/// The keyboard is on a header: a column's tag, or the workspace's.
header: ?Header = null,
/// A mouse sweep is extending the focused header's selection.
header_drag: bool = false,
/// A middle or right sweep held over a column's or the workspace's tag.
header_sweep: ?mouse.HeaderSweep = null,
/// The kind's pane a press went to, which has its drag and release
/// wherever the pointer goes; and the one the pointer is over, told
/// when it leaves (mouse.kindMouse).
kind_grab: ?u8 = null,
kind_hover: ?u8 = null,
header_scroll: usize = 0,
/// The focused header's first line on screen, which follows its caret
/// when it has more lines than rows.
header_top: usize = 0,
/// middle+left chord argument: a kept left selection captured by a left
/// press during an active middle select-drag; consumed on middle release
chord_arg: ?[]u8 = null,
clip_pending: ?edit.ClipRequest = null,
};
gpa: std.mem.Allocator,
image_gpa: std.mem.Allocator,
/// Its kinds of pane (Kind.zig): the compiled-in ones, then what addons
/// brought; the data both cores hold, the code only the authority.
kinds: pardes.Kind.Registry = .{},
tree_sitter_gpa: std.mem.Allocator,
opts: Options,
resize_count: usize = 0,
panes: [MAX_PANES]?*Pane = @splat(null),
reserved_slots: [MAX_PANES]bool = @splat(false),
/// Deferred teardown of dropped panes (see RetiredPanes).
retired_panes: RetiredPanes = .{},
// layout: columns own x by weight; panes own y by vweight within a column.
next_column_serial: u32 = 1,
/// A pane or column on its way to another window (Handover.zig).
handover: Handover = .{},
global_tag: Text = .{ .what = .workspace },
// derived each sync
/// The files opened lately, closed ones too (recent.zig): `Recent`,
/// /recent, and the jumplist's way back to a closed pane.
recent: recent_files.List = .{},
/// The panes this session closed, which Panes brings back (Store.zig).
store: Store = .{},
/// The user's state file, which every session shares: Recent's (Db.zig).
db: Db = .{},
/// acme's Incl: the directories a look at a name that is nowhere else
/// (`stdio.h`, `<foo.h>`) is tried in, in order. The session's, seeded
/// with C's (/usr/include, /usr/local/include), kept in a dump.
incl: std.ArrayList([]u8) = .empty,
/// Plumb's rules, the user's, tried in order before the built-in ones
/// (look.resolve), the first to match taking the look. Kept in a dump.
plumb: std.ArrayList([]u8) = .empty,
/// Zerox's groups of panes on one buffer (File.syncTwins), and the id
/// the next takes.
twin_groups: std.ArrayList(pardes.panes.File.TwinGroup) = .empty,
/// The buttons held as the 9P mousein file last said (Plan 9's bits:
/// 1 left, 2 middle, 4 right): its next line presses and releases
/// what changed.
mousein_buttons: u8 = 0,
next_twin: u32 = 1,
look_src: [MAX_PANES]u32 = undefined,
n_look_src: usize = 0,
look_walk_owner: ?u32 = null,
/// hands out Pane.serial; monotonic, never reused
next_serial: u32 = 0,
/// The column whose tag the running command came from, while it runs:
/// the column acme's commands take from their Text's col.
exec_column: ?usize = null,
/// Panes made this step that found no room in their column
/// (exec.placeNew): closed at the step's end, once whatever made them
/// is done with them.
unplaced: std.StaticBitSet(MAX_PANES) = .empty,
/// A look's word search is running (look.lookUnresolved): from a
/// terminal its rows refill the directory's one +Search (Output).
word_look: bool = false,
/// The running word came from the workspace's or a column's tag, which
/// have no directory of their own: it runs in the session's
/// (`sessionDir`), as acme's row and column tags do.
exec_header: bool = false,
session_dir: [limits.host_path_cap]u8 = undefined,
/// A spawn's directory too long for the effect's inline buffer, by pane
/// slot: the effect then carries none, and perform gives the host this.
spawn_dirs: [MAX_PANES]?[]u8 = @splat(null),
session_dir_len: ?u16 = null,
settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } },
locations_config: locations.Config = .{},
locations_cache: locations.Cache = .{},
tty_filter_palette: pardes.panes.terminal.FilterPalette = .{},
font_request_taken: bool = false,
custom_theme: ?Theme = null,
/// bodyChrome's: the theme it was worked out for, and it.
body_chrome: ?struct { theme: Theme, chrome: ChromeTheme } = null,
theme_file_path: config.Runtime.Text(limits.host_path_cap) = .{},
/// The ThemeFile last loaded whole: what /ctl and DumpConfig name, and
/// what a failed ThemeFile goes back to (colors.revertThemeFile).
theme_file_loaded: config.Runtime.Text(limits.host_path_cap) = .{},
theme_file_generation: u32 = 0,
theme_file_pane: u8 = 0,
chrome: colors.ChromeTheme = colors.initial_chrome,
/// Every drawn frame's timings (FrameStats: the Debug box, PARDES_FRAMES).
frames: FrameStats = .{},
quit: bool = false,
/// A detached session with no frontend attached: nothing renders, so
/// no input ever dismisses a message (Messages.expireUnattended).
unattended: bool = false,
haptic: HapticSlot = if (platform == .macos) .none else {},
/// The look just run found nothing (look.zig missed).
look_missed: bool = false,
/// The look being run opens a .diff or .patch as text, not its +Diff:
/// Diff going back from a +Diff, Edit's B (it edits the file).
look_text: bool = false,
look_hover_wait: ?look.LookHoverWait = null,
/// The place a look-hover last found nothing to open: the pointer
/// resting there does not ask again every frame (look.noteLookHover).
look_hover_refused: ?look.LookHoverWait = null,
look_hover_preview: ?look.LookHoverPreview = null,
/// While a key is replayed across the ranges (normal.replaySels): which
/// range this pass is, in document order, how many there are, and
/// whether this is the first pass; outside a replay, the one range and
/// its first pass. A register value belongs to its range by this index.
multi_first: bool = true,
multi_stop: bool = false,
multi_index: usize = 0,
multi_count: usize = 1,
/// how many `execute` calls are on the stack — see max_exec_depth
exec_depth: u8 = 0,
/// An exec waiting on the REPL question (`Pane.Prompt.repl_choice`):
/// the pane it came from, the language, and the text, owned.
/// `offered` holds, by letter, the serial of the pane each answer named
/// when asked: a letter answered later is that pane or nothing.
repl_ask: ?struct { from: u32, lang: u8, text: []u8, offered: [26]u32 = @splat(0) } = null,
/// A key press is being handled: someone is at the keyboard to answer,
/// so a builtin may ask rather than guess. Nothing else sets it -- not
/// a click, a 9P write, a startup line or a pane's shell exiting.
can_ask: bool = false,
/// The question to the language servers awaited, and the last asked
/// (lsp/Ask.zig).
lsp_ask: Ask = .{},
pipe: Pipe = .{},
/// A query pane's Grep, and its Find's listing, on a worker (Stream.zig).
stream: Stream = .{},
fs: filesystem.Namespace = .{},
boot: Boot = .shell,
/// Is there a frame worth drawing? Cleared once one is presented, set by
/// anything that can change what is on screen. The first frame always is.
needs_frame: bool = true,
/// Set by a shell whose present was skipped (no swapchain image): the
/// frame is still owed, and the next pump draws it again.
present_skipped: bool = false,
clock: Clock = .{},
/// Builtins announce themselves on the message row. Off while startup
/// configuration is applied: those lines are nobody clicking, and should
/// not leave the row holding the name of the last one.
announce: bool = true,
// Reject overflow: evicting an older effect would reorder a byte stream.
effects: [limits.effect_cap]Effect = undefined,
effects_head: usize = 0,
effects_len: usize = 0,
// Each pty retains its own overflow tail until earlier effects drain.
pending_write: [MAX_PANES]?PendingWrite = @splat(null),
/// Total bytes parked above, so the drain path costs one comparison when
/// nothing is waiting — which is every frame that is not a large paste.
pending_write_bytes: usize = 0,
/// WHO SERVES THIS CORE. Every method optional; a null one is answered by
/// `fallback` below, so a `Host{}` is a complete in-process pardes.
host: Host = .{},
/// The in-program answers behind every unimplemented host method. Per
/// instance, so several cores behind one fan-out host stay independent.
fallback: host_io.Fallback,
/// The message-row log (see Messages.zig).
messages: Messages = .{},
in_q: [64]Event = undefined,
in_head: usize = 0,
in_len: usize = 0,
registers: Registers = .{},
macro: Macro = .{},
/// an edited text nothing kept (a tag's shown text): see edit.retireEditText
retired_edit: ?[]u8 = null,
/// the last serialized dump (gpa-owned), read by the write_dump effect
dump_out: ?[]u8 = null,
/// Where the last Dump goes as a file of its own (`Dump export`; gpa-
/// owned), else the state file.
dump_export: ?[]u8 = null,
/// where the shell wrote the last dump (shell reports back after
/// write_dump); shown in the topbar as `Restore <path>`
last_dump: ?[]const u8 = null,
/// What a session word (Newcol, New, Exit) runs with when no pane is
/// there to run it: the window Delcol emptied. Never installed, made the
/// first time it is wanted.
stand_in: ?*Pane = null,
/// a Restore builtin wants this dump loaded into the live session; the
/// shell consumes it via takeRestore each frame (restore contents stay host-fed)
restore_req: ?[]const u8 = null,
restore_buf: [1024]u8 = @splat(0),
surface: Surface = .{},
/// A replica's predicted echo (src/echo.zig), drawn over its terminals:
/// presentation, its own, in no digest and no rollback copy. Null on a
/// session's own core.
echo: ?*pardes.echo.Echo = null,
/// The live view, `views[live]` (`view()`): whose input the session
/// takes now, and whose share of the panes is in their own fields
/// (views.zig). `views_open` says which views there are, one a window
/// or terminal each.
live: u8 = 0,
views_open: u8 = 1,
/// The open views kept for their clients' rejoin (Views.away).
views_away: u8 = 0,
/// Each open view (`views_open`); a closed one is null.
views: [Views.max]?View = @splat(null),
/// The views no frontend here draws: a replica client's, which its own
/// process draws (src/replica.zig). A pump skips them.
undrawn: u8 = 0,
/// The Ctrl key into a terminal's tty mode and out (`--tty-toggle`): the
/// session's, taken from its options when it is made, so a dump carries
/// it to a replica, whose own options are its process's.
tty_toggle: u21 = config.tty_toggle_default,
/// per-update scratch (paneCursorLines, selection text); reset each update
scratch: std.heap.ArenaAllocator,
/// The arena each frame's Surface text is built in, reset by `pump`. Hosts
/// that still own their loop pass their own arena to `render` instead.
frame_arena: std.heap.ArenaAllocator,
/// the terminal motion surface, memoized against the pane it was built
/// for — see panes.terminal.RowsCache for the lifetime rule
shell_rows: pardes.panes.terminal.RowsCache = .{},
/// Finished command panes' output, and whether it is a diff
/// (File.DiffOutput).
diff_output: pardes.panes.File.DiffOutput = .{},
/// What the replay digest leaves out (src/walk.zig): what drawing
/// keeps, what is recomputed, and what only the session that performs
/// effects has.
pub const replica = .{
.local = .{
// A frame, and the timings that make it.
"surface", "frames", "chrome",
"frame_arena", "scratch",
"needs_frame", "present_skipped",
"echo",
// Drained by every pump before its digest; a replica's queues
// are its own.
"effects", "effects_head", "effects_len", "in_q", "in_head", "in_len",
// The views no frontend here draws (views.zig).
"undrawn",
// How this process was started, and the last dump it made for
// its host to write: a session loaded elsewhere has its own.
"opts", "dump_out", "dump_export",
},
.derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" },
// The host's handles, the 9P server's fids and log, the state file
// every session of the user shares (and Recent read from it), this
// session's closed panes, and the files of a host with no file
// system of its own.
.authority = .{ "host", "fs", "store", "recent", "db", "fallback" },
.len = .{ .{ "look_src", "n_look_src" }, .{ "session_dir", "session_dir_len" } },
};
/// The message row's entry points, called from everywhere as
/// `p.setMessage(...)`; they live with the rest of it in Messages.zig.
pub const setStatus = Messages.setStatus;
pub const setMessage = Messages.setMessage;
pub const reportError = Messages.reportError;
pub const reportFailure = Messages.reportFailure;
/// Running a builtin line, called from everywhere as
/// `p.executeBuiltinLine(...)`; it lives with the rest of exec in exec.zig.
pub const executeBuiltinLine = exec.executeBuiltinLine;
/// Geometry, called from everywhere as `p.bodyTop(pane, r)` and the rest
/// (setActiveColumn and tagTop by Store.zig and Handover.zig); it lives with the
/// columns in layout.zig.
pub const topBarHeight = layout.topBarHeight;
pub const bodyTop = layout.bodyTop;
pub const tagTop = layout.tagTop;
pub const setActiveColumn = layout.setActiveColumn;
/// Pane slots, called from everywhere as `p.freeSlot()` and the rest
/// (emitSpawn and installPane by dump.zig); they live with the panes
/// in panes.zig.
pub const emitSpawn = pardes.panes.emitSpawn;
pub const installPane = pardes.panes.installPane;
pub const newShell = pardes.panes.newShell;
pub const newDocPane = pardes.panes.newDocPane;
pub const newScratchBelow = pardes.panes.newScratchBelow;
pub const freeSlot = pardes.panes.freeSlot;
pub const paneBySerial = pardes.panes.paneBySerial;
pub const setTestFile = pardes.panes.setTestFile;
pub const paneDir = pardes.panes.paneDir;
pub const removePane = pardes.panes.removePane;
/// A language word's request, called from every word and test as
/// `p.lspRequest(...)`; it lives with its answer in lsp/Ask.zig.
pub const lspRequest = @import("lsp/Ask.zig").lspRequest;
/// Performing an effect, called from every host and test as
/// `p.perform(e)`; it lives with the effects in Effect.zig.
pub const perform = @import("Effect.zig").perform;
/// The one construction of a session, empty: its allocators, its column
/// and workspace tags, the 9P tree's clock and its mounts. `init` boots
/// a layout into it and a dump's restore (dump.initDump) its panes; a
/// second copy of this drifted once, leaving restored tags without an
/// allocator and every 9P mtime 0.
pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes {
const p = try gpa.create(Pardes);
p.* = .{
.gpa = gpa,
.image_gpa = opts.image_allocator orelse gpa,
.kinds = .started(opts.addons),
.tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa,
.opts = opts,
.tty_toggle = opts.tty_toggle,
.views = .{ View{
.frontend = .{ .windowed = opts.windowed },
.col_tags = @splat(.{ .what = .column, .gpa = gpa }),
.screen_w = opts.cols,
.screen_h = opts.rows,
}, null, null, null },
.global_tag = .{ .what = .workspace, .gpa = gpa },
.fs = .{},
.scratch = .init(gpa),
.frame_arena = .init(opts.frame_allocator orelse gpa),
.fallback = .{ .gpa = gpa },
.db = .{ .kind = opts.state },
};
errdefer p.deinit();
p.fs.started = ctlfs.events.now();
for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial);
p.opts.mounts = &.{};
return p;
}
/// A new session, its tape written from here when PARDES_RECORD asks.
pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes {
tape.startFromEnv();
const taped = tape.enter(null, .{ .init = opts });
const p = initSession(gpa, opts) catch |err| {
tape.leave(null, taped);
return err;
};
tape.leave(p, taped);
return p;
}
fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes {
// A new session draws a tab at the default until `Tab` says otherwise.
config.tab_now = config.tab_width;
const p = try create(gpa, opts);
errdefer p.deinit();
p.boot = Boot.of(opts);
// Asked once, at the start, whoever asks first after.
_ = p.sessionDir();
switch (p.boot) {
.document => {
const path = opts.file.?;
const opened = initial_doc: {
if (p.kinds.forPath(path)) |kind| {
const made = pardes.Kind.openFile(p, 0, kind, path);
// `pardes book.pdf:12`'s place, the kind's to take.
if (made) |_| {
if (opts.file_line > 0) {
var said: pardes.Kind.Buf(160) = .{};
var place: [16]u8 = undefined;
_ = pardes.Kind.address(p, 0, std.fmt.bufPrint(&place, "{d}", .{opts.file_line}) catch "", &said);
}
} else |_| {}
break :initial_doc made;
}
break :initial_doc pardes.panes.File.open(p, 0, path, opts.file_line);
};
if (opened) |_| {} else |err| {
if (err == error.OutOfMemory) return err;
const why = switch (@as(anyerror, err)) {
error.PermissionDenied => "permission denied",
error.FileNotFound => "no file of that name",
error.IsDirectory => "that is a directory, and not one that could be read",
error.PathTooLong => "that path is too long",
error.FileTooLarge => "that file is too large to open",
error.NotAFile => "that is a pipe or a device, not a document",
else => @errorName(err),
};
const content = try std.fmt.allocPrint(gpa, "cannot open\n\n\t{s}\n\n{s}\n", .{ path, why });
errdefer gpa.free(content);
_ = try pardes.panes.Output.open(p, 0, std.fs.path.dirname(path) orelse "/", .errors, "", content);
}
p.oneColumn();
},
.missing => {
const missing = opts.missing.?;
const content = try std.fmt.allocPrint(
gpa,
"file or directory not found\n\n\t{s}\n",
.{missing.word},
);
errdefer gpa.free(content);
_ = try pardes.panes.Output.open(p, 0, missing.dir, .errors, "", content);
p.oneColumn();
},
.stdin => {
const page = try pager.parse(gpa, opts.stdin_text.?);
errdefer gpa.free(page.spans);
const content = page.text;
errdefer gpa.free(content);
const dir = p.sessionDir();
const shown = try pardes.panes.Output.open(p, 0, dir, .{ .cmd = .New }, "", content);
// Named +Pager, as `pardes -` inside a session names its pane.
const named = try std.fs.path.join(gpa, &.{ dir, "+Pager" });
gpa.free(shown.file.?.path);
shown.file.?.path = named;
shown.file.?.pager = true;
shown.tty_filter = true;
shown.file.?.pager_diff = pardes.panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]);
shown.file.?.pager_spans = page.spans;
p.oneColumn();
},
.tty, .tty_shell => {
_ = try p.newShell(0, "");
p.panes[0].?.body.mode = .tty;
p.oneColumn();
// A bare tty is still an editor: it opens with somewhere to put
// text under the shell. The shell keeps the keyboard. A boot
// layout, like .classic's, not a placement.
if (p.boot == .tty) {
const np = try pardes.panes.newScratch(p, 0, 1, .scratch);
layout.insert(p, 0, 1, 1);
layout.splitBelow(p, 0, np);
}
},
.classic => {
_ = try p.newShell(0, "");
_ = try p.newShell(1, "");
_ = try p.newShell(2, "");
for (p.panes[0..3]) |slot| slot.?.greet = true;
p.view().ncol = 2;
p.view().cols[0].n = 2;
p.view().cols[0].panes[0] = 0;
p.view().cols[0].panes[1] = 1;
p.view().cols[1].n = 1;
p.view().cols[1].panes[0] = 2;
},
.shell => {
_ = try p.newShell(0, "");
p.panes[0].?.greet = true;
p.oneColumn();
},
}
p.sync();
for (config.default_incl) |dir| {
const copy = try gpa.dupe(u8, dir);
p.incl.append(gpa, copy) catch |err| {
gpa.free(copy);
return err;
};
}
exec.applyStartupConfig(p);
// After the startup config, whose DumpDir says where the state file is.
p.loadRecent();
colors.finishThemeInitialization(p);
p.sync();
// A config init that opens a file with `Look …` armed the pulse before
// anyone touched anything. Nobody asked for that, so boot is silent.
_ = p.takeHaptic();
// The ring is reserved whole now, so recording never allocates later.
try p.fs.log.buf.ensureTotalCapacityPrecise(p.gpa, p.fs.log.cap);
ctlfs.events.announce(p); // /log starts with the panes it booted with
return p;
}
/// The layout every single-pane boot starts from.
fn oneColumn(p: *Pardes) void {
const v = p.view();
v.ncol = 1;
v.cols[0].n = 1;
v.cols[0].panes[0] = 0;
}
/// The recent list's own allocator: it is kept best effort (a file not
/// remembered for want of memory is no failure of what opened it), so
/// on a host it takes from the process heap, not the editor's, whose
/// every failure must be answered.
// ponytail: a host heap for a best-effort list.
pub fn recentGpa(_: *const Pardes) std.mem.Allocator {
return std.heap.smp_allocator;
}
/// Recent read from the state file once at start: a new session's.
pub fn loadRecent(p: *Pardes) void {
// A replica's Recent is its own, in memory: the recording session's
// state file is every session's of its user (src/tape.zig).
if (tape.replaying()) p.db.kind = .off;
p.db.readRecent(p);
}
/// What changed written out, at the end of a step and at the end.
pub fn saveRecent(p: *Pardes) void {
p.db.writeRecent(p, false);
}
/// Whether `path` is one Recent keeps: a file on this host's disk, not
/// the served tree's (`/virtual/`) nor a name never saved.
pub fn recentKeeps(path: []const u8) bool {
const local = filesystem.localPath(path) orelse return false;
return exec.kindOf(local) == .file;
}
/// A file pane or a kind's (a PDF, a picture) closing: its place noted in Recent, when
/// Recent keeps it.
pub fn noteClosed(p: *Pardes, pane: *const Pane) void {
const d = recentPlace(pane) orelse return;
// The host asked first, always: what Recent holds is the
// authority's, and a step that asked only when it did not know the
// file would ask on one side and not the other.
if (!recentKeeps(d.path) and p.recent.get(d.path) == null) return;
p.recent.closed(p.recentGpa(), d.path, d.line, d.col, d.aline, d.acol);
}
pub const RecentPlace = struct { path: []const u8, line: u32, col: u32, aline: u32 = 0, acol: u32 = 0 };
/// Where a pane is, as Recent keeps it: a file's dot, a kind's pane's
/// path and the first number of its `where` (a PDF's page), 0 for none.
/// Null for any other.
pub fn recentPlace(pane: *const Pane) ?RecentPlace {
if (recentDot(pane)) |d| return .{ .path = d.path, .line = d.line, .col = d.col, .aline = d.aline, .acol = d.acol };
if (pane.addon) |k| if (k.path.len > 0) {
var buf: [32]u8 = undefined;
const line = Jump.firstNumber(pardes.Kind.placeOf(@constCast(k), &buf));
return .{ .path = k.path, .line = line, .col = @intFromBool(line > 0) };
};
return null;
}
/// A file pane's path and dot, for the recent list (0 when none).
pub fn recentDot(pane: *const Pane) ?struct { path: []const u8, line: u32, col: u32, aline: u32 = 0, acol: u32 = 0 } {
const f = pane.file orelse return null;
if (f.output != null) return null;
// The selection's anchor too, so a reopen restores both its ends.
const sel = pane.body.vsel.active;
return .{
.path = f.path,
.line = @intCast(@max(0, pane.body.cur_row) + 1),
.col = @intCast(@max(0, pane.body.cur_col) + 1),
.aline = if (sel) @intCast(@max(0, pane.body.vsel.row) + 1) else 0,
.acol = if (sel) @intCast(@max(0, pane.body.vsel.col) + 1) else 0,
};
}
/// The session's configuration directory and startup file, as a step
/// reads them: its process's options, so the authority's
/// (`tape.authority`); a replica's are its own process's.
pub fn configDir(p: *Pardes) ?[]const u8 {
return tape.authority(optsConfigDir, .{p});
}
pub fn startupPath(p: *Pardes) ?[]const u8 {
return tape.authority(optsStartupPath, .{p});
}
fn optsConfigDir(p: *Pardes) ?[]const u8 {
return p.opts.config_dir;
}
fn optsStartupPath(p: *Pardes) ?[]const u8 {
return p.opts.startup_config_path;
}
/// The recent entry a closed jump names, by its path's hash, its path
/// in scratch. Recent is the authority's (every window of its user
/// writes it): a replica has its answer (`tape.authority`).
pub fn recentByHash(p: *Pardes, hash: u64) ?recent_files.Entry {
return tape.authority(recentFound, .{ p, hash });
}
fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry {
for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) {
var found = e;
found.path = p.scratch.allocator().dupe(u8, e.path) catch return null;
return found;
};
return null;
}
pub fn deinit(p: *Pardes) void {
const taped = tape.enter(p, .{ .deinit = tape.current(p) });
tape.forget(p);
defer tape.leave(null, taped);
if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path));
// Every file open now is closed with its dot, and the list kept.
for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane);
p.db.writeRecent(p, true);
// The state file compacted once it is mostly what no moment holds.
p.db.compact(p);
p.db.deinit();
p.store.deinit(p.recentGpa());
p.recent.deinit(p.recentGpa());
for (p.incl.items) |dir| p.gpa.free(dir);
p.incl.deinit(p.gpa);
for (p.plumb.items) |rule| p.gpa.free(rule);
p.plumb.deinit(p.gpa);
for (p.twin_groups.items) |group| p.gpa.free(group.path);
p.twin_groups.deinit(p.gpa);
p.fs.batch.bytes.deinit(p.gpa);
if (p.stand_in) |pane| pardes.panes.teardownPane(p, pane);
look.cancelLookHover(p);
if (p.repl_ask) |ask| p.gpa.free(ask.text);
for (0..MAX_PANES) |id| p.dropPendingWrite(id);
// The panes, then those retired these last two frames.
inline for (.{ &p.panes, &p.retired_panes.previous, &p.retired_panes.current }) |slots| for (slots) |*slot| if (slot.*) |pane| {
pardes.panes.teardownPane(p, pane);
slot.* = null;
};
const gpa = p.gpa;
Views.deinit(p);
p.global_tag.deinit(gpa);
p.registers.deinit(gpa);
p.macro.deinit(gpa);
if (p.retired_edit) |r| gpa.free(r);
if (p.dump_out) |d| gpa.free(d);
if (p.dump_export) |d| gpa.free(d);
p.fallback.deinit();
if (p.last_dump) |d| gpa.free(d);
if (p.custom_theme) |theme_value| gpa.free(theme_value.name);
for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir);
p.pipe.deinit(gpa);
p.stream.deinit(gpa);
p.handover.deinit(gpa);
if (p.stream.ahead.len > 0) p.tree_sitter_gpa.free(p.stream.ahead);
p.locations_cache.deinit(p.tree_sitter_gpa);
p.fs.deinit(gpa);
p.shell_rows.reset(gpa);
p.diff_output.reset(gpa);
p.scratch.deinit();
p.frame_arena.deinit();
gpa.free(p.surface.cells);
for (&p.surface.body_layers) |*layer| gpa.free(layer.cells);
for (&p.surface.tag_layers) |*layer| gpa.free(layer.cells);
p.surface.placements.deinit(gpa);
gpa.destroy(p);
}
/// shell feedback after write_dump: remember where the dump landed (the
/// topbar grows a `Restore <path>` word pointing at it)
pub fn setLastDump(p: *Pardes, path: []const u8) void {
const taped = tape.enter(p, .{ .set_last_dump = path });
defer tape.leave(p, taped);
p.pointRestoreAt(path);
ctlfs.events.notePath(p, "dump", path);
}
/// The workspace tag's `Restore <path>` names `path` from now on: the
/// default's does by itself, and one the tag was edited around (its own
/// text) has the old path swapped, never left pointing at a dump that is
/// not the last.
pub fn pointRestoreAt(p: *Pardes, path: []const u8) void {
const copy = p.gpa.dupe(u8, path) catch return;
if (p.last_dump) |old| {
if (p.global_tag.own) |own| swap: {
const a = p.scratch.allocator();
const was = std.fmt.allocPrint(a, "Restore {s}", .{old}) catch break :swap;
if (std.mem.indexOf(u8, own, was) == null) break :swap;
const now = std.fmt.allocPrint(a, "Restore {s}", .{path}) catch break :swap;
const swapped = std.mem.replaceOwned(u8, p.gpa, own, was, now) catch break :swap;
p.gpa.free(own);
p.global_tag.own = swapped;
}
p.gpa.free(old);
}
p.last_dump = copy;
}
/// the shell polls this each frame: a pending Restore's dump path, or null
pub fn takeRestore(p: *Pardes) ?[]const u8 {
const taped = tape.enter(p, .take_restore);
defer tape.leave(p, taped);
const r = p.restore_req;
p.restore_req = null;
return r;
}
/// DECSET 1004: a program that asked is told `CSI I` when its pane
/// takes the keyboard (the active pane, its body, the window focused)
/// and `CSI O` when it gives it up, to another pane, a tag or header,
/// or another window.
fn reportFocus(p: *Pardes) void {
const v = p.view();
const want: @FieldType(View, "focus_told") = blk: {
if (!v.window_focused or v.header != null) break :blk null;
const pane = p.panes[v.active] orelse break :blk null;
if (pane.focus != .body) break :blk null;
break :blk .{ .id = v.active, .serial = pane.serial };
};
if (std.meta.eql(want, v.focus_told)) return;
if (v.focus_told) |old| if (p.panes[old.id]) |pane| {
if (pane.serial == old.serial and pardes.panes.terminal.reportsFocus(pane)) p.emitWrite(old.id, "\x1b[O");
};
if (want) |new| if (pardes.panes.terminal.reportsFocus(p.panes[new.id].?)) p.emitWrite(new.id, "\x1b[I");
v.focus_told = want;
}
pub fn emitWrite(p: *Pardes, id: usize, bytes: []const u8) void {
var off: usize = 0;
// Anything already parked for this pane owns the stream's position, so
// new bytes queue BEHIND it — emitting them now would reorder the pty.
if (p.pending_write[id] == null) {
while (off < bytes.len and p.effects_len < p.effects.len) {
const n = @min(bytes.len - off, effect_write_cap);
p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(bytes[off .. off + n]) } });
off += n;
}
}
if (off < bytes.len) p.parkPendingWrite(id, bytes[off..]);
}
/// How many bytes `emitWrite` can take for pane `id` now without
/// dropping any: the effects left, then what the pending buffer holds.
pub fn writeRoom(p: *const Pardes, id: usize) usize {
const pending = limits.pending_write_cap -| p.pending_write_bytes;
if (p.pending_write[id] != null) return pending;
return (p.effects.len - p.effects_len) * effect_write_cap + pending;
}
pub fn parkPendingWrite(p: *Pardes, id: usize, bytes: []const u8) void {
if (p.pending_write_bytes + bytes.len > limits.pending_write_cap) return;
if (p.pending_write[id]) |*pw| {
// Compact what the drain already sent before growing: a burst that
// arrives in pieces must not keep re-copying bytes nobody wants.
const keep = pw.bytes.len - pw.off;
const grown = p.gpa.alloc(u8, keep + bytes.len) catch return;
@memcpy(grown[0..keep], pw.bytes[pw.off..]);
@memcpy(grown[keep..], bytes);
p.gpa.free(pw.bytes);
pw.* = .{ .bytes = grown };
} else {
p.pending_write[id] = .{ .bytes = p.gpa.dupe(u8, bytes) catch return };
}
p.pending_write_bytes += bytes.len;
}
/// The shell reports the spawned pane's working directory (and later cwd
/// changes it observes, e.g. via /proc/<pid>/cwd before each frame).
pub fn setCwd(p: *Pardes, id: usize, cwd: []const u8) void {
const taped = tape.enter(p, .{ .set_cwd = .{ .id = id, .cwd = cwd } });
defer tape.leave(p, taped);
const pane = p.panes[id] orelse return;
// A command pane stays the directory's it was run for (newCommand).
if (pane.command != null) return;
const cur = switch (pane.cwd) {
.owned => |dir| dir,
else => "",
};
if (std.mem.eql(u8, cur, cwd)) return;
// A shell started in a directory is asked where it is before it has
// said anything: its chdir may not have happened yet, and the answer
// is this process's directory, a rename to undo. That answer, then,
// is not taken.
if (pane.isTerminal() and !pane.shell_spoke and pane.cwd == .owned and std.mem.eql(u8, cwd, p.sessionDir())) return;
// One with no directory yet is named by the session's (nameOf): its
// shell saying it is there is no new name.
const same_name = cur.len == 0 and std.mem.eql(u8, cwd, p.sessionDir());
pane.setOwnedCwd(cwd) catch |err| return p.reportError(id, "directory", err);
if (look.lookHoverPane(p) == id) look.cancelLookHover(p);
// A terminal is named by its directory, so /log hears it renamed; one
// not announced yet is announced under the new name.
if (pane.isTerminal() and !same_name) ctlfs.events.noteLog(p, .rename, pane);
}
pub fn shellBin(p: *const Pardes) []const u8 {
const selected = p.settings.shell.requested.get();
return if (selected.len == 0) config.defaultShell() else selected;
}
/// A shell a dead session left, taken in (Adopt): a terminal pane made
/// for it as the Term word makes one, its greeting off (the shell is up
/// already), whose spawn the host answers with that shell's pty. Its id,
/// or null with no room. An input, as every host write into the core
/// is: a replica of the session makes the same pane.
pub fn adoptShell(p: *Pardes) ?u8 {
const taped = tape.enter(p, .adopt_shell);
defer tape.leave(p, taped);
var newest: u32 = 0;
for (p.panes) |slot| if (slot) |pn| {
newest = @max(newest, pn.serial);
};
_ = p.executeBuiltinLine(p.view().active, "Term");
for (p.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) {
pn.greet = false;
return @intCast(id);
};
return null;
}
/// A terminal's reader failed (no end of file: the host closed its pty):
/// its pane takes keys again, and why is said.
pub fn readerFailed(p: *Pardes, id: u8, err: anyerror) void {
const taped = tape.enter(p, .{ .reader_failed = .{ .id = id, .err = err } });
defer tape.leave(p, taped);
const pane = p.panes[id] orelse return;
pane.body.mode = .normal;
p.reportError(id, "terminal reader", err);
}
pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_marks: bool) void {
const taped = tape.enter(p, .{ .acknowledge_shell = .{ .id = id, .executable = executable, .prompt_marks = prompt_marks } });
defer tape.leave(p, taped);
if (id < MAX_PANES) if (p.panes[id]) |pane| {
ctlfs.pty.shellGone(p, pane, true); // a respawn replaced whatever ran
pane.shell_failed = false;
pane.had_shell = true;
pane.fs.unmarked = !prompt_marks;
// The tag's Term word names the shell the host ran, and a click
// on it (`Term+fish`) opens another of the same.
if (pane.command == null) {
// A shell given as a path keeps it: its bare name would find
// nothing, or another program, on the usual paths.
const base = if (pane.shell) |given| (if (std.mem.indexOfScalar(u8, given, '/') != null) given else std.fs.path.basename(executable)) else std.fs.path.basename(executable);
const rest = tagline.terminal_pane_tail[" Term".len..];
if (std.fmt.bufPrint(&pane.shell_tail, " Term+{s}{s}", .{ base, rest })) |tail| {
pane.shell_tail_len = @intCast(tail.len);
} else |_| {}
}
};
if (id < MAX_PANES) pardes.panes.terminal.shellSpawned(p, id, prompt_marks);
if (p.settings.shell.effective.set(executable))
p.settings.shell.pending = false;
}
/// A window's font, asked and told (this and the three below): in every
/// build, not only a window's, as only a window's host calls
/// them and a terminal's replica of a window's session must step as
/// the window does.
pub fn takeFontRequest(p: *Pardes) ?[]const u8 {
const taped = tape.enter(p, .take_font_request);
defer tape.leave(p, taped);
if (!p.settings.font.pending or p.font_request_taken) return null;
const path = p.settings.font.requested_path.get();
if (path.len == 0) return null;
p.font_request_taken = true;
return path;
}
pub fn observeFont(
p: *Pardes,
effective_name: []const u8,
effective_size_hundredths: u16,
unit: config.Runtime.FontSizeUnit,
) bool {
const taped = tape.enter(p, .{ .observe_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } });
defer tape.leave(p, taped);
if (!p.settings.font.effective_name.set(effective_name)) return false;
p.settings.font.effective_size_hundredths = effective_size_hundredths;
p.settings.font.effective_size_unit = unit;
return true;
}
/// Resolve the request already handed to the GUI host. Requested and
/// effective tuples deliberately remain separate so DumpConfig can show both.
pub fn acknowledgeFont(
p: *Pardes,
effective_name: []const u8,
effective_size_hundredths: u16,
unit: config.Runtime.FontSizeUnit,
) bool {
const taped = tape.enter(p, .{ .acknowledge_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } });
defer tape.leave(p, taped);
if (!p.settings.font.pending or !p.font_request_taken) return false;
const changed = !std.mem.eql(
u8,
p.settings.font.effective_name.get(),
effective_name,
) or p.settings.font.effective_size_hundredths != effective_size_hundredths or
p.settings.font.effective_size_unit != unit;
if (!p.observeFont(effective_name, effective_size_hundredths, unit)) return false;
p.settings.font.pending = false;
p.font_request_taken = false;
if (changed) look.cancelLookHover(p);
return true;
}
pub fn rejectFont(p: *Pardes) void {
const taped = tape.enter(p, .reject_font);
defer tape.leave(p, taped);
if (!p.settings.font.pending or !p.font_request_taken) return;
p.settings.font.pending = false;
p.font_request_taken = false;
}
fn applyWatchedFileChanged(p: *Pardes, id: u8, bytes: []const u8) bool {
if (id >= MAX_PANES) return false;
const pane = p.panes[id] orelse return false;
if (pane.addon != null) return pardes.Kind.fileChanged(p, id, bytes);
if (pane.file == null) return false;
pardes.panes.File.changed(p, id, bytes);
return if (p.panes[id]) |current|
if (current.file) |file| std.mem.eql(u8, file.content, bytes) else false
else
false;
}
/// The live view.
pub inline fn view(p: anytype) if (@typeInfo(@TypeOf(p)).pointer.attrs.@"const") *const View else *View {
return &p.views[p.live].?;
}
/// A view of its own for a new client (a second window, a terminal
/// `pardes --attach`ed), as the live one is laid out; null at
/// Views.max. Not live until `toView`.
pub fn openView(p: *Pardes) ?u8 {
const taped = tape.enter(p, .open_view);
defer tape.leave(p, taped);
// Every view taken: one kept for a client that has not come back
// for it (Views.away) goes first. ponytail: no timer lets one go;
// until its place is wanted it costs a parked slot, and a terminal
// it sized last keeps that size until another view types into it.
if (@popCount(p.views_open) == Views.max and p.views_away != 0) {
Views.close(p, @ctz(p.views_away));
p.sync();
}
// What was queued since the last pump (a leaving client's view
// closed, a 9P request's step) done first, as every client of the
// tape does it here: a join dumps the session next, and a core
// loaded from a dump has no queue (Replica.initDump).
p.settle();
p.needs_frame = true;
return Views.open(p);
}
/// The client of view `k` gone: its view goes, the others stay. The
/// last one stays the session's own.
pub fn closeView(p: *Pardes, k: u8) void {
const taped = tape.enter(p, .{ .close_view = k });
defer tape.leave(p, taped);
Views.close(p, k);
p.sync();
// What its sync queued (a terminal it sized, sized again) done here,
// in its own unit on every side: the session's next pump is another
// unit, and a replica takes a copy only of a core with nothing
// queued (rollback.Copy.take).
p.settle();
}
/// The last client of a session no one else watches gone: its view
/// goes, and the session's own is laid out as it was (Views.closeKeeping),
/// which the client's rejoin copies. Settled as `closeView` is.
pub fn leaveView(p: *Pardes, k: u8) void {
const taped = tape.enter(p, .{ .leave_view = k });
defer tape.leave(p, taped);
Views.closeKeeping(p, k);
p.sync();
p.settle();
}
/// The client of view `k` gone, to join again for it (an Upgrade's
/// rejoin, a divergence's): its view kept as it is (Views.away).
pub fn awayView(p: *Pardes, k: u8) void {
const taped = tape.enter(p, .{ .away_view = k });
defer tape.leave(p, taped);
Views.away(p, k);
}
/// A client back for view `k`, kept for it (`awayView`): its own again,
/// as it left it; false when it was let go meanwhile. Settled as
/// `openView` is, for the join's dump next.
pub fn rejoinView(p: *Pardes, k: u8) bool {
const taped = tape.enter(p, .{ .rejoin_view = k });
defer tape.leave(p, taped);
if (!Views.isAway(p, k)) return false;
p.views_away &= ~(@as(u8, 1) << @intCast(k));
p.settle();
p.needs_frame = true;
return true;
}
/// Into view `k`, before the input its client sent.
pub fn toView(p: *Pardes, k: u8) void {
if (k == p.live) return;
const taped = tape.enter(p, .{ .to_view = k });
defer tape.leave(p, taped);
Views.to(p, k);
}
/// Something changed the core without going through `update` -- a watched
/// file reloading under it, a theme file rewritten on disk. `pump` draws
/// only when it has a reason to, and this is the reason.
pub fn invalidate(p: *Pardes) void {
const taped = tape.enter(p, .invalidate);
defer tape.leave(p, taped);
p.needs_frame = true;
}
pub fn reloadWatchedFile(p: *Pardes, id: u8, bytes: []const u8) bool {
const taped = tape.enter(p, .{ .reload_watched_file = .{ .id = id, .bytes = bytes } });
defer tape.leave(p, taped);
p.invalidate();
look.invalidateLookHover(p, id);
const applied = p.applyWatchedFileChanged(id, bytes);
_ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept });
p.sync();
return applied;
}
pub fn emit(p: *Pardes, e: Effect) void {
if (p.effects_len == p.effects.len) return;
const tail = (p.effects_head + p.effects_len) % p.effects.len;
p.effects[tail] = e;
p.effects_len += 1;
}
pub fn nextEffect(p: *Pardes) ?Effect {
const taped = tape.enter(p, .next_effect);
defer tape.leave(p, taped);
p.refillPendingWrites();
if (p.effects_len == 0) {
p.effects_head = 0;
return null;
}
const e = p.effects[p.effects_head];
p.effects_head = (p.effects_head + 1) % p.effects.len;
p.effects_len -= 1;
return e;
}
/// Move parked pty bytes into whatever room the ring now has, oldest pane
/// slot first. Costs one comparison when nothing is parked.
fn refillPendingWrites(p: *Pardes) void {
if (p.pending_write_bytes == 0) return;
for (&p.pending_write, 0..) |*slot, id| {
while (p.effects_len < p.effects.len) {
// `|*pw|` points INTO the slot: capturing by value would advance
// a copy's cursor and re-send the same chunk for ever.
const pw = if (slot.*) |*live| live else break;
const n = @min(pw.bytes.len - pw.off, effect_write_cap);
p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(pw.bytes[pw.off..][0..n]) } });
pw.off += n;
p.pending_write_bytes -= n;
if (pw.off == pw.bytes.len) {
p.gpa.free(pw.bytes);
slot.* = null;
break;
}
}
if (p.effects_len == p.effects.len) return;
}
}
/// Drop a pane's parked bytes: its pty is gone, and the slot it occupied
/// may be handed to a different pane next frame.
pub fn dropPendingWrite(p: *Pardes, id: usize) void {
const pw = p.pending_write[id] orelse return;
p.pending_write_bytes -= pw.bytes.len - pw.off;
p.gpa.free(pw.bytes);
p.pending_write[id] = null;
}
pub fn postEvent(p: *Pardes, ev: Event) void {
switch (ev) {
.key => |k| std.debug.assert(k.text.len == 0),
.output, .paste, .lsp_resp, .pipe_resp, .search, .file_changed, .command, .addon, .job => unreachable,
else => {},
}
if (p.in_len == p.in_q.len) return;
p.in_q[(p.in_head + p.in_len) % p.in_q.len] = ev;
p.in_len += 1;
}
fn nextQueued(p: *Pardes) ?Event {
if (p.in_len == 0) {
p.in_head = 0;
return null;
}
const ev = p.in_q[p.in_head];
p.in_head = (p.in_head + 1) % p.in_q.len;
p.in_len -= 1;
return ev;
}
pub fn hostForegroundName(p: *const Pardes, id: usize, buf: []u8) ?[]const u8 {
const f = p.host.vtable.fg_name orelse return null;
return f(p.host.ctx, @intCast(id), buf);
}
pub fn hostTtyTaken(p: *const Pardes, id: usize) bool {
const f = p.host.vtable.tty_taken orelse return false;
return f(p.host.ctx, @intCast(id));
}
pub fn hostKillJob(p: *const Pardes, id: usize) bool {
const f = p.host.vtable.kill_job orelse return false;
return f(p.host.ctx, @intCast(id));
}
/// A terminal whose shell could not be started: said, and a run waiting
/// on it, or written to it from now on, hears `error shell gone`
/// rather than wait for a prompt that never comes.
pub fn shellFailed(p: *Pardes, id: u8, err: anyerror) void {
const taped = tape.enter(p, .{ .shell_failed = .{ .id = id, .err = err } });
defer tape.leave(p, taped);
const pane = p.panes[id] orelse return;
pane.shell_failed = true;
ctlfs.pty.shellGone(p, pane, false);
p.sayShellFailure(id, err);
// A command that never started ended: `exit 127`, as a shell says of
// a command it could not run, so a follower waiting on its exit
// hears one, its tag stops saying it runs, and Kill finds nothing.
if (pane.command != null and !pane.command_done) {
pane.command_pty = false;
exec.commandDone(p, id, 127);
} else if (pane.command == null and !pane.had_shell) {
// A Term whose shell never ran: no dead pane left behind; the
// write that asked for it has failed with why. A terminal whose
// shell was started again (pty/ctl exec) keeps its pane.
p.unplaced.set(id);
}
}
/// A shell started again in a terminal whose shell runs (pty/ctl's
/// exec) did not start: the host kept the running one, so only said.
pub fn restartFailed(p: *Pardes, id: u8, err: anyerror) void {
const taped = tape.enter(p, .{ .restart_failed = .{ .id = id, .err = err } });
defer tape.leave(p, taped);
if (p.panes[id] == null) return;
p.sayShellFailure(id, err);
}
fn sayShellFailure(p: *Pardes, id: u8, err: anyerror) void {
const pane = p.panes[id] orelse return;
if (err == error.FileNotFound or err == error.NotDir) {
p.reportFailure(id, "shell: directory missing (no such directory)");
} else if (err == error.InterpreterNotFound) {
// The script is there; the program its `#!` names is not.
var said: [320]u8 = undefined;
var interp: [256]u8 = undefined;
const name = tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp });
p.reportFailure(id, if (name) |n| std.fmt.bufPrint(&said, "shell: interpreter {s} not found", .{n}) catch "shell: interpreter not found" else "shell: interpreter not found");
} else {
p.reportError(id, "shell", err);
}
// A 9P write that asked for the shell (pty/ctl's exec), waiting on
// it, fails with what was said, as a failed Save's does.
p.noteLateFailure(id);
}
/// The program the shell's `#!` names that is not there, in `out`.
fn missingInterpreter(bin: []const u8, out: []u8) ?[]const u8 {
const Shell = @import("host_io.zig").Shell;
var buf: [std.fs.max_path_bytes]u8 = undefined;
return Shell.missingInterpreter(Shell.find(bin, &buf) orelse return null, out);
}
/// The directory a write of `path` that failed with `err` went into:
/// what is there (a directory when it is no local path), whether it is
/// missing, and whether that is because one above refuses (EACCES).
fn parentTrouble(path: []const u8, err: anyerror) struct { dir: []const u8, kind: ?std.Io.File.Kind, missing: bool, denied: bool } {
const dir = std.fs.path.dirname(path) orelse "/";
const local = filesystem.localPath(dir);
const kind: ?std.Io.File.Kind = if (local) |l| exec.kindOf(l) else .directory;
const missing = err == error.FileNotFound or err == error.NotDir or kind != .directory;
const denied = missing and (if (local) |l| tape.value(.denied, filesystem.deniedAbove, .{l}) else false);
return .{ .dir = dir, .kind = kind, .missing = missing, .denied = denied };
}
pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void {
const taped = tape.enter(p, .{ .save_failed = .{ .id = id, .path = path, .err = err } });
defer tape.leave(p, taped);
if (p.panes[id]) |pane| if (pane.file) |*f| {
// The `-%` spelling fs.zig already uses for "make this dirty".
f.saved_revision = f.revision -% 1;
};
var what: [limits.host_path_cap + 32]u8 = undefined;
// A write into a directory that is not there: said so, in the words
// a mount reads as ENOENT; EACCES when one above refuses.
const parent = parentTrouble(path, err);
if (parent.denied)
p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: permission denied", .{path}) catch "Save: permission denied")
else if (parent.missing)
p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: no such directory", .{path}) catch "Save: no such directory")
else
p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{path}) catch "Save", err);
p.noteLateFailure(id);
}
/// A Dump the host could not write: said on the message row and in the
/// log, and the 9P write that asked for it fails with it, as a failed
/// Save's does.
pub fn dumpFailed(p: *Pardes, path: []const u8, err: anyerror) void {
const v = p.view();
const taped = tape.enter(p, .{ .dump_failed = .{ .path = path, .err = err } });
defer tape.leave(p, taped);
var what: [limits.host_path_cap + 8]u8 = undefined;
const operation = std.fmt.bufPrint(&what, "Dump {s}", .{path}) catch "Dump";
// Into a DumpDir that is not there: said so, ENOENT, as a Save is;
// one that is there but no directory (`/dev/null`) says that.
const parent = parentTrouble(path, err);
var said: [limits.host_path_cap + 48]u8 = undefined;
if (parent.denied and parent.kind == null)
p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: permission denied", .{operation}) catch "Dump: permission denied")
else if (parent.kind != null and parent.kind != .directory)
p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: {s} is not a directory", .{ operation, parent.dir }) catch "Dump: not a directory")
else if (parent.missing)
p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: no such directory", .{operation}) catch "Dump: no such directory")
else
p.reportError(v.active, operation, err);
// In the words the message row has, so the write's err is the one
// record of it (its msg goes: 9p_io, dropMessage).
p.noteLateFailure(v.active);
}
pub fn fsPayload(p: *const Pardes, r: ctlfs.Reply) []const u8 {
return switch (r.payload) {
.none => &.{},
.staged => |n| p.fs.out.items[0..@min(n, p.fs.out.items.len)],
.region => |g| region: {
const pane = p.panes[g.pane] orelse break :region &.{};
if (pane.serial != g.serial) break :region &.{};
const text = if (pane.file) |*f| f.content else break :region &.{};
const lo = @min(g.off, text.len);
break :region text[lo..@min(lo + g.len, text.len)];
},
};
}
pub fn pump(p: *Pardes, host: Host) !void {
p.host = host;
const taped = tape.enter(p, .pump);
defer tape.leave(p, taped);
// The host as the tape sees it, while it records.
const h = p.host;
const v = h.vtable;
if (v.wait_input) |f| {
// Asleep until input or until the core's next deadline
// (nextWake); 0 is no timeout at all.
// The clock read whether or not it is wanted: what a replica
// waits on is its own (a picture decoding wakes only a frame
// that draws it), and the tape has the same calls either way.
const now = if (v.now) |clock| clock(h.ctx) else p.clock.now_ns;
const timeout: u32 = if (p.nextWake()) |due| wake: {
const ms = ((due -| now) + std.time.ns_per_ms - 1) / std.time.ns_per_ms;
break :wake @intCast(std.math.clamp(ms, 1, std.math.maxInt(u32)));
} else 0;
f(h.ctx, timeout);
}
// Detached, nobody's key dismisses a message: they go on the clock,
// here in the step, where the clock read is taped (the host's wait
// did it, untaped, and a replay kept a message its session had let
// go).
Messages.expireUnattended(p);
p.frames.mark_start = FrameStats.nowNs();
if (v.now) |clock| p.advance(clock(h.ctx));
p.settle();
// A quitting frame has already freed what it would draw.
if (p.quit) return;
if (v.poll_frame) |f| f(h.ctx);
// Nothing to draw: do not spend a frame, and above all do not block on
// the display for one. This is what keeps the frame rate governing
// rendering and nothing else.
// A shell with a clock draws what `advance` stepped; one without
// steps its own `.tick`s and draws while a deadline is due.
if (!p.needs_frame and (v.now != null or !p.animationActive())) return p.frames.idle();
// No one to see it: the frame stays owed (needs_frame), not drawn.
// A pty streaming into an unwatched session spent most of its time
// drawing what nobody looked at.
if (v.watched) |f| if (!f(h.ctx)) return;
// The one view this process shows (a replica client's is its own
// process's to draw), drawn as it is if another's is live.
const shown = Views.shown(p);
if (shown != p.live) {
if (shown) |k| try Views.drawOne(p, k, .{ .ctx = h.ctx, .f = v.present });
} else {
_ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept });
p.frames.mark_update = FrameStats.nowNs();
p.frames.view = if (p.panes[p.view().active]) |pane| pane.scroll() else 0;
const surface = try p.render(p.frame_arena.allocator());
p.frames.mark_render = FrameStats.nowNs();
if (v.present) |f| f(h.ctx, surface);
Stream.askAhead(p);
}
// Settled before post_present: a shell ticks there, and what that
// tick moves owes the next frame.
const skipped = p.present_skipped;
p.needs_frame = p.present_skipped;
p.present_skipped = false;
if (v.post_present) |f| f(h.ctx);
// Still moving: the next frame is owed a period from now.
const owed = if (p.nextWake()) |due| due <= p.clock.stepped_ns + frame_ns else false;
p.frames.record(FrameStats.nowNs(), owed, skipped);
}
/// What a pump does between its wait and its frame: the queued inputs
/// and the effects. Also the session at a step boundary, taken now (an
/// Upgrade's dump, upgrade.zig).
pub fn settle(p: *Pardes) void {
// What a 9P open wrote in a row goes in once the writes pause.
ctlfs.pane.flushPausedBatch(p);
// ...and what a /pager open was written before its close.
ctlfs.ctl.fillClosedPagers(p);
// ...and the last line of an open closed with no newline after it.
ctlfs.runClosedLines(p);
while (p.nextQueued()) |ev| p.update(ev);
while (p.nextEffect()) |e| p.perform(e);
turn.bump(&turn.epoch);
}
/// A replica client's input settled on the authority (src/replica.zig):
/// a pump that waits on nothing, reads no clock and draws nothing, so
/// the client's own core can apply the same at once and expect the
/// authority's tape of it to read the same. The session's own pump
/// draws it after.
pub fn step(p: *Pardes) void {
const taped = tape.enter(p, .step);
defer tape.leave(p, taped);
p.settle();
}
/// One request of the control filesystem, from whichever thread has the
/// turn (`pardes.turn`). Not an event: it neither sweeps nor resets
/// anything the editor's own step may be in the middle of using, so it
/// can be answered while that step is out in a syscall. Only a request
/// that changes a pane costs a frame, which is why a round trip on a
/// local socket costs microseconds and not a vsync.
pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply {
const taped = tape.enter(p, .{ .serve_fs = req });
defer tape.leave(p, taped);
// The held write of an Edit whose commands run, asked again by a
// retry of its park: still waiting, or its answer, never run twice.
if (p.fs.edit_hold) |*h| if (h.names(req)) {
if (!h.done) return .{ .tag = req.tag, .status = .again };
return filesystem.EditHold.answer(&p.fs);
};
defer pardes.panes.File.syncTwins(p);
if (!ctlfs.changesPane(p, req)) return ctlfs.handle(p, req);
// An address, a limit or the mark flag is nothing drawn: a script's
// addr write then its close costs no frame between them.
const drawn = if (ctlfs.Node.target(req.node)) |t| !(t == .pane and (t.pane.file == .addr or t.pane.file == .limit or t.pane.file == .mark)) else true;
if (drawn) p.needs_frame = true;
p.view().raw_hover_intent = false;
look.cancelLookHover(p);
p.fs.serving = true;
p.fs.lsp_answer_at = null;
p.fs.edit_started = false;
const reply = ctlfs.handle(p, req);
p.fs.serving = false;
// The one-failure rule is a write's: a refused open (its OTRUNC's
// truncation, a setattr, too), create or remove is its Rerror alone,
// no err, as is a write to pane/new, which is only ever read.
const ruled = req.op == .write and req.node != @backingInt(ctlfs.TopFile.new);
if (reply.status == .err and ruled) ctlfs.events.noteError(p, req, reply);
// The request was a whole step of its own, so it settles the way a
// step does: the cursor and scroll reconciled, the scripted panes
// told, and the panes it made announced to /log now rather than at
// the end of whatever the editor does next.
pardes.Kind.step(p);
p.sync();
p.fsReport();
// A /focus write moves the keyboard as a click does: the programs
// that asked (DECSET 1004) hear it now, as after update().
p.reportFocus();
ctlfs.events.announce(p);
return reply;
}
pub fn update(p: *Pardes, ev: Event) void {
const v = p.view();
const taped = tape.enter(p, .{ .update = ev });
defer tape.leave(p, taped);
defer pardes.panes.File.syncTwins(p);
defer p.reportFocus();
// A tick with no deadline due is the one event that cannot change
// the screen.
p.needs_frame = p.needs_frame or ev != .tick;
p.shell_rows.sweep(p.gpa);
Messages.expireUnattended(p);
// An announcement stands in only until its own step says more.
for (p.panes) |slot| if (slot) |pane| {
pane.msg_announcement = false;
};
// A Look's hover outlives a tick, a batch of rows coming in (no
// gesture), a move with no button, and a change to another pane.
const hover_stays = switch (ev) {
.tick, .search => true,
.mouse => |m| m.button == .none and m.kind == .motion,
.output => |o| look.lookHoverPane(p) != o.pane,
.file_changed => |changed| look.lookHoverPane(p) != changed.pane,
else => false,
};
if (!hover_stays) {
v.raw_hover_intent = false;
look.cancelLookHover(p);
}
switch (ev) {
.key, .mouse => {
for (p.panes) |slot| {
if (slot) |pane| Messages.dismissMessage(p, pane);
}
v.clip_pending = null;
},
.tick => {
Stream.step(p);
Messages.advanceMessages(p);
for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| f.tables.step(pane.gpa, f);
for (0..p.panes.len) |id| exec.flushReplEnter(p, id, false);
},
else => {},
}
if (p.fs.listeners != 0) p.fs.origin = switch (ev) {
.key => 'K',
.mouse => 'M',
else => p.fs.origin,
};
switch (ev) {
.resize => |sz| {
if (sz.row_metrics) |metrics| v.row_metrics = metrics;
v.screen_w = sz.cols;
v.screen_h = sz.rows;
v.cell_pixels.w = @max(1, sz.cell_pixels.w);
v.cell_pixels.h = @max(1, sz.cell_pixels.h);
layout.compute(p);
p.resize_count += 1;
},
.output => |o| {
const pane = p.panes[o.pane] orelse return;
pane.shell_spoke = true;
ctlfs.events.notePtyOutput(p, o.pane, o.bytes);
pardes.panes.terminal.feedOutput(p, pane, o.bytes);
ctlfs.pty.noteMarks(p, o.pane, pane);
exec.flushReplEnter(p, o.pane, true);
},
.exited => |e| if (p.panes[e.pane]) |pane| {
if (pane.command == null)
ctlfs.pty.shellExited(p, pane, e.status)
else if (!pane.command_done)
exec.commandDone(p, e.pane, e.status);
},
.eof => |e| if (p.panes[e.pane]) |pane| if (pane.command != null) {
// Output is over; the command is over when its child exits.
pane.command_pty = false;
} else p.removePane(e.pane, null) catch |err| {
pane.body.mode = .normal;
p.reportError(e.pane, "terminal exited; Del retries close", err);
},
.lsp_resp => |r| @import("lsp/Ask.zig").lspResponse(p, r.id, r.rows),
.pipe_resp => |r| Pipe.pipeResponse(p, r.id, r.success, r.outputs, r.failure),
.search => |b| Stream.receive(p, &b),
.file_changed => |fc| _ = p.applyWatchedFileChanged(fc.pane, fc.bytes),
.key => |key| {
p.can_ask = true;
defer p.can_ask = false;
p.typedInto();
@import("keys.zig").handleKey(p, key);
},
.mouse => |m| mouse.handleMouse(p, m),
.paste => |bytes| {
p.typedInto();
edit.applyPaste(p, bytes);
},
.command => |line| _ = p.executeBuiltinLine(v.active, line),
.focus => |focused| {
v.window_focused = focused;
if (focused) if (p.host.vtable.newer_build) |f| if (f(p.host.ctx)) p.setMessage(v.active, newer_build_words);
},
.handed => |h| p.handover.finish(p, h.seq, h.to, h.failure),
.addon => |a| pardes.Addon.landed(p, a.op, a.pane, a.kind.*),
.job => |j| pardes.Kind.jobDone(p, j.pane, j.serial, j.token, j.gen, j.bytes),
.frontend => |f| {
v.frontend = f;
},
.pointer_leave => {
mouse.kindLeave(p);
v.pointer_inside = false;
v.pointer_body_hit = null;
v.pointer_tag_hit = null;
},
.tick => {
mouse.edgeScroll(p);
look.advanceLookHover(p);
},
}
// Each kind's pane whose time has come steps, and its jobs' answers land.
pardes.Kind.step(p);
// Each pane's places find a frame's more on a tick, and on any other
// step the ones an edit or a scroll left unfound in the view.
for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick);
// Each live query pane's rows, made from what changed this step.
pardes.panes.Query.produceAll(p, ev == .tick, ev == .key);
_ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept });
p.sync();
p.fsReport();
ctlfs.events.announce(p);
}
fn fsReport(p: *Pardes) void {
if (p.fs.listeners == 0) return;
for (p.panes, 0..) |slot, id| {
const pane = slot orelse continue;
if (pane.fs.readers == 0) continue;
const tag = tagline.tagText(p, p.scratch.allocator(), pane) catch continue;
const snap = &pane.fs.tag_snap;
if (std.mem.eql(u8, snap.items, tag)) continue;
if (snap.capacity != 0 or snap.items.len != 0)
ctlfs.events.noteReplace(p, id, true, snap.items, tag);
snap.clearRetainingCapacity();
snap.appendSlice(p.gpa, tag) catch {};
}
}
/// Where pardes started: the directory of what runs from a header.
pub fn sessionDir(p: *Pardes) []const u8 {
if (p.session_dir_len) |n| return p.session_dir[0..n];
// The directory the session that recorded was started in.
const dir = tape.value(.cwd, processDir, .{&p.session_dir}) orelse return "/";
std.mem.copyForwards(u8, &p.session_dir, dir);
p.session_dir_len = @intCast(dir.len);
return p.session_dir[0..dir.len];
}
fn processDir(buf: *[limits.host_path_cap]u8) ?[]const u8 {
if (std.c.getcwd(buf, buf.len) == null) return null;
return buf[0 .. std.mem.indexOfScalar(u8, buf, 0) orelse return null];
}
/// The directory a word run from pane `id`'s text or tag runs in, or,
/// from a header, the session's.
pub fn execDir(p: *Pardes, id: usize) []const u8 {
if (p.exec_header) return p.sessionDir();
return paneDir(p.panes[id] orelse return p.sessionDir());
}
pub const SavePath = Effect.Buf(effect_path_cap);
/// What was said of a failure just now on pane `id` is also the waiting
/// 9P write's (9p_io, `fs.late_failure`).
pub fn noteLateFailure(p: *Pardes, id: usize) void {
const taped = tape.enter(p, .{ .note_late_failure = id });
defer tape.leave(p, taped);
// Said by reportFailure just now: its words fitted whole, the
// reason kept; else what the message row has.
const said = if (p.fs.said_at == p.fs.failures and p.fs.said_len > 0)
p.fs.said[0..p.fs.said_len]
else if (p.panes[id]) |pane| pane.msg[0..pane.msg_len] else return;
const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len);
@memcpy(p.fs.late_failure[0..kept.len], kept);
p.fs.late_failure_len = @intCast(kept.len);
}
/// The frontend drew a frame: a pointer resting on it follows what is
/// under it now, a drag's moving end and a look-hover's word.
pub fn presented(p: *Pardes) void {
const v = p.view();
const taped = tape.enter(p, .presented);
defer tape.leave(p, taped);
if (v.pointer_inside and v.drag != .none) {
v.hover_col = v.pointer_raw_col;
v.hover_row = v.pointer_raw_row;
mouse.dragUpdate(p, v.pointer_raw_col, v.pointer_raw_row, v.pointer_body_hit);
}
look.refreshLookHoverFromRaw(p);
}
/// The window's answer to a WindowOpacity: done, or `failure` says why
/// not, `applied` the opacity it keeps.
pub fn windowOpacityDone(p: *Pardes, applied: u8, failure: ?[]const u8) void {
const taped = tape.enter(p, .{ .window_opacity_done = .{ .applied = applied, .failure = failure } });
defer tape.leave(p, taped);
p.settings.window_opacity_pending = false;
const reason = failure orelse return;
// Do not claim a value the compositor refused; an explicit retry of
// the same command will arm a new request.
p.settings.window_opacity = applied;
var buf: [256]u8 = undefined;
p.setMessage(p.view().active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch "WindowOpacity: compositor rejected the request");
}
/// Recompute geometry, push grid-size changes to each emulator and pty,
/// fire deferred greetings.
pub fn sync(p: *Pardes) void {
const v = p.view();
while (p.unplaced.findFirstSet()) |id| {
p.unplaced.unset(id);
// Refused, it was never there. Its serial is not handed out
// again: one logged or answered names this pane for good. Its
// rows, if it had any, go where a closed pane's go; no other
// pane moves (a pane dragged short keeps its rows).
if (p.panes[id] != null) p.removePane(id, null) catch {};
}
// A file opened or closed this step: the kept list follows.
p.saveRecent();
tagline.flattenHeaders(p);
if (p.headerColumn() != null and layout.columnBarHeight(p) == 0) {
tagline.exitHeader(p);
}
pardes.panes.reapPanes(p);
if (Views.several(p)) Views.show(p);
layout.compute(p);
Jump.trackJump(p);
for (&p.panes, 0..) |*slot, id| {
const pane = slot.* orelse continue;
// The keyboard is on one pane, or on a header: a tag it has left
// hands it back to its body, and a name drafted there is dropped.
if (id != v.active or v.header != null) {
pane.focus = .body;
if (pane.prompt == .name and pane.prompt_view == p.live) pane.closePrompt();
}
// A sweep over the tag is the tag's while it has the keyboard.
const swept = pane.sel[sel_slot];
if (pane.focus == .body and swept.state == .done and @min(swept.r0, swept.r1) < pane.tag_rows) {
pane.clearPointerSelection(sel_slot);
pane.sel[sel_slot].state = .none;
}
// What the terminal answers its program (a cursor report, its
// attributes) goes as typed bytes go: behind whatever is still
// queued for its pty, never ahead of it nor dropped.
if (pane.terminal) |state| {
p.emitWrite(id, state.reply[0..state.reply_len]);
state.reply_len = 0;
}
const r = v.rects[id];
// The session's part of the pane's view geometry (File.geometry),
// and its context declarations.
if (pane.file) |*f| pardes.panes.File.refreshContext(p, pane, f);
pane.view = .{ .wrap = p.settings.wrap, .body_h = v.row_metrics.body_h, .tagline_h = v.row_metrics.tagline_h, .rect_h = r.h };
// The tag takes a row per line, leaving the body one row if it
// had any; a folded pane shows its first line only. Its prefix
// is made once, on the stack: this runs on every event, and not
// every event may take from the scratch arena.
var wrap_room: [32 * 1024]u8 = undefined;
var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room);
const wa = wrap_fba.allocator();
const prefix: ?[]const u8 = tagline.prefixIn(p, wa, pane) catch null;
const lead = if (prefix) |made| made.len else pane.tag_lead;
if (lead != pane.tag_lead) {
const t = &pane.tag;
const old: i32 = @intCast(pane.tag_lead);
const new: i32 = @intCast(lead);
if (t.cur_row == 0 and t.cur_col >= old) t.cur_col += new - old;
if (t.vsel.row == 0 and t.vsel.col >= old) t.vsel.col += new - old;
for (t.sels[0..t.nsel]) |*sel| {
if (sel.row == 0 and sel.col >= old) sel.col += new - old;
if (sel.arow == 0 and sel.acol >= old) sel.acol += new - old;
}
pane.tag_lead = lead;
}
// A row per shown row: the tag's lines wrapped at its width.
var lines = std.mem.count(u8, tagline.curTail(pane), "\n") + 1;
var wanted = lines;
var caret_row: usize = @intCast(@max(0, pane.tag.cur_row));
if (prefix) |made| wrap: {
const whole = std.mem.concat(wa, u8, &.{ made, tagline.curTail(pane) }) catch break :wrap;
const shown = tagline.wrapTag(wa, whole, tagline.tagWidth(p, id)) catch break :wrap;
lines = shown.rows();
// Collapsed, one row, as acme's Tagup sets taglines to 1
// (plan9port text.c:786).
wanted = if (pane.tag_expanded) lines else 1;
const cur = modal.offsetAt(whole, .{ .row = caret_row, .col = @intCast(@max(0, pane.tag.cur_col)) });
caret_row = std.mem.count(u8, shown.text[0..@min(shown.fromReal(cur), shown.text.len)], "\n");
}
if (!pane.tag_expanded) wanted = 1;
pane.tag_rows = @intCast(@min(wanted, MAX_TAG_ROWS, @max(BOX_H, r.h -| 1)));
if (pane.collapsed) pane.tag_rows = BOX_H;
if (pane.focus == .tag and pane.prompt != .name) {
const cur: usize = caret_row;
var top: usize = pane.tag_top;
if (cur < top) top = cur;
if (cur >= top + pane.tag_rows) top = cur + 1 - pane.tag_rows;
pane.tag_top = @intCast(@min(top, lines - pane.tag_rows));
} else pane.tag_top = 0;
const cols = @max(1, r.w -| config.GUTTER);
// The tag steals the top rows. The pty is what the pane shows
// (layout keeps a terminal two body rows where the window has
// them): a taller pty would put its cursor below the pane.
const rows = @max(1, r.h -| pane.tag_rows);
// A terminal's pty follows its pane down to a row, whatever the
// resize; only a folded one keeps the size it had, and one not
// placed yet the grid it was made with.
if ((cols != pane.cols or rows != pane.rows) and (r.h > pane.tag_rows or (pane.isTerminal() and !pane.collapsed and r.h > 0)) and
(!pane.isTerminal() or p.sizes(pane)))
{
// doc panes have no pty/emulator grid to reflow; just record
// the size so bodyText renders the right number of rows
if (pane.isTerminal()) {
pardes.panes.terminal.resizeGrid(pane, cols, rows);
p.shell_rows.markStale(pane); // reflow moved every row
p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } });
pane.fs.winsize = null;
}
pane.cols = cols;
pane.rows = rows;
if (pane.file) |*file| file.syntax_dirty = true;
}
pane.pan = pardes.panes.terminal.panFor(p, pane, r);
// A directory pane's entries follow its width, as acme's
// columns do (Dir.fit).
if (pane.file) |file| if (file.listing != null and r.h > pane.tag_rows) pardes.panes.Dir.fit(p, pane, pane.cols);
pardes.panes.terminal.releasePendingCommandIfReady(p, id, pane);
// Which bands a pane shows is the step's, as its geometry is:
// what is drawn under them, and where a click lands, read it.
Messages.collectNotices(p, pane, r, id);
// The greeting `ls` of a new terminal in a directory is typed at
// its shell's FIRST prompt, or never: typed later it would land
// in whatever runs then, or in the middle of a line someone
// typed (panes.terminal.greeting).
if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (tape.value(.prompt, pardes.panes.terminal.greeting, .{pane})) {
.wait => {},
.never => pane.greet = false,
.now => {
p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = pane.cols, .rows = pane.rows } });
p.emitWrite(id, "ls\r");
pane.greet = false;
},
};
}
// A header's caret kept in its view, as a pane's is: the step's, not
// the frame's (paintHeaders draws what this leaves).
tagline.revealHeader(p);
}
/// The view typing goes into is the one its terminal is sized for
/// (`sizes`).
fn typedInto(p: *Pardes) void {
if (p.panes[p.view().active]) |pane| pane.sized_by = p.live;
}
/// Whether the live view sizes terminal `pane`: a terminal shown at two
/// sizes takes the size of the view that typed into it last, and any
/// view's once that one is gone. The others show it at that size, a
/// shorter one passed down to its cursor (`Pane.pan`, terminal.panFor).
// ponytail: a panned view's pointer reports to a terminal's program and
// its kitty images are placed as the unpanned rows are.
fn sizes(p: *Pardes, pane: *Pane) bool {
if (pane.sized_by == p.live) return true;
if (Views.isOpen(p, pane.sized_by)) return false;
pane.sized_by = p.live;
return true;
}
pub fn theme(p: *const Pardes) *const Theme {
if (p.custom_theme) |*custom| return custom;
return &themes[p.settings.theme];
}
/// The colours of the chrome: the theme's, set as it changes.
pub fn chromeTheme(p: *const Pardes) *const ChromeTheme {
return &p.chrome;
}
/// The theme's own chrome, not a fade's (`theme()`'s, worked out once
/// per theme: its contrast searches take pow calls, too many for a
/// grapheme or a row).
pub fn bodyChrome(p: *Pardes) *const ChromeTheme {
const th = p.theme();
if (p.body_chrome) |*cached| if (std.meta.eql(cached.theme, th.*)) return &cached.chrome;
p.body_chrome = .{ .theme = th.*, .chrome = ChromeTheme.fromTheme(th) };
return &p.body_chrome.?.chrome;
}
/// When the core next needs a frame, on the `stepped_ns` timeline: a
/// frame from now while work goes on (places to find, a picture
/// decoding, a PDF page on a lane), the end of the wait while something
/// only waits (a message lingering, a look-hover delay), null when
/// nothing is due. Every deadline the core owns is in this one list,
/// which is what lets every shell sleep exactly as long as nothing
/// changes; what moves on the screen is the frontends' own.
pub fn nextWake(p: *const Pardes) ?u64 {
const next = p.clock.stepped_ns + frame_ns;
// Held 9P writes go in when they pause: wake for it, never before
// the next frame (writes served before the shell's clock was first
// seen are stamped 0, which `advance` would count back from).
if (p.fs.batch.bytes.items.len > 0) return @max(next, p.fs.batch.last_ns + ctlfs.pane.batch_pause_ns);
// Places still to find resume on the next frame; a picture being
// decoded is looked for.
for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next;
const kinds = pardes.Kind.wake(p);
if (kinds) |due| if (due <= next) return next;
// A markdown text's tables still being read from the top (Tables.zig).
for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.tables.busy()) return next;
if (pardes.panes.Query.busy(p)) return next;
// A typed Grep waiting out its pause.
const streaming = p.stream.wake(next);
if (streaming) |due| if (due <= next) return next;
var frames: ?u64 = null;
if (streaming) |due| frames = @max(1, (due -| p.clock.stepped_ns + frame_ns - 1) / frame_ns);
if (p.look_hover_wait) |waiting| {
const delay = config.look_preview_delay_frames;
frames = @max(1, delay -| waiting.frames);
}
for (p.panes) |slot| if (slot) |pane| {
const wait = Messages.messageWake(p, pane) orelse continue;
frames = if (frames) |soonest| @min(soonest, wait) else wait;
};
// Del's question goes up at the end of its delay: a frame then, and
// none after (stepped time has reached it).
for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.clock.stepped_ns) {
const wait = @max(1, (pane.question_due_ns - p.clock.stepped_ns + frame_ns - 1) / frame_ns);
frames = if (frames) |soonest| @min(soonest, wait) else wait;
};
// A paste's Enter waiting on its REPL goes at the end of its wait,
// a time on the clock: the frames from `stepped_ns` that reach it.
for (p.panes) |slot| if (slot) |pane| if (pane.repl_enter > 0) {
const wait = @max(1, (pane.repl_enter_due_ns -| p.clock.stepped_ns + frame_ns - 1) / frame_ns);
frames = if (frames) |soonest| @min(soonest, wait) else wait;
};
// A terminal's kitty animation, at its next frame. Only a time still
// ahead counts: a pane not drawn keeps the last one it was given,
// and a past one would wake every frame for nothing.
for (p.panes) |slot| if (slot) |pane| if (pardes.panes.terminal.animationDueMs(pane)) |due_ms| {
const due = due_ms *| std.time.ns_per_ms;
if (due > p.clock.stepped_ns) {
const wait = @max(1, (due - p.clock.stepped_ns + frame_ns - 1) / frame_ns);
frames = if (frames) |soonest| @min(soonest, wait) else wait;
}
};
// A kind's next tick (Kind.zig).
if (kinds) |due| {
const wait = @max(1, (due -| p.clock.stepped_ns + frame_ns - 1) / frame_ns);
frames = if (frames) |soonest| @min(soonest, wait) else wait;
}
return if (frames) |n| p.clock.stepped_ns + n * frame_ns else null;
}
/// For shells that only need a yes or no: macOS, which keeps its own
/// frame bank.
pub fn animationActive(p: *const Pardes) bool {
return p.nextWake() != null;
}
/// Bring core time up to `now_ns`, the shell's monotonic clock: one
/// `.tick` for every whole frame that has passed since it last stood
/// still, so a timing lasts as long on a 144 Hz display, over ssh or
/// after a slow frame as it does anywhere. A wait (a message lingering,
/// the look-hover delay) is jumped to its end in one step and drawn
/// once. Idle, time is not banked: the next wait starts from now.
pub fn advance(p: *Pardes, now_ns: u64) void {
const taped = tape.enter(p, .{ .advance = now_ns });
defer tape.leave(p, taped);
// The first time a shell's clock is seen, core time starts there.
const started = p.clock.started;
p.clock.started = true;
p.clock.now_ns = now_ns;
if (!started) p.clock.stepped_ns = now_ns;
const frame = frame_ns;
var moving: u32 = 0;
// The session's ticks are the recording session's: a picture still
// decoding or a fade still moving asks for frames the way a message
// waiting to go does, and a replica that draws nothing has none.
while (tape.value(.wake, nextWake, .{p})) |due| {
if (due > now_ns) break;
// Only waiting until `due`: its counters move there at once.
const held = (due - p.clock.stepped_ns) / frame;
if (held > 1) {
Messages.holdMessages(p, held - 1);
if (p.look_hover_wait) |*waiting| waiting.frames +|= @intCast(@min(held - 1, std.math.maxInt(u16)));
p.clock.stepped_ns += (held - 1) * frame;
}
// Back from a stall, the moving frames it missed are not all
// run at once: the rest are stepped from now, at their pace.
if (moving == max_catch_up_frames) {
p.clock.stepped_ns = now_ns;
return;
}
moving += 1;
p.clock.stepped_ns += frame;
p.update(.tick);
// A stepped frame is a frame to draw. (A `.tick` does not ask
// for one itself: the last frame of a fade used never to be
// drawn.)
p.needs_frame = true;
} else {
p.clock.stepped_ns = now_ns;
return;
}
// A 60 Hz display frame is 16.67 ms and ours 16: without this, every
// 24th display frame would take two steps, a hitch in every fade.
// An overshoot this small is let go; a larger one (144 Hz lands 4.8
// ms past) is kept, so the average rate stays right.
if (moving > 0 and now_ns - p.clock.stepped_ns < vsync_slack_ns) p.clock.stepped_ns = now_ns;
}
pub const vsync_slack_ns = 1500 * std.time.ns_per_us;
pub const max_catch_up_frames = 240;
pub fn noteHaptic(p: *Pardes, pulse: Haptic) void {
if (comptime platform != .macos) return;
if (p.haptic == .look) return;
p.haptic = pulse;
}
/// Take the armed pulse and disarm. The shell calls this once per pump,
/// after the tick that may have set it.
pub fn takeHaptic(p: *Pardes) Haptic {
if (comptime platform != .macos) return .none;
defer p.haptic = .none;
return p.haptic;
}
pub const render = draw.render;
pub fn appendPlacement(p: *Pardes, place: Placement) bool {
p.surface.placements.append(p.gpa, place) catch return false;
return true;
}
pub const PendingWrite = struct { bytes: []u8, off: usize = 0 };
/// The session layouts `init` can put on screen. One name each, so choosing
/// between them reads as a choice instead of a chain of ifs over four options.
/// A column (acme's Column, cols.c): its panes top to bottom, its share of
/// the width and its serial. Its tag is the session's `col_tags`, and its
/// place on screen (`col_x`, `col_w`) is worked out each sync, as a pane's
/// rect is.
pub const Column = struct {
// Zeroed, not undefined: a digest takes the whole of it, a release
// build's heap leaves its unused slots whatever was there before, and
// two replicas must agree on them (src/replica.zig).
panes: [MAX_PANES]usize = @splat(0),
n: usize = 0,
weight: u64 = column_weight_unit,
serial: u32 = 0,
};
/// Core time. `now_ns` is the shell's monotonic clock as `advance` was
/// last given it; `stepped_ns` is how far its timings have been stepped
/// along it, in whole frames of `frame_ns`. Idle, the two are the same
/// instant.
pub const Header = union(enum) { workspace, column: usize };
/// The column whose tag has the keyboard, null for none or the workspace's.
pub fn headerColumn(p: *const Pardes) ?usize {
const h = p.view().header orelse return null;
return if (h == .column) h.column else null;
}
pub const Clock = struct {
now_ns: u64 = 0,
stepped_ns: u64 = 0,
started: bool = false,
};
pub const Boot = enum {
/// the document named on the command line, or the pane explaining why not
document,
/// a Look that found nothing: reported, not opened
missing,
/// `pardes -`: stdin's text in a +Pager pane, as `vim -` shows it
stdin,
/// the bare tty startup: one shell in raw tty mode, with an empty text
/// pane under it so the editor half is there before you want it
tty,
/// that raw shell by itself, which is all a core booted for a test wants
tty_shell,
/// acme's boot: two columns, the left one split in two
classic,
/// one greeted shell
shell,
pub fn of(opts: Options) Boot {
if (opts.boot) |named| return named;
if (opts.file != null) return .document;
if (opts.missing != null) return .missing;
if (opts.stdin_text != null) return .stdin;
if (opts.tty_only) return .tty_shell;
// ponytail: 1 and 3 are the only shell counts anyone asked for
return if (opts.shells >= 3) .classic else .shell;
}
};
pub const Options = struct {
tty_only: bool = false,
/// The first view's frontend is a window (`Pardes.frontend`), as a
/// window's build says: an option, taped with the rest, so that a
/// window's build replaying a terminal's session starts as it did.
windowed: bool = platform == .gui,
/// The layout to boot, when a host means one outright rather than leaving
/// it to be read off the options below. `--tty` names `.tty`; a core
/// booted for a test names nothing and gets `.tty_shell`.
boot: ?Boot = null,
/// initial shell panes: 1 (default) or 3 for the classic two-column boot.
/// A `file` outranks this — see there.
shells: u8 = 1,
file: ?[]const u8 = null,
file_line: usize = 0,
missing: ?struct { word: []const u8, dir: []const u8 } = null,
/// `pardes -`: stdin as it came, for a +Pager pane at boot (pager.zig
/// parses it).
stdin_text: ?[]const u8 = null,
tty_toggle: u21 = config.tty_toggle_default,
/// load a dump of another instance instead of spawning shells (acme -l)
load_path: ?[]const u8 = null,
/// `--geometry=WxH[+X+Y]`: a pixel shell's window size, and where it
/// goes when the display lets it say (a pane carried out of another
/// window opens one as big as that, Handover.zig).
geometry: ?[]const u8 = null,
nested: bool = false,
startup_config: ?[]const u8 = null,
ninep_name: []const u8 = "",
ninep_tcp: ?[]const u8 = null,
mounts: []const filesystem.Mount = &.{},
config_dir: ?[]const u8 = null,
/// Where what outlives the session is kept (Db.zig): the user's state
/// file, set by a host that has one; none, Recent lasts as long as the
/// session; memory, the test host's.
state: Db.Kind = .off,
/// Where Recent's files were before the state file (0.24's `recent`, the
/// `store` before it): a state file that holds no Recent yet reads them
/// once (Db.zig). Set by a host that had them.
recent_import: ?[]const u8 = null,
startup_config_path: ?[]const u8 = null,
image_allocator: ?std.mem.Allocator = null,
/// What the host's scan of the addon directories found (Addon.scan).
addons: []const pardes.Kind.Loaded = &.{},
tree_sitter_allocator: ?std.mem.Allocator = null,
/// Where each frame's Surface text is built. Hosts pass a purpose-built
/// stack-fallback arena; null means the general allocator.
frame_allocator: ?std.mem.Allocator = null,
cols: u16 = 80,
rows: u16 = 24,
};
pub const Haptic = enum { none, exec, look };
/// Zero-sized off macOS: no other shell reads
/// the field, so no other shell carries it.
const HapticSlot = if (platform == .macos) Haptic else void;
pub const RetiredPanes = struct {
current: [2 * MAX_PANES]?*Pane = @splat(null),
previous: [2 * MAX_PANES]?*Pane = @splat(null),
pub fn retire(a: *RetiredPanes, pane: *Pane) void {
for (&a.current) |*slot| if (slot.* == null) {
slot.* = pane;
return;
};
// One update runs one builtin, and the widest drop is a whole column;
// 2*MAX_PANES cannot fill in a single frame.
unreachable;
}
};
const FakeTtyQuery = struct {
taken: [MAX_PANES]bool = @splat(false),
asked: usize = 0,
const vtable: Host.VTable = .{ .tty_taken = answer };
fn install(f: *FakeTtyQuery, p: *Pardes) void {
p.host = .{ .ctx = f, .vtable = &vtable };
}
fn answer(ctx: ?*anyopaque, pane: u8) bool {
const f: *FakeTtyQuery = @ptrCast(@alignCast(ctx.?));
f.asked += 1;
return f.taken[pane];
}
};
fn bootAndTearDown(gpa: std.mem.Allocator) !void {
const p = try Pardes.init(gpa, .{ .cols = 56, .rows = 14, .tty_only = true, .frame_allocator = gpa, .image_allocator = gpa, .tree_sitter_allocator = gpa });
p.deinit();
}
test "startup config runs builtin lines in order and isolates bad lines" {
const p = try Pardes.init(std.testing.allocator, .{
.startup_config =
\\Theme dark
\\DefinitelyNotABuiltin
\\Exit trailing-garbage
\\Theme no-such-theme
\\Theme acme
,
});
defer p.deinit();
try std.testing.expectEqualStrings("acme", p.theme().name);
// The theme lands without a tween (the chrome is the theme's at once);
// the bad lines are said, so a notice may be up.
try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*);
try std.testing.expect(!p.quit);
for (0..p.effects_len) |i| switch (p.effects[(p.effects_head + i) % p.effects.len]) {
.write => |w| {
try std.testing.expect(std.mem.indexOf(u8, w.bytes.slice(), "DefinitelyNotABuiltin") == null);
try std.testing.expect(std.mem.indexOf(u8, w.bytes.slice(), "Exit") == null);
},
else => {},
};
}
test "topbar hover highlights exactly the executable word" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
_ = try p.render(frame.allocator());
p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 1, .row = 0 } });
_ = frame.reset(.retain_capacity);
const hovered = try p.render(frame.allocator());
for (0.."Newcol".len) |col| {
const cell = hovered.at(TAG_TEXT_INSET + @as(u16, @intCast(col)), 0);
try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, cell.style.bg);
try std.testing.expectEqual(Color{ .rgb = p.theme().sel_fg }, cell.style.fg);
}
try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, hovered.at(TAG_TEXT_INSET + 6, 0).style.bg);
p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 6, .row = 0 } });
_ = frame.reset(.retain_capacity);
const whitespace = try p.render(frame.allocator());
try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, whitespace.at(TAG_TEXT_INSET + 1, 0).style.bg);
p.update(.pointer_leave);
_ = frame.reset(.retain_capacity);
const left = try p.render(frame.allocator());
try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, left.at(TAG_TEXT_INSET + 1, 0).style.bg);
}
test "pane-tag Exec prefers Term and argument builtins before shell fallback" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {} // initial shell spawn/geometry
p.acknowledgeShell(0, "/bin/sh", false);
// The Term word names the shell the host ran, and opens another of it.
const pane = p.panes[0].?;
try std.testing.expectEqualStrings(" Term+sh" ++ tagline.terminal_pane_tail[" Term".len..], tagline.curTail(pane));
const tag_x = p.view().rects[0].x + TAG_TEXT_INSET;
const tag_y = p.view().rects[0].y;
const rendered = try tagline.tagText(p, p.scratch.allocator(), pane);
const new_x = tag_x + @as(u16, @intCast(std.mem.indexOf(u8, rendered, "Term").?)) + 1;
var panes_before: usize = 0;
for (p.panes) |s| if (s != null) {
panes_before += 1;
};
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = new_x, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = new_x, .row = tag_y } });
while (p.nextEffect()) |effect| switch (effect) {
.write => return error.NewFellThroughToPty,
else => {},
};
var panes_after: usize = 0;
for (p.panes) |s| if (s != null) {
panes_after += 1;
};
try std.testing.expectEqual(panes_before + 1, panes_after);
try std.testing.expect(p.panes[p.view().active].?.isTerminal());
try std.testing.expectEqualStrings("sh", p.panes[p.view().active].?.shell.?);
// Argument-taking builtins use the same gesture path: a tag sweep is the
// complete command line, and Theme consumes its tail without a PTY write.
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = try p.gpa.dupe(u8, " Theme dark");
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .drag, .col = tag_x + 10, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 10, .row = tag_y } });
try std.testing.expectEqualStrings("dark", p.theme().name);
while (p.nextEffect()) |effect| switch (effect) {
.write => return error.ArgumentBuiltinFellThroughToPty,
else => {},
};
// Fixed-name builtins remain exact: a tail does not turn New or Exit into
// a match (especially important for the destructive one).
try std.testing.expect(!p.executeBuiltinLine(0, "New argument"));
try std.testing.expect(!p.executeBuiltinLine(0, "Exit trailing-garbage"));
try std.testing.expect(!p.quit);
// A word absent from the builtin vocabulary takes the fallback, including
// the terminating carriage return expected by the shell prompt.
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = try p.gpa.dupe(u8, " DefinitelyNotABuiltin");
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 1, .row = tag_y } });
var sent: [256]u8 = undefined;
var sent_len: usize = 0;
while (p.nextEffect()) |effect| switch (effect) {
.write => |w| {
try std.testing.expectEqual(@as(u8, 0), w.pane);
try std.testing.expect(w.bytes.slice().len <= sent.len - sent_len);
@memcpy(sent[sent_len..][0..w.bytes.slice().len], w.bytes.slice());
sent_len += w.bytes.slice().len;
},
else => {},
};
try std.testing.expectEqualStrings("DefinitelyNotABuiltin\r", sent[0..sent_len]);
}
test "LocationsConfig command reports partial updates and survives restore" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
_ = try p.setTestFile("source\n");
try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:5 tscontext:on"));
try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig tslocations:off"));
const expected: locations.Config = .{ .context = 5, .tscontext = true, .tslocations = false };
try std.testing.expectEqual(expected, p.locations_config);
try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:2 unknown:on"));
try std.testing.expectEqual(expected, p.locations_config);
// Setting it is silent; asking bare is what opens the window.
try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig"));
var reports: usize = 0;
for (p.panes) |slot| {
const pane = slot orelse continue;
const file = pane.file orelse continue;
const out = file.output orelse continue;
if (!std.meta.eql(out.from, pardes.panes.Output.Origin{ .cmd = .LocationsConfig })) continue;
reports += 1;
try std.testing.expectEqualStrings("LocationsConfig context:5 tscontext:on tslocations:off layout:stacked\n", file.content);
}
try std.testing.expectEqual(@as(usize, 1), reports);
try dump.dumpState(p);
const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?);
defer restored.deinit();
try std.testing.expectEqual(expected, restored.locations_config);
}
test "TreeContext rows in the tag style keep the message rows" {
if (comptime !syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer p.deinit();
const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n");
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, "/test.zig");
if (!pardes.panes.File.supportsContext(pane)) return error.SkipZigTest;
p.update(.{ .resize = .{ .cols = 60, .rows = 16, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } });
pane.file.?.tree_context = true;
pane.file.?.scroll = 8;
pane.msg_len = 0;
p.sync();
_ = try p.render(p.scratch.allocator());
const full_height = p.surface.body_layers[0].viewport.h;
try std.testing.expect(p.surface.body_layers[0].rows > full_height);
try std.testing.expectEqual(FontRole.tagline, p.surface.body_layers[0].cells[0].style.font_role);
pane.msg[0] = '!';
pane.msg_len = 1;
p.sync();
_ = try p.render(p.scratch.allocator());
// An overlay takes nothing: the message is a chip OVER the body's first
// row, so the viewport keeps every row it had.
try std.testing.expectEqual(full_height, p.surface.body_layers[0].viewport.h);
const r = p.view().rects[0];
const band = for (p.surface.tagLayers()) |*layer| {
if (layer.rows != 0 and layer.kind == .notice) break layer;
} else return error.NoNoticeBand;
try std.testing.expectEqual(p.bodyTop(pane, r), band.viewport.y);
try std.testing.expectEqual(p.surface.body_layers[0].viewport.y, band.viewport.y);
// Sized to its message, flush with the pane's right edge, and the text
// right aligned a cell short of that edge.
try std.testing.expectEqual(r.x + r.w, band.viewport.x + band.viewport.w);
try std.testing.expect(band.viewport.w < r.w - config.GUTTER);
try std.testing.expectEqualStrings("!", band.cells[layout.tagCapacity(p, band.viewport.w) - 2].grapheme());
pane.msg_len = 0;
p.view().prefix = .leader;
p.sync();
_ = try p.render(p.scratch.allocator());
try std.testing.expectEqual(full_height, p.surface.body_layers[0].viewport.h);
p.view().prefix = .none;
}
test "TreeContext command and custom tag survive a workspace round trip" {
if (comptime !syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("pub fn main() void {}\n");
try std.testing.expect(!pardes.panes.File.supportsContext(pane));
try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(pane));
const path = try p.gpa.dupe(u8, "/test.zig");
p.gpa.free(pane.file.?.path);
pane.file.?.path = path;
if (!pardes.panes.File.supportsContext(pane)) return error.SkipZigTest;
try std.testing.expectEqualStrings(if (lsp.speaks("/test.zig")) tagline.lsp_context_pane_tail else tagline.context_pane_tail, tagline.curTail(pane));
try std.testing.expect(!pane.file.?.tree_context);
try std.testing.expect(p.executeBuiltinLine(0, "TreeContext on"));
try std.testing.expect(pane.file.?.tree_context);
try std.testing.expect(p.executeBuiltinLine(0, "TreeContext off"));
try std.testing.expect(!pane.file.?.tree_context);
try std.testing.expect(p.executeBuiltinLine(0, "TreeContext"));
try std.testing.expect(pane.file.?.tree_context);
try std.testing.expect(p.executeBuiltinLine(0, "TreeContext invalid"));
try std.testing.expect(pane.file.?.tree_context);
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = try p.gpa.dupe(u8, " Save Keep Del");
try dump.dumpState(p);
const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?);
defer restored.deinit();
const saved = restored.panes[0].?;
try std.testing.expect(saved.file.?.tree_context);
try std.testing.expectEqualStrings(" Save Keep Del", tagline.curTail(saved));
}
test "Filter is ordered after Del and toggles only its terminal or +Pager pane" {
const testing = std.testing;
const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin;
const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin;
try testing.expectEqual(@backingInt(del) + 1, @backingInt(filter));
const p = try Pardes.init(testing.allocator, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const first = p.panes[0].?;
const palette_before = first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?;
try testing.expect(first.tty_filter);
try testing.expect(p.executeBuiltinLine(0, "Filter"));
try testing.expect(!first.tty_filter);
try testing.expect(palette_before.eql(first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?));
const second_id = p.freeSlot().?;
const second = try p.newShell(second_id, "");
try testing.expect(second.tty_filter);
try testing.expect(p.executeBuiltinLine(second_id, "Filter"));
try testing.expect(!second.tty_filter);
try testing.expect(!first.tty_filter);
const doc_id = p.freeSlot().?;
const doc = try pardes.Kind.open(p, doc_id, pardes.Kind.test_kind.of(p), "/tmp/filter-inert.ppm", "");
try testing.expect(!doc.tty_filter);
try testing.expect(p.executeBuiltinLine(doc_id, "Filter"));
try testing.expect(!doc.tty_filter);
try testing.expect(!first.tty_filter);
try testing.expect(p.executeBuiltinLine(0, "Filter"));
try testing.expect(first.tty_filter);
try testing.expect(!second.tty_filter);
// A +Pager opens filtered, with Filter on its tag and no line numbers;
// a second is a pane of its own.
const pager_id = try pardes.panes.Output.openPager(p, 0, "/tmp");
const pager_pane = p.panes[pager_id].?;
try testing.expect(pager_pane.tty_filter);
try testing.expectEqualStrings(tagline.pager_pane_tail, tagline.curTail(pager_pane));
try testing.expectEqual(@as(u16, 0), pardes.panes.File.gutterWidth(pager_pane));
try testing.expect(p.executeBuiltinLine(pager_id, "Filter"));
try testing.expect(!pager_pane.tty_filter);
try testing.expect(try pardes.panes.Output.openPager(p, 0, "/tmp") != pager_id);
}
test "compact tag commands stay beside their own prefix across layout changes" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {} // initial shell spawn/geometry
// A longer sibling never introduces invisible padding into this tag.
const below_id = p.freeSlot().?;
const below = try p.newShell(below_id, "");
const f = layout.findPane(p, p.view().active).?;
layout.insert(p, f.col, f.idx + 1, below_id);
layout.splitBelow(p, p.view().active, below);
p.setCwd(below_id, "/a/deep/dir/whose/name/eats/the/right/pad/the/end/of/its/own/tagline");
p.sync();
while (p.nextEffect()) |_| {}
const above = p.panes[0].?;
try std.testing.expectEqual(p.view().rects[0].x, p.view().rects[below_id].x);
const above_tag = try tagline.tagText(p, gpa, above);
defer gpa.free(above_tag);
const below_tag = try tagline.tagText(p, p.scratch.allocator(), below);
try std.testing.expect(below_tag.len > above_tag.len);
const tail = tagline.terminal_pane_tail;
try std.testing.expectEqualStrings(tail, above_tag[above_tag.len - tail.len ..]);
try std.testing.expectEqual(above.cwdSlice().len + tail.len, above_tag.len);
p.update(.{ .resize = .{ .cols = 88, .rows = 30 } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above));
p.update(.{ .resize = .{ .cols = 87, .rows = 30 } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above));
p.update(.{ .resize = .{ .cols = 100, .rows = 30 } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqualStrings(tail, tagline.curTail(below));
try below.appendTag(" lots and lots of typing out here");
try std.testing.expectEqual(above_tag.len, (try tagline.tagText(p, p.scratch.allocator(), above)).len);
p.update(.{ .resize = .{ .cols = 100, .rows = 2 } });
while (p.nextEffect()) |_| {}
try std.testing.expectEqual(@as(u16, 0), p.view().rects[below_id].h);
try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above));
}
test "Term spawns a raw shell in the caller's directory" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
p.setCwd(0, "/tmp/newtty-dir");
try std.testing.expect(p.executeBuiltinLine(0, "Term"));
const free = p.view().active;
try std.testing.expect(free != 0);
const nt = p.panes[free] orelse return error.NoNewPane;
try std.testing.expect(nt.isTerminal());
try std.testing.expect(nt.body.mode == .tty);
var found = false;
while (p.nextEffect()) |effect| switch (effect) {
.spawn => |s| if (@as(usize, s.pane) == free) {
try std.testing.expectEqualStrings("/tmp/newtty-dir", s.cwd.slice());
found = true;
},
else => {},
};
try std.testing.expect(found);
}
test "a terminal respawned into a closed pane's slot hangs the old shell up first" {
// Hosts keep a shell per slot: were the spawn first, the close would
// end the new shell and leave the old one running.
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
try std.testing.expect(p.executeBuiltinLine(0, "Term"));
const slot = p.view().active;
while (p.nextEffect()) |_| {}
try p.removePane(slot, null);
try std.testing.expect(p.executeBuiltinLine(0, "Term"));
try std.testing.expectEqual(slot, p.view().active);
var closed = false;
var spawned = false;
while (p.nextEffect()) |effect| switch (effect) {
.close_pty => |c| if (c.pane == slot) {
try std.testing.expect(!spawned);
closed = true;
},
.spawn => |s| if (s.pane == slot) {
spawned = true;
},
else => {},
};
try std.testing.expect(closed and spawned);
}
test "a frame no one watches is not drawn, and is drawn once someone does" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const Watch = struct {
var presents: usize = 0;
var seen = false;
const vtable: Host.VTable = .{ .present = present, .watched = watched };
fn present(_: ?*anyopaque, _: *const Surface) void {
presents += 1;
}
fn watched(_: ?*anyopaque) bool {
return seen;
}
};
Watch.presents = 0;
Watch.seen = false;
p.needs_frame = true;
try p.pump(.{ .vtable = &Watch.vtable });
try std.testing.expectEqual(@as(usize, 0), Watch.presents);
try std.testing.expect(p.needs_frame); // still owed
Watch.seen = true;
try p.pump(.{ .vtable = &Watch.vtable });
try std.testing.expectEqual(@as(usize, 1), Watch.presents);
}
test "an empty column shows its theme's empty_col under its tag: acme's white, else the border" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 20 });
defer p.deinit();
layout.newColumn(p, 0);
tagline.exitHeader(p);
inline for (.{ "acme", "dark" }) |name| {
try std.testing.expect(p.executeBuiltinLine(0, "Theme " ++ name));
p.sync();
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const s = try p.render(arena.allocator());
const cell = s.at(p.view().col_x[1] + 3, p.view().screen_h - 2);
const want = p.chromeTheme().empty_col;
try std.testing.expectEqual(want, cell.style.bg.rgb);
if (std.mem.eql(u8, name, "acme")) try std.testing.expectEqual([3]u8{ 0xff, 0xff, 0xff }, want) else try std.testing.expectEqual(p.chromeTheme().border, want);
}
}
test "unknown Exec from a document runs as a command pane in its directory, typed into no terminal" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{});
defer p.deinit();
while (p.nextEffect()) |_| {}
p.acknowledgeShell(0, "/bin/sh", false);
// A terminal free at a prompt in the same directory is not borrowed.
p.setCwd(0, "/tmp/pardes-image-dir");
const image_doc = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pardes-image-dir/pic.ppm", null);
try std.testing.expectEqualStrings("/tmp/pardes-image-dir", Pardes.paneDir(image_doc));
const dst = exec.execute(p, 1, "echo image-fallback") orelse return error.ExecFoundNowhereToRun;
try std.testing.expect(dst != 0 and dst != 1);
try std.testing.expectEqualStrings("echo image-fallback", p.panes[dst].?.command.?);
var spawned = false;
while (p.nextEffect()) |effect| switch (effect) {
.write => return error.TypedIntoATerminal,
.spawn => |sp| if (sp.pane == dst) {
try std.testing.expectEqualStrings("/tmp/pardes-image-dir", sp.cwd.slice());
spawned = true;
},
else => {},
};
try std.testing.expect(spawned);
}
test "Exec in a terminal whose tty is taken runs as a command pane instead of typing at the program" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{});
defer p.deinit();
while (p.nextEffect()) |_| {}
p.setCwd(0, "/tmp/pardes-taken");
// vim, a pager, an agent: the host answers that this pane's tty is no
// longer the prompt pardes forked
var host: FakeTtyQuery = .{};
host.install(p);
host.taken[0] = true;
const dst = exec.execute(p, 0, "echo taken-fallback") orelse return error.ExecFoundNowhereToRun;
// somewhere ELSE -- and still without moving focus, which is execute's
// contract and the whole difference between it and a look
try std.testing.expect(dst != 0);
try std.testing.expectEqual(@as(usize, 0), p.view().active);
try std.testing.expectEqualStrings("echo taken-fallback", p.panes[dst].?.command.?);
var spawned = false;
while (p.nextEffect()) |effect| switch (effect) {
.write => return error.WroteACommandLineIntoATerminal,
.spawn => |sp| if (sp.pane == dst) {
// ...in the directory the command was about, the taken pane's own
try std.testing.expectEqualStrings("/tmp/pardes-taken", sp.cwd.slice());
spawned = true;
},
else => {},
};
try std.testing.expect(spawned);
}
test "a command of several lines keeps its tag one row, and its echo does not staircase" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
_ = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pic.ppm", null);
const two = "def greet(name):\n return name\n\nprint(greet(\"x\"))\n";
const dst = exec.execute(p, 1, two) orelse return error.NoCommandPane;
while (p.nextEffect()) |_| {}
const pane = p.panes[dst].?;
const prefix = try tagline.tagPrefix(p, pane);
try std.testing.expect(std.mem.indexOfScalar(u8, prefix, '\n') == null);
try std.testing.expect(std.mem.indexOf(u8, prefix, "(def greet(name):...) running") != null);
// Rendered without a panic, however the tag wraps.
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
_ = try p.render(frame.allocator());
p.update(.{ .exited = .{ .pane = @intCast(dst), .status = 0 } });
_ = exec.execute(p, 1, two);
while (p.nextEffect()) |_| {}
_ = try p.render(frame.allocator());
const body = try pardes.panes.terminal.screenTextAlloc(pane, gpa);
defer gpa.free(body);
try std.testing.expect(std.mem.indexOf(u8, body, "% def greet(name):\n return name") != null);
}
test "a spawn is for the pane it was made for, not whatever took the slot since" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const Count = struct {
var spawns: usize = 0;
var command: [32]u8 = undefined;
var core: *Pardes = undefined;
const vtable: Host.VTable = .{ .spawn = spawn };
fn spawn(_: ?*anyopaque, pane: u8, _: []const u8) void {
spawns += 1;
const line = core.panes[pane].?.command.?;
@memcpy(command[0..line.len], line);
}
};
Count.core = p;
p.host = .{ .vtable = &Count.vtable };
// A command pane closed and its slot taken, in one step, before the
// effects run: only the second's spawn is performed.
const slot = p.freeSlot().?;
_ = try pardes.panes.newCommand(p, slot, "", "first");
try p.removePane(slot, null);
try std.testing.expectEqual(slot, p.freeSlot().?);
_ = try pardes.panes.newCommand(p, slot, "", "second");
while (p.nextEffect()) |effect| p.perform(effect);
try std.testing.expectEqual(@as(usize, 1), Count.spawns);
try std.testing.expectEqualStrings("second", Count.command[0.."second".len]);
}
test "a REPL bound for a language takes the exec made on a body in it; tags, Exec by name and command words still run" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const file = try p.setTestFile("print(1)\nls\n");
gpa.free(file.file.?.path);
file.file.?.path = try gpa.dupe(u8, "/x.py");
const Sent = struct {
var to: [MAX_PANES][128]u8 = undefined;
var len: [MAX_PANES]usize = @splat(0);
var spawned: bool = false;
fn drain(pp: *Pardes) void {
len = @splat(0);
spawned = false;
while (pp.nextEffect()) |effect| switch (effect) {
.write => |w| {
@memcpy(to[w.pane][len[w.pane]..][0..w.bytes.slice().len], w.bytes.slice());
len[w.pane] += w.bytes.slice().len;
},
.spawn => spawned = true,
else => {},
};
}
fn said(pane: usize) []const u8 {
return to[pane][0..len[pane]];
}
};
// The programs the REPLs run hold their terminals' ttys.
var host: FakeTtyQuery = .{};
host.install(p);
host.taken[1] = true;
host.taken[2] = true;
// Only a terminal is a REPL; a language's name is the syntax table's.
try std.testing.expect(p.executeBuiltinLine(0, "Repl python"));
try std.testing.expect(file.repl == null);
try std.testing.expect(p.executeBuiltinLine(1, "Repl pithon"));
try std.testing.expect(p.panes[1].?.repl == null);
try std.testing.expect(std.mem.indexOf(u8, p.panes[1].?.msg[0..p.panes[1].?.msg_len], "python") != null);
try std.testing.expect(p.executeBuiltinLine(1, "Repl python"));
// again, as a code fence may name it: no change
try std.testing.expect(p.executeBuiltinLine(1, "Repl PY"));
var idbuf: [48]u8 = undefined;
try std.testing.expectEqualStrings("python-a", exec.replId(&idbuf, p.panes[1].?));
try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, p.panes[1].?), " python-a"));
Sent.drain(p);
// A click on the file's body, a single word: typed into the REPL.
try std.testing.expectEqual(@as(?usize, 1), exec.executeFrom(p, 0, "ls", true));
Sent.drain(p);
try std.testing.expectEqualStrings("ls\r", Sent.said(1));
try std.testing.expect(!Sent.spawned);
try std.testing.expect(file.msg_sent);
try std.testing.expectEqualStrings("\u{2192} python-a", file.msg[0..file.msg_len]);
// A body's click written back to event is done as the click: sent. A
// line written to exec came back as F and runs as the command it was.
{
const th = @import("ninep/testing.zig");
const event = ctlfs.Node.of(file.serial, .event);
const h = th.call(p, .{ .tag = 1, .op = .open, .node = event }).reply.handle;
defer _ = th.call(p, .{ .tag = 2, .op = .release, .node = event, .handle = h });
// The 9P harness performs the effects: what it wrote is its answer's.
const sent = th.wr(p, event, "MX0 8\n");
try std.testing.expectEqualStrings("print(1)\r", sent.pty_buf[0..sent.pty_len]);
const ran = th.wr(p, event, "FX0 0 2 2 ls\n");
try std.testing.expect(ran.pty_len == 0 and ran.spawned);
// The pane's ctl line ends with the id it is bound as.
var line: [ctlfs.ctl.pane_text_cap]u8 = undefined;
try std.testing.expect(std.mem.indexOf(u8, ctlfs.ctl.paneText(p, p.panes[1].?, &line), " python-a ") != null);
}
// What is sent is plain text: CRLF is LF, no ESC or other control.
_ = exec.executeFrom(p, 0, "a = 1\r\nb = \x1b[201~2", true);
Sent.drain(p);
try std.testing.expectEqualStrings("a = 1\rb = [201~2\r", Sent.said(1));
// Into a REPL that takes a bracketed paste (3.13's), the Enter waits
// for the REPL to answer the paste: read with it, it would be part of it.
p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?2004h" } });
Sent.drain(p);
_ = exec.executeFrom(p, 0, "print(1)", true);
Sent.drain(p);
try std.testing.expectEqualStrings("\x1b[200~print(1)\x1b[201~", Sent.said(1));
p.update(.{ .output = .{ .pane = 1, .bytes = "print(1)" } });
Sent.drain(p);
// Python's echo only restarts a short wait: the Enter goes once the
// echo of the whole paste has gone quiet.
try std.testing.expectEqualStrings("", Sent.said(1));
p.clock.now_ns = p.panes[1].?.repl_enter_due_ns;
p.update(.tick);
Sent.drain(p);
try std.testing.expectEqualStrings("\r", Sent.said(1));
// A paste of more than one line gets the blank line a block gets.
_ = exec.executeFrom(p, 0, "print(11)\nprint(22)", true);
Sent.drain(p);
try std.testing.expectEqualStrings("\x1b[200~print(11)\nprint(22)\x1b[201~", Sent.said(1));
p.clock.now_ns = p.panes[1].?.repl_enter_due_ns;
p.update(.tick);
Sent.drain(p);
try std.testing.expectEqualStrings("\r\r", Sent.said(1));
// Nothing answering, it goes when its wait is up.
_ = exec.executeFrom(p, 0, "print(2)", true);
p.update(.tick); // on the clock: not yet, however old core time is
Sent.drain(p);
try std.testing.expect(std.mem.endsWith(u8, Sent.said(1), "\x1b[200~print(2)\x1b[201~"));
p.clock.now_ns = p.panes[1].?.repl_enter_due_ns; // the clock reaches its wait
p.update(.tick);
Sent.drain(p);
try std.testing.expectEqualStrings("\r", Sent.said(1));
p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?2004l" } });
Sent.len[1] = 0;
// A block left open by its indented last line gets the blank line that
// ends it: a second Enter.
_ = exec.executeFrom(p, 0, "def f():\n return 1", true);
Sent.drain(p);
try std.testing.expectEqualStrings("def f():\r return 1\r\r", Sent.said(1));
// Several selections executed at once: each is sent, not the first.
{
const text = try edit.flatSurface(p, &file.body);
file.body.setRanges(text, &.{ .{ .anchor = 0, .head = 8 }, .{ .anchor = 9, .head = 11 } }, &.{}, 0, true);
try std.testing.expect(exec.chordEachSel(p, file, .Exec));
Sent.drain(p);
try std.testing.expectEqualStrings("print(1)\rls\r", Sent.said(1));
}
// Its own body too.
try std.testing.expectEqual(@as(?usize, 1), exec.executeFrom(p, 1, "x = 1", true));
Sent.drain(p);
try std.testing.expectEqualStrings("x = 1\r", Sent.said(1));
// Escapes: a tag's word, Exec by name, a command word. Each a command.
_ = exec.execute(p, 0, "ls");
Sent.drain(p);
try std.testing.expect(Sent.spawned and Sent.len[1] == 0);
try std.testing.expect(p.executeBuiltinLine(0, "Exec ls"));
Sent.drain(p);
try std.testing.expect(Sent.spawned and Sent.len[1] == 0);
_ = exec.executeFrom(p, 0, "@`ls`", true);
Sent.drain(p);
try std.testing.expect(Sent.spawned and Sent.len[1] == 0);
// Two bound: it asks, one key answers, Esc sends nowhere.
try std.testing.expect(p.executeBuiltinLine(2, "Repl python"));
try std.testing.expectEqualStrings("python-b", exec.replId(&idbuf, p.panes[2].?));
Sent.drain(p);
try std.testing.expectEqual(@as(?usize, null), exec.executeFrom(p, 0, "print(2)", true));
try std.testing.expectEqual(Pane.Prompt.repl_choice, file.prompt);
try std.testing.expect(std.mem.indexOf(u8, file.promptText().?, "a b") != null);
p.update(.{ .key = .{ .cp = 'b' } });
Sent.drain(p);
try std.testing.expectEqualStrings("print(2)\r", Sent.said(2));
try std.testing.expect(Sent.len[1] == 0 and file.prompt == .none);
// The question is in the log, and a script answers it on the ctl.
{
const th = @import("ninep/testing.zig");
_ = exec.executeFrom(p, 0, "print(5)", true);
var want: [32]u8 = undefined;
try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "ask {d} repl a b\n", .{file.serial})));
// A choice not offered is refused, and the question stands.
const refused = th.wr(p, ctlfs.Node.of(file.serial, .ctl), "answer z\n");
try std.testing.expectEqual(ctlfs.E.INVAL, refused.errno());
try std.testing.expect(std.mem.endsWith(u8, refused.reply.ename, " \"z\""));
try std.testing.expectEqual(Pane.Prompt.repl_choice, file.prompt);
const answered = th.wr(p, ctlfs.Node.of(file.serial, .ctl), "answer a\n");
try std.testing.expectEqual(ctlfs.Status.ok, answered.reply.status);
try std.testing.expectEqualStrings("print(5)\r", answered.pty());
try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} a\n", .{file.serial})));
}
_ = exec.executeFrom(p, 0, "print(3)", true);
p.update(.{ .key = .{ .cp = Key.escape } });
Sent.drain(p);
try std.testing.expect(Sent.len[1] == 0 and Sent.len[2] == 0);
// The pane a letter offered is the one it answers for: unbound while
// the question stood, it is sent nothing, and that is said.
_ = exec.executeFrom(p, 0, "print(4)", true);
try std.testing.expect(p.executeBuiltinLine(2, "Repl -"));
p.update(.{ .key = .{ .cp = 'b' } });
Sent.drain(p);
try std.testing.expect(Sent.len[1] == 0 and Sent.len[2] == 0);
try std.testing.expectEqualStrings("Repl: the REPL chosen is gone; nothing sent", file.msg[0..file.msg_len]);
try std.testing.expect(p.executeBuiltinLine(2, "Repl python"));
try std.testing.expectEqualStrings("python-b", exec.replId(&idbuf, p.panes[2].?));
// A bound REPL whose program exited (Ctrl-D: the shell has the tty) is
// skipped: the one still running takes the text, no question asked;
// with none running, nothing runs and that is said.
host.taken[1] = false;
_ = exec.executeFrom(p, 0, "import os", true);
try std.testing.expectEqual(Pane.Prompt.none, file.prompt);
Sent.drain(p);
try std.testing.expectEqualStrings("import os\r", Sent.said(2));
host.taken[2] = false;
_ = exec.executeFrom(p, 0, "import os", true);
try std.testing.expectEqual(Pane.Prompt.none, file.prompt);
Sent.drain(p);
try std.testing.expect(Sent.len[1] == 0 and Sent.len[2] == 0 and !Sent.spawned);
try std.testing.expect(std.mem.indexOf(u8, file.msg[0..file.msg_len], "no program running") != null);
host.taken[1] = true;
host.taken[2] = true;
// Unbound, its letter is free again; bare, it says what it is.
try std.testing.expect(p.executeBuiltinLine(1, "Repl -"));
try std.testing.expect(p.panes[1].?.repl == null);
try std.testing.expect(p.executeBuiltinLine(1, "Repl python"));
try std.testing.expectEqualStrings("python-a", exec.replId(&idbuf, p.panes[1].?));
try std.testing.expect(p.executeBuiltinLine(2, "Repl"));
try std.testing.expectEqualStrings("Repl: python-b", p.panes[2].?.msg[0..p.panes[2].?.msg_len]);
// A command pane is a REPL while its command runs: done, it is none,
// and a done one cannot be bound. A document pane is no terminal.
const cmd = p.freeSlot().?;
_ = try pardes.panes.newCommand(p, cmd, "", "python3");
try std.testing.expect(p.executeBuiltinLine(cmd, "Repl python"));
try std.testing.expect(p.panes[cmd].?.repl != null);
p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 0 } });
try std.testing.expect(p.panes[cmd].?.repl == null);
try std.testing.expect(p.executeBuiltinLine(cmd, "Repl python"));
try std.testing.expect(p.panes[cmd].?.repl == null);
const doc_slot = p.freeSlot().?;
const doc = try p.newDocPane(doc_slot);
try std.testing.expect(p.executeBuiltinLine(doc_slot, "Repl python"));
try std.testing.expect(doc.repl == null);
}
test "a restored terminal's tag names neither the REPL it was nor the shell it had" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
p.acknowledgeShell(0, "/usr/bin/fish", true);
var host: FakeTtyQuery = .{};
host.install(p);
try std.testing.expect(p.executeBuiltinLine(0, "Repl python"));
try dump.dumpState(p);
const restored = try dump.restore(p, p.dump_out.?, "test");
defer restored.deinit();
const pane = restored.panes[0].?;
try std.testing.expect(pane.repl == null and pane.tag.own == null);
const shown = try tagline.tagText(restored, restored.scratch.allocator(), pane);
try std.testing.expect(std.mem.indexOf(u8, shown, "python-a") == null);
try std.testing.expect(std.mem.indexOf(u8, shown, "Term+fish") == null);
}
test "a Term started by a shell's path keeps the path in its Term+ word" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
try std.testing.expect(p.executeBuiltinLine(0, "Term /bin/sh"));
try std.testing.expect(p.view().active != 0);
p.acknowledgeShell(p.view().active, "/bin/sh", false);
try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.view().active].?), " Term+/bin/sh "));
}
test "Tty, Term's old name in saved tags, runs as Term, bare and with its +shell" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
try std.testing.expect(p.executeBuiltinLine(0, "Tty+sh"));
try std.testing.expectEqualStrings("sh", p.panes[p.view().active].?.shell.?);
const first = p.view().active;
p.view().active = 0;
try std.testing.expect(p.executeBuiltinLine(0, "Tty"));
try std.testing.expect(p.view().active != 0 and p.view().active != first);
}
test "Term+fish, one word a tag can hold, opens a terminal on that shell" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
// sh, the one shell every host has.
try std.testing.expect(p.executeBuiltinLine(0, "Term+sh"));
try std.testing.expect(p.view().active != 0);
try std.testing.expectEqualStrings("sh", p.panes[p.view().active].?.shell.?);
p.acknowledgeShell(p.view().active, "/bin/sh", false);
try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.view().active].?), " Term+sh "));
p.view().active = 0;
// A shell that is not there is said, not quietly replaced, and the
// pane that asked gets no shell of its own.
const before = p.view().active;
const caller = p.panes[0].?;
try std.testing.expect(p.executeBuiltinLine(0, "Term /nonexistent"));
try std.testing.expect(p.view().active == before and caller.shell == null);
try std.testing.expect(std.mem.indexOf(u8, caller.msg[0..caller.msg_len], "shell \"/nonexistent\" not found") != null);
try std.testing.expect(p.executeBuiltinLine(0, "Term fsh-not-a-shell"));
try std.testing.expect(caller.shell == null);
// A directory passes access(X_OK); it is no shell either.
try std.testing.expect(p.executeBuiltinLine(0, "Term /etc"));
try std.testing.expect(p.view().active == before);
try std.testing.expect(std.mem.indexOf(u8, caller.msg[0..caller.msg_len], "Term: not a shell: /etc is a directory") != null);
// Only a word that says so splits at `+`: `Dump+x.zon` is no Dump.
try std.testing.expect(!p.executeBuiltinLine(0, "Dump+x.zon"));
try std.testing.expect(!p.executeBuiltinLine(0, "Msg+hello"));
}
test "a command pane shows how its command ended, and the next command there runs below it" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{});
defer p.deinit();
while (p.nextEffect()) |_| {}
p.setCwd(0, "/tmp/pardes-cmd");
_ = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pardes-cmd/pic.ppm", null);
const dst = exec.execute(p, 1, "make -j8") orelse return error.NoCommandPane;
while (p.nextEffect()) |_| {}
const pane = p.panes[dst].?;
// Its first command is echoed as every later one is.
{
const first = try pardes.panes.terminal.screenTextAlloc(pane, gpa);
defer gpa.free(first);
try std.testing.expect(std.mem.startsWith(u8, first, "% make -j8"));
}
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, pane), "(make -j8) running"));
// Running, a second command goes to a pane of its own.
const other = exec.execute(p, 1, "ls") orelse return error.NoCommandPane;
try std.testing.expect(other != dst);
while (p.nextEffect()) |_| {}
p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "compiled\r\n" } });
// Its exit comes first, a job it left still printing: done, and not
// the next command's until its pty closes.
p.update(.{ .exited = .{ .pane = @intCast(dst), .status = 2 } });
try std.testing.expect(pane.command_done and pane.command_pty);
const busy = exec.execute(p, 1, "true") orelse return error.NoCommandPane;
try std.testing.expect(busy != dst);
while (p.nextEffect()) |_| {}
// Its output ending: now it may be reused.
p.update(.{ .eof = .{ .pane = @intCast(dst) } });
try std.testing.expect(p.panes[dst] == pane and !pane.command_pty);
try std.testing.expect(p.panes[dst] == pane);
try std.testing.expect(pane.command_done);
try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, pane), "(make -j8) exit 2"));
// Kill leaves a finished one be.
try std.testing.expect(p.executeBuiltinLine(0, "Kill make"));
while (p.nextEffect()) |effect| if (effect == .signal_pty and effect.signal_pty.pane == dst) return error.SignalledAFinishedCommand;
// A program that crashed out of its full screen leaves the emulator
// in its modes; the next command starts clear of them.
p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "\x1b[?1049h\x1b[?2004h\x1b[?1000h" } });
try std.testing.expect(pardes.panes.terminal.bracketedPaste(pane));
// Done, the directory's next command runs there, below what it showed.
try std.testing.expectEqual(@as(?usize, dst), exec.execute(p, 1, "make test"));
try std.testing.expect(!pardes.panes.terminal.bracketedPaste(pane));
var respawned = false;
while (p.nextEffect()) |effect| if (effect == .spawn and effect.spawn.pane == dst) {
respawned = true;
};
try std.testing.expect(respawned);
const body = try pardes.panes.terminal.screenTextAlloc(pane, gpa);
defer gpa.free(body);
const said = std.mem.indexOf(u8, body, "compiled") orelse return error.OutputLost;
const ended = std.mem.indexOf(u8, body, "exit 2") orelse return error.ExitLost;
const next = std.mem.indexOf(u8, body, "% make test") orelse return error.NoSeparator;
try std.testing.expect(said < ended and ended < next);
try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, pane), "(make test) running"));
// Kill stops a running one: its whole process group, SIGTERM.
try std.testing.expect(p.executeBuiltinLine(0, "Kill make"));
var signalled = false;
while (p.nextEffect()) |effect| if (effect == .signal_pty and effect.signal_pty.pane == dst) {
try std.testing.expectEqual(PtySignal.term, effect.signal_pty.sig);
signalled = true;
};
try std.testing.expect(signalled);
// The log says what ran and how it ended.
const log = try ctlfs.events.freezeLog(p);
defer gpa.free(log.bytes);
var want: [64]u8 = undefined;
// The whole line, after the `new` of the pane it runs in.
const ran = std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "run {d} make -j8\n", .{pane.serial})) orelse return error.NoRunRecord;
const made = std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "new {d} ", .{pane.serial})) orelse return error.NoNewRecord;
try std.testing.expect(made < ran);
try std.testing.expect(std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "exit {d} 2\n", .{pane.serial})) != null);
// A signal for a pane is not performed on whoever takes its slot.
const Count = struct {
var signals: usize = 0;
const vtable: Host.VTable = .{ .pty_signal = signal };
fn signal(_: ?*anyopaque, _: u8, _: PtySignal) void {
signals += 1;
}
};
const host_before = p.host;
p.host = .{ .vtable = &Count.vtable };
try std.testing.expect(p.executeBuiltinLine(0, "Kill make"));
try p.removePane(dst, null);
_ = try pardes.panes.newCommand(p, dst, "", "other");
while (p.nextEffect()) |effect| if (effect == .signal_pty) p.perform(effect);
try std.testing.expectEqual(@as(usize, 0), Count.signals);
p.host = host_before;
// A command line longer than a command pane takes is refused.
const long = &@as([exec.command_max + 1]u8, @splat('x'));
try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 1, long));
}
test "a terminal its program gave back takes command lines again" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{});
defer p.deinit();
while (p.nextEffect()) |_| {}
p.acknowledgeShell(0, "/bin/sh", false);
p.setCwd(0, "/tmp/pardes-taken-flip");
var host: FakeTtyQuery = .{};
host.install(p);
host.taken[0] = true;
try std.testing.expect(exec.execute(p, 0, "echo while-taken") != 0);
while (p.nextEffect()) |_| {}
// the program exited, so the host's answer changes — and the core asks
// again, because it never cached the old one
host.taken[0] = false;
try std.testing.expectEqual(@as(?usize, 0), exec.execute(p, 0, "echo after"));
var sent: [64]u8 = undefined;
var sent_len: usize = 0;
while (p.nextEffect()) |effect| switch (effect) {
.write => |w| {
try std.testing.expectEqual(@as(u8, 0), w.pane);
try std.testing.expect(w.bytes.slice().len <= sent.len - sent_len);
@memcpy(sent[sent_len..][0..w.bytes.slice().len], w.bytes.slice());
sent_len += w.bytes.slice().len;
},
.spawn => return error.SpawnedDespiteAPromptOfItsOwn,
else => {},
};
try std.testing.expectEqualStrings("echo after\r", sent[0..sent_len]);
}
test "the host is asked about a tty only where a command line is about to go" {
const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
var host: FakeTtyQuery = .{};
host.install(p);
p.setCwd(0, "/tmp/pardes-lazy-a");
p.setCwd(1, "/tmp/pardes-lazy-b");
p.setCwd(2, "/tmp/pardes-lazy-c");
_ = try p.render(frame.allocator());
p.update(.{ .key = .{ .cp = 'x' } });
p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = 4, .row = 4 } });
p.update(.{ .resize = .{ .cols = 90, .rows = 28 } });
while (p.nextEffect()) |_| {}
_ = try p.render(frame.allocator());
try std.testing.expectEqual(@as(usize, 0), host.asked);
// The pane an Exec is typed into is one question, asked once...
_ = exec.execute(p, 0, "echo lazy");
while (p.nextEffect()) |_| {}
try std.testing.expectEqual(@as(usize, 1), host.asked);
// ...and a taken one is asked once too: the line then runs as a command
// pane, with no other terminal to ask about.
host.taken[0] = true;
host.asked = 0;
_ = exec.execute(p, 0, "echo lazy-again");
while (p.nextEffect()) |_| {}
try std.testing.expectEqual(@as(usize, 1), host.asked);
}
test "a host with no methods at all is a complete in-process pardes" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 });
defer p.deinit();
while (p.nextEffect()) |_| {}
// A pump against the empty host renders a frame and blocks on nothing.
try p.pump(.{});
try std.testing.expect(!p.quit);
// the absent child is SILENT: the bytes are dropped, and nothing appears
// on the pane's screen to suggest a program answered
const before = p.panes[0].?.terminal.?.vt.screens.active.cursor.y;
p.perform(.{ .write = .{ .pane = 0, .bytes = .from("ls\r") } });
try std.testing.expectEqual(before, p.panes[0].?.terminal.?.vt.screens.active.cursor.y);
// the clipboard round-trips through the in-process one
p.registers.put(gpa, '+', "copied", 0, 1, true);
p.perform(.set_clipboard);
try std.testing.expectEqualStrings("copied", p.fallback.clipboard.items);
// ...and a save with no filesystem lands in the virtual one
const doc = try p.setTestFile("body\n");
var doc_id: u8 = 0;
for (p.panes, 0..) |slot, i| if (slot == doc) {
doc_id = @intCast(i);
};
p.perform(.{ .save_file = .{ .pane = doc_id } });
try std.testing.expectEqualStrings("body\n", p.fallback.files.get(doc.file.?.path).?);
// a language backend nobody supplied answers nothing rather than hanging
p.perform(.{ .lsp = .{ .id = 7, .kind = .hover, .pane = doc_id, .offset = 0, .arg = .{} } });
p.perform(.quit);
try std.testing.expect(p.quit);
}
test "Font keeps requested and acknowledged faces as separate plain state" {
if (comptime !font_picker) return; // there is no Font builtin on the tty
const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 });
defer p.deinit();
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const installed = fonts.list(arena.allocator(), null);
if (installed.len == 0) return; // a machine with no monospace face at all
var line: [512]u8 = undefined;
const cmd = try std.fmt.bufPrint(&line, "Font {s}", .{installed[0].name});
try std.testing.expect(p.executeBuiltinLine(p.view().active, cmd));
try std.testing.expect(p.settings.font.pending);
try std.testing.expectEqualStrings(installed[0].name, p.settings.font.requested_name.get());
try std.testing.expectEqualStrings(installed[0].path, p.settings.font.requested_path.get());
try std.testing.expectEqual(@as(u16, 0), p.settings.font.requested_size_hundredths);
try std.testing.expectEqualStrings("", p.settings.font.effective_name.get());
// Boot/zoom/display-scale reports describe the face already being drawn;
// they must neither answer nor reject the new request waiting beside it.
try std.testing.expect(p.observeFont("Embedded Mono", 1200, .pixels));
try std.testing.expectEqualStrings("Embedded Mono", p.settings.font.effective_name.get());
try std.testing.expect(p.settings.font.pending);
try std.testing.expect(!p.acknowledgeFont("Stray Ack", 1250, .pixels));
p.rejectFont();
try std.testing.expect(p.settings.font.pending);
const request = p.takeFontRequest() orelse return error.MissingFontRequest;
try std.testing.expectEqualStrings(installed[0].path, request);
try std.testing.expect(p.settings.font.pending);
try std.testing.expect(p.takeFontRequest() == null);
try std.testing.expect(p.acknowledgeFont(installed[0].name, 1375, .pixels));
try std.testing.expect(!p.settings.font.pending);
try std.testing.expectEqualStrings(installed[0].name, p.settings.font.effective_name.get());
try std.testing.expectEqual(@as(u16, 1375), p.settings.font.effective_size_hundredths);
try std.testing.expectEqual(config.Runtime.FontSizeUnit.pixels, p.settings.font.effective_size_unit);
try std.testing.expect(!p.acknowledgeFont("Duplicate Ack", 1400, .pixels));
try std.testing.expect(p.executeBuiltinLine(p.view().active, cmd));
_ = p.takeFontRequest() orelse return error.MissingRepeatedFontRequest;
try std.testing.expect(p.acknowledgeFont(installed[0].name, 1375, .pixels));
// A name nothing answers to changes neither request nor effective state.
try std.testing.expect(p.executeBuiltinLine(p.view().active, "Font zzz-no-such-face"));
try std.testing.expectEqualStrings(installed[0].name, p.settings.font.requested_name.get());
try std.testing.expectEqualStrings(installed[0].name, p.settings.font.effective_name.get());
}
test "Font size suffix reaches native request and invalid input leaves it intact" {
if (comptime !font_picker) return;
const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 });
defer p.deinit();
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const installed = fonts.list(arena.allocator(), null);
if (installed.len == 0) return;
var line: [512]u8 = undefined;
try std.testing.expect(p.executeBuiltinLine(p.view().active, try std.fmt.bufPrint(&line, "Font {s}:18.5", .{installed[0].name})));
try std.testing.expectEqual(@as(u16, 1850), p.settings.font.requested_size_hundredths);
try std.testing.expectEqualStrings(installed[0].path, p.takeFontRequest().?);
try std.testing.expect(p.acknowledgeFont(installed[0].name, 1850, .pixels));
try std.testing.expect(p.executeBuiltinLine(p.view().active, try std.fmt.bufPrint(&line, "Font {s}:nan", .{installed[0].name})));
try std.testing.expectEqual(@as(u16, 1850), p.settings.font.requested_size_hundredths);
try std.testing.expect(p.takeFontRequest() == null);
try std.testing.expect(p.executeBuiltinLine(p.view().active, "Font zzz-no-such-face:20"));
try std.testing.expectEqual(@as(u16, 1850), p.settings.font.requested_size_hundredths);
try std.testing.expect(p.takeFontRequest() == null);
try std.testing.expect(p.executeBuiltinLine(p.view().active, try std.fmt.bufPrint(&line, "Font {s}", .{installed[0].name})));
try std.testing.expectEqual(@as(u16, 0), p.settings.font.requested_size_hundredths);
try std.testing.expectEqual(@as(u16, 1850), p.settings.font.effective_size_hundredths);
}
test "startup config overrides restored styling before initFromDump returns" {
const source = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme dark\n" });
defer source.deinit();
try std.testing.expectEqualStrings("dark", source.theme().name);
try dump.dumpState(source);
const restored = try dump.initFromDump(
std.testing.allocator,
.{ .startup_config = "Theme acme\n" },
source.dump_out.?,
);
defer restored.deinit();
try std.testing.expectEqualStrings("acme", restored.theme().name);
try std.testing.expect(!source.animationActive());
try std.testing.expect(!restored.animationActive());
try std.testing.expectEqual(ChromeTheme.fromTheme(source.theme()), source.chromeTheme().*);
try std.testing.expectEqual(ChromeTheme.fromTheme(restored.theme()), restored.chromeTheme().*);
}
test "restored terminals keep monotonic nonzero pane identities" {
const gpa = std.testing.allocator;
const source = try Pardes.init(gpa, .{ .shells = 3 });
defer source.deinit();
// Filter is the pane's, and a dump keeps it: one toggled off comes back off.
source.panes[1].?.tty_filter = false;
try dump.dumpState(source);
const restored = try dump.initFromDump(gpa, .{}, source.dump_out.?);
defer restored.deinit();
var ids: [MAX_PANES]usize = undefined;
var serials: [MAX_PANES]u32 = undefined;
var n: usize = 0;
for (restored.panes, 0..) |slot, id| {
const pane = slot orelse continue;
if (!pane.isTerminal()) continue;
try std.testing.expectEqual(id != 1, pane.tty_filter);
try std.testing.expect(pane.serial != 0);
for (serials[0..n]) |seen| try std.testing.expect(pane.serial != seen);
ids[n] = id;
serials[n] = pane.serial;
n += 1;
}
try std.testing.expectEqual(@as(usize, 3), n);
for (ids[0..n], serials[0..n]) |id, serial|
try std.testing.expectEqual(id, restored.paneBySerial(serial).?);
const before = restored.next_serial;
const free = restored.freeSlot() orelse return error.NoFreePane;
const fresh = try restored.newShell(free, "");
try std.testing.expect(fresh.tty_filter);
try std.testing.expectEqual(before + 1, fresh.serial);
try std.testing.expectEqual(fresh.serial, restored.next_serial);
}
test "Tab N draws every pane's tab N cells wide and clicks count past it; bare Tab says the width; the ctl read and a Dump keep it" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 });
defer p.deinit();
// The width is the process's: the next test starts from the default.
defer config.tab_now = config.tab_width;
const pane = try p.setTestFile("\tx = 1\n");
try std.testing.expect(p.executeBuiltinLine(0, "Tab 8"));
try std.testing.expectEqual(@as(u16, 8), config.tab_now);
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
const surface = try p.render(frame.allocator());
const rect = p.view().rects[0];
const text_x = rect.x + config.GUTTER + config.PREFIX_W;
const body_y = rect.y + BOX_H;
try std.testing.expectEqualStrings("x", surface.at(text_x + 8, body_y).grapheme());
// A click on the x is on its byte, past the tab.
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = text_x + 8, .row = body_y } });
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + 8, .row = body_y } });
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
// Bare, it says the width.
try std.testing.expect(p.executeBuiltinLine(0, "Tab"));
try std.testing.expectEqualStrings("Tab 8", pane.msg[0..pane.msg_len]);
// Out of range: refused, the width kept.
try std.testing.expect(p.executeBuiltinLine(0, "Tab 0"));
try std.testing.expectEqual(@as(u16, 8), config.tab_now);
// The ctl read's tab column, and a Dump's settings.
const ctl_text = @import("ninep/testing.zig").rd(p, ctlfs.Node.of(pane.serial, .ctl), 0, 4096).bytes;
try std.testing.expect(std.mem.indexOf(u8, ctl_text, " 8 ") != null);
try dump.dumpState(p);
const restored = try dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
defer restored.deinit();
try std.testing.expectEqual(@as(u16, 8), restored.settings.tab);
try std.testing.expectEqual(@as(u16, 8), config.tab_now);
}
test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 });
defer p.deinit();
const pane = try p.setTestFile("\treturn x\n");
const f = &pane.file.?;
f.highlights = try p.tree_sitter_gpa.alloc(u8, f.content.len);
@memset(f.highlights, @backingInt(syntax.Syn.none));
@memset(f.highlights[1..7], @backingInt(syntax.Syn.keyword));
f.syntax_dirty = false;
pane.body.cur_row = 0;
pane.body.cur_col = 1;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
const surface = try p.render(frame.allocator());
const rect = p.view().rects[0];
const text_x = rect.x + config.GUTTER + config.PREFIX_W;
const body_y = rect.y + BOX_H;
// The keyword's ink shows the glyph boundaries.
const kw: Color = .{ .rgb = p.theme().kw };
for (0..config.tab_width) |col|
try std.testing.expect(!std.meta.eql(kw, surface.at(text_x + @as(u16, @intCast(col)), body_y).style.fg));
for (0.."return".len) |col|
try std.testing.expectEqual(kw, surface.at(text_x + config.tab_width + @as(u16, @intCast(col)), body_y).style.fg);
try std.testing.expectEqual(text_x + config.tab_width, surface.cursor.?.x);
const click_x = text_x + config.tab_width + 2;
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = click_x, .row = body_y } });
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = click_x, .row = body_y } });
try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col);
const line = modal.lineSlice(f.content, 0);
const virtual: u16 = 3;
const blank_x = text_x + @as(u16, @intCast(pardes.panes.File.displayWidth(line))) + virtual;
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = blank_x, .row = body_y } });
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = blank_x, .row = body_y } });
try std.testing.expectEqual(@as(i32, @intCast(line.len)), pane.body.cur_col);
_ = frame.reset(.retain_capacity);
const virtual_surface = try p.render(frame.allocator());
try std.testing.expectEqual(blank_x - virtual, virtual_surface.cursor.?.x);
const local_blank: i32 = @intCast(blank_x - rect.x - config.GUTTER);
try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = local_blank, .c1 = local_blank, .r0 = BOX_H, .r1 = BOX_H }) == null);
// The immediately-adjacent EOL cell and an in-line separator are blank
// too. Pointer expansion must not lean left into the preceding word.
const adjacent: i32 = @intCast(config.PREFIX_W + pardes.panes.File.displayWidth(line));
try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = adjacent, .c1 = adjacent, .r0 = BOX_H, .r1 = BOX_H }) == null);
const separator: i32 = @intCast(config.PREFIX_W + config.tab_width + "return".len);
try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = separator, .c1 = separator, .r0 = BOX_H, .r1 = BOX_H }) == null);
}
test "the workspace tag's Restore word names the last dump, the tag edited around it or not, across a Restore too" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true });
defer p.deinit();
p.setLastDump("/tmp/a.zon");
// The tag edited: its own text holds the Restore word as it was then.
p.global_tag.own = try p.gpa.dupe(u8, try std.fmt.allocPrint(p.scratch.allocator(), "{s} Mine", .{tagline.headerDefault(p, .workspace)}));
p.setLastDump("/tmp/b.zon");
try std.testing.expect(std.mem.indexOf(u8, p.global_tag.own.?, "Restore /tmp/b.zon Mine") != null);
try dump.dumpState(p);
const restored = try dump.restore(p, p.dump_out.?, "/tmp/c.zon");
defer restored.deinit();
try std.testing.expect(std.mem.indexOf(u8, restored.global_tag.own.?, "Restore /tmp/c.zon Mine") != null);
try std.testing.expectEqualStrings("/tmp/c.zon", restored.last_dump.?);
}
test "editable workspace and column tags are typed into and persist" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true });
defer p.deinit();
_ = try p.setTestFile("untouched\n");
p.presented();
try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.view().rects[0].y);
// a sweep over a header is its selection, the caret where it ended
p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = 0 } });
p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = TAG_TEXT_INSET + 6, .row = 0 } });
p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET + 6, .row = 0 } });
try std.testing.expect(p.global_tag.vsel.active and p.global_tag.vsel.col == 0 and p.global_tag.cur_col == 6);
// A clicked header is in normal mode: `a` types after the sweep's
// last character, the blank it ended on.
p.update(.{ .key = .{ .cp = 'a', .text = "a" } });
p.update(.{ .key = .{ .cp = 'H', .text = "Help " } });
try std.testing.expect(std.mem.startsWith(u8, p.global_tag.own.?, "Newcol Help Joincol"));
p.update(.{ .key = .{ .cp = Key.escape } });
p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } });
p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } });
p.update(.{ .key = .{ .cp = 'i', .text = "i" } });
p.update(.{ .key = .{ .cp = 'é', .text = "é" } });
try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "éNew"));
p.update(.{ .key = .{ .cp = Key.backspace } });
try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "New"));
p.update(.{ .paste = "Grep " });
try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "Grep New"));
try std.testing.expectEqualStrings("untouched\n", p.panes[0].?.file.?.content);
try dump.dumpState(p);
const restored = try dump.restore(p, p.dump_out.?, "test");
defer restored.deinit();
try std.testing.expectEqualStrings(p.global_tag.own.?, restored.global_tag.own.?);
try std.testing.expectEqualStrings(tagline.columnTag(p, 0), tagline.columnTag(restored, 0));
p.gpa.free(p.view().col_tags[0].own.?);
p.view().col_tags[0].own = try p.gpa.dupe(u8, "");
try dump.dumpState(p);
const empty = try dump.restore(p, p.dump_out.?, "test");
defer empty.deinit();
try std.testing.expectEqualStrings("", tagline.columnTag(empty, 0));
}
test "column tag first-cell execution keeps New local to the clicked column" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 20, .tty_only = true });
defer p.deinit();
_ = try p.setTestFile("untouched\n");
layout.newColumn(p, 0);
layout.newScratchIn(p, 0, layout.activeColumn(p).?);
p.sync();
for (0..2) |column| {
p.view().active = p.view().cols[1 - column].panes[0];
p.presented();
const before = p.view().cols;
p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = p.view().col_x[column] + TAG_TEXT_INSET, .row = TOPBAR_H } });
p.update(.{ .mouse = .{ .button = .middle, .kind = .release, .col = p.view().col_x[column] + TAG_TEXT_INSET, .row = TOPBAR_H } });
try std.testing.expectEqual(before[column].n + 1, p.view().cols[column].n);
try std.testing.expectEqual(before[1 - column].n, p.view().cols[1 - column].n);
try std.testing.expectEqual(column, layout.findPane(p, p.view().active).?.col);
}
try std.testing.expectEqualStrings("untouched\n", p.panes[0].?.file.?.content);
}
test "a screen too short for the column row releases a column tag's focus without losing its commands" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12, .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("unchanged body\n");
p.view().col_tags[0].own = try p.gpa.dupe(u8, "New Help");
p.presented();
const shown = p.view().rects[0];
try std.testing.expectEqual(TOPBAR_H + COLBAR_H, shown.y);
p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } });
p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } });
try std.testing.expect(p.view().header != null and p.headerColumn() != null);
p.update(.{ .resize = .{ .cols = 60, .rows = 2 } });
try std.testing.expectEqual(@as(u16, 0), layout.columnBarHeight(p));
try std.testing.expectEqual(TOPBAR_H, p.view().rects[0].y);
try std.testing.expect(p.view().header == null and p.headerColumn() == null);
p.update(.{ .resize = .{ .cols = 60, .rows = 12 } });
try std.testing.expectEqual(shown, p.view().rects[0]);
try std.testing.expectEqualStrings("New Help", tagline.columnTag(p, 0));
try std.testing.expectEqualStrings("unchanged body\n", pane.file.?.content);
}
test "screen resize keeps its previous storage until allocation succeeds" {
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
const p = try Pardes.init(failing.allocator(), .{ .cols = 80, .rows = 24, .tty_only = true });
defer p.deinit();
var frame: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer frame.deinit();
const surface = try p.render(frame.allocator());
const cells = surface.cells;
p.update(.{ .resize = .{ .cols = 81, .rows = 25 } });
failing.fail_index = failing.alloc_index;
try std.testing.expectError(error.OutOfMemory, p.render(frame.allocator()));
try std.testing.expectEqual(cells.ptr, surface.cells.ptr);
try std.testing.expectEqual(cells.len, surface.cells.len);
try std.testing.expectEqual(@as(u16, 80), surface.cols);
try std.testing.expectEqual(@as(u16, 24), surface.rows);
failing.fail_index = std.math.maxInt(usize);
const resized = try p.render(frame.allocator());
try std.testing.expectEqual(@as(u16, 81), resized.cols);
try std.testing.expectEqual(@as(u16, 25), resized.rows);
try std.testing.expectEqual(@as(usize, 81 * 25), resized.cells.len);
}
test "a boot file that will not open boots an errors pane rather than failing the launch" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.cols = 80,
.rows = 24,
.file = "/definitely/not/here/notes.md",
});
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
const pane = p.panes[0].?;
const f = pane.file.?;
try std.testing.expectEqual(pardes.panes.Output.Origin.errors, f.output.?.from);
// The reason IN WORDS, not an error name: `PermissionDenied` on a screen
// is jargon, and the whole point of this pane is that a human reads it.
try std.testing.expect(std.mem.indexOf(u8, f.content, "cannot open") != null);
try std.testing.expect(std.mem.indexOf(u8, f.content, "no file of that name") != null);
try std.testing.expect(std.mem.indexOf(u8, f.content, "/definitely/not/here/notes.md") != null);
}
test "argv naming nothing boots an errors pane rather than failing the launch" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.cols = 80,
.rows = 24,
.missing = .{ .word = "notes/tdoo.md", .dir = "/home/pardes-test/work" },
});
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
// One pane, filling the window, and it is an OUTPUT pane rather than the
// shell a bare `pardes` boots: the answer is the whole screen.
try std.testing.expectEqual(@as(u8, 1), p.view().ncol);
try std.testing.expectEqual(@as(usize, 1), p.view().cols[0].n);
try std.testing.expectEqual(@as(usize, 0), p.view().cols[0].panes[0]);
try std.testing.expectEqual(@as(usize, 0), p.view().active);
for (p.panes[1..]) |slot| try std.testing.expect(slot == null);
const pane = p.panes[0].?;
try std.testing.expect(!pane.isTerminal());
const f = pane.file.?;
try std.testing.expectEqual(pardes.panes.Output.Origin.errors, f.output.?.from);
// ...and it says what happened AND what was asked for. The word as typed,
// which is the half a bare "not found" leaves out.
try std.testing.expect(std.mem.indexOf(u8, f.content, "not found") != null);
try std.testing.expect(std.mem.indexOf(u8, f.content, "notes/tdoo.md") != null);
try std.testing.expectEqualStrings("/home/pardes-test/work/+Errors", f.path);
}
test "raw terminal cursor obeys visibility without hiding modal and tag cursors" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = p.panes[0].?;
pane.body.mode = .tty;
p.update(.{ .output = .{ .pane = 0, .bytes = "abc" } });
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
const visible = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
const rect = p.view().rects[0];
const body_y = rect.y + BOX_H;
try std.testing.expectEqual(rect.x + config.GUTTER + 3, visible.x);
try std.testing.expectEqual(body_y, visible.y);
p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25l" } });
try std.testing.expect((try p.render(frame.allocator())).cursor == null);
pane.body.mode = .normal;
pane.body.cur_pinned = true;
pane.body.cur_row = 0;
pane.body.cur_col = 1;
const modal_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
try std.testing.expectEqual(rect.x + config.GUTTER + 1, modal_cursor.x);
try std.testing.expectEqual(body_y, modal_cursor.y);
tagline.enterTag(p, pane);
const tag_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
try std.testing.expectEqual(rect.y, tag_cursor.y);
pane.focus = .body;
pane.body.mode = .tty;
try std.testing.expect((try p.render(frame.allocator())).cursor == null);
p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25h\x1b[?1049h\x1b[2;5H" } });
const alternate = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
try std.testing.expectEqual(rect.x + config.GUTTER + 4, alternate.x);
try std.testing.expectEqual(body_y + 1, alternate.y);
p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25l" } });
try std.testing.expect((try p.render(frame.allocator())).cursor == null);
p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049l\x1b[?25h" } });
const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
try std.testing.expectEqual(visible.x, returned.x);
try std.testing.expectEqual(visible.y, returned.y);
}
test "raw terminal cursor follows its active row only while that row is visible" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = p.panes[0].?;
pane.body.mode = .tty;
for (0..60) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "row\r\n" } });
p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;4H" } });
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
const live = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
const rect = p.view().rects[0];
const body_y = rect.y + BOX_H;
try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x);
try std.testing.expectEqual(body_y + 2, live.y);
pardes.panes.terminal.scrollGrid(pane, -1);
const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
try std.testing.expectEqual(live.x, scrolled.x);
try std.testing.expectEqual(live.y + 1, scrolled.y);
pardes.panes.terminal.scrollGrid(pane, -@as(i32, pane.rows));
try std.testing.expect((try p.render(frame.allocator())).cursor == null);
pardes.panes.terminal.followOutput(pane);
const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
try std.testing.expectEqual(live.x, returned.x);
try std.testing.expectEqual(live.y, returned.y);
}
test "the bare tty startup opens a text pane under the shell, unfocused" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty });
defer p.deinit();
try std.testing.expectEqual(Boot.tty, p.boot);
// One column, shell on top in raw mode, an empty text pane under it.
try std.testing.expectEqual(@as(usize, 1), p.view().ncol);
try std.testing.expectEqual(@as(usize, 2), p.view().cols[0].n);
const shell = p.panes[p.view().cols[0].panes[0]].?;
const scratch = p.panes[p.view().cols[0].panes[1]].?;
try std.testing.expect(shell.isTerminal());
try std.testing.expectEqual(Text.Mode.tty, shell.body.mode);
try std.testing.expect(!scratch.isTerminal());
try std.testing.expectEqualStrings("", scratch.file.?.content);
// ...and the shell keeps the keyboard.
try std.testing.expectEqual(p.view().cols[0].panes[0], p.view().active);
// Unnamed, it is the bare shell every test asks for.
const plain = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer plain.deinit();
try std.testing.expectEqual(Boot.tty_shell, plain.boot);
try std.testing.expectEqual(@as(usize, 1), plain.view().cols[0].n);
}
test "tty output follows only from the bottom" {
const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc
const shell = p.view().active;
const sp = p.panes[shell].?;
p.update(.{ .key = .{ .cp = 'b', .ctrl = true } });
try std.testing.expectEqual(Text.Mode.tty, sp.body.mode);
for (0..60) |i| {
var buf: [32]u8 = undefined;
p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } });
}
p.sync();
const bottom = pardes.panes.terminal.scrollbar(sp).offset;
try std.testing.expect(bottom > 0);
// Scrolled back, the reader stays put however much the shell prints.
sp.scrollBy(-10);
p.sync();
const parked = pardes.panes.terminal.scrollbar(sp).offset;
try std.testing.expect(parked < bottom);
for (60..70) |i| {
var buf: [32]u8 = undefined;
p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } });
}
p.sync();
try std.testing.expectEqual(parked, pardes.panes.terminal.scrollbar(sp).offset);
// Typing snaps back to live output, so nobody types blind.
p.update(.{ .key = .{ .cp = 'x', .text = "x" } });
p.sync();
try std.testing.expect(pardes.panes.terminal.scrollbar(sp).offset > parked);
// ...and from there output follows again.
const live = pardes.panes.terminal.scrollbar(sp).offset;
p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } });
p.sync();
try std.testing.expect(pardes.panes.terminal.scrollbar(sp).offset > live);
}
test "an unasked desktop paste reaches a tty pane's program, not its buffer" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
var buf: [256]u8 = undefined;
_ = test_api.ptyBytes(p, null, &buf);
const pane = p.panes[0].?;
pardes.panes.terminal.enterTty(p, 0);
// No request behind it: the window manager's own paste, or SDL answering a
// Ctrl-Shift-V the desktop handled. It still has to reach the shell.
p.update(.{ .paste = "ls -la" });
try std.testing.expectEqualStrings("ls -la", test_api.ptyBytes(p, null, &buf));
// and nothing was typed into an overlay the pty does not know about
try std.testing.expect(pane.ovl == null);
}
test "a paste larger than the effect ring reaches the program whole and in order" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
const buf = try gpa.alloc(u8, 2 << 20);
defer gpa.free(buf);
_ = test_api.ptyBytes(p, null, buf);
pardes.panes.terminal.enterTty(p, 0);
const text = try gpa.alloc(u8, 1536 * 1024);
defer gpa.free(text);
for (text, 0..) |*c, i| c.* = 'a' + @as(u8, @intCast(i % 26));
p.update(.{ .paste = text });
try std.testing.expectEqualSlices(u8, text, test_api.ptyBytes(p, null, buf));
// ...and the core is not still holding a copy afterwards
try std.testing.expectEqual(@as(usize, 0), p.pending_write_bytes);
}
test "a bracketed paste larger than the ring still closes its bracket" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
const buf = try gpa.alloc(u8, 2 << 20);
defer gpa.free(buf);
_ = test_api.ptyBytes(p, null, buf);
pardes.panes.terminal.enterTty(p, 0);
p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } });
try std.testing.expect(pardes.panes.terminal.bracketedPaste(p.panes[0].?));
const text = try gpa.alloc(u8, 1536 * 1024);
defer gpa.free(text);
@memset(text, 'z');
p.update(.{ .paste = text });
const got = test_api.ptyBytes(p, null, buf);
try std.testing.expect(std.mem.startsWith(u8, got, "\x1b[200~"));
try std.testing.expect(std.mem.endsWith(u8, got, "\x1b[201~"));
try std.testing.expectEqualSlices(u8, text, got["\x1b[200~".len .. got.len - "\x1b[201~".len]);
}
test "a terminal's answer to its program waits behind the paste still queued for its pty" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
const buf = try gpa.alloc(u8, 2 << 20);
defer gpa.free(buf);
_ = test_api.ptyBytes(p, null, buf);
pardes.panes.terminal.enterTty(p, 0);
const text = try gpa.alloc(u8, 1536 * 1024);
defer gpa.free(text);
@memset(text, 'p');
p.update(.{ .paste = text });
// The ring is full and the rest of the paste waits for room in it. A
// host takes one write off, and the program asks where its cursor is.
const taken = p.nextEffect().?;
const off = if (taken == .write) taken.write.bytes.len else 0;
p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[6n" } });
const got = test_api.ptyBytes(p, null, buf);
// The whole paste first, then the answer, `CSI row ; col R`, whole.
try std.testing.expectEqualSlices(u8, text[off..], got[0 .. text.len - off]);
const answer = got[text.len - off ..];
try std.testing.expect(std.mem.startsWith(u8, answer, "\x1b[") and std.mem.endsWith(u8, answer, "R"));
}
test "pasted bytes still queued at shutdown are freed, not leaked" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
const buf = try gpa.alloc(u8, 2 << 20);
defer gpa.free(buf);
_ = test_api.ptyBytes(p, null, buf);
pardes.panes.terminal.enterTty(p, 0);
const text = try gpa.alloc(u8, 1536 * 1024);
defer gpa.free(text);
@memset(text, 'q');
p.update(.{ .paste = text });
try std.testing.expect(p.pending_write_bytes > 0);
}
test "leaving tty hides the prompt and keeps the command typed at it" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc
const shell = p.view().active;
const sp = p.panes[shell].?;
try std.testing.expect(sp.isTerminal());
// Exactly what an OSC 133 shell draws: prompt, then the marker that says
// the rest of this row is the user's, then what they typed. One grid row.
p.update(.{ .output = .{
.pane = @intCast(shell),
.bytes = "\x1b]133;A\x1b\\user@box ~/src $ \x1b]133;B\x1b\\grep -rn TODO src/",
} });
p.sync();
const rowOf = struct {
fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 {
const rows = pardes.panes.terminal.shellRows(pp, pane) catch return null;
for (rows) |r| if (std.mem.indexOf(u8, r, needle) != null) return r;
return null;
}
}.at;
const bodyRowOf = struct {
fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 {
const body = pardes.panes.terminal.bodyText(pp.scratch.allocator(), pane) catch return null;
var it = std.mem.splitScalar(u8, body, '\n');
while (it.next()) |r| if (std.mem.indexOf(u8, r, needle) != null) return r;
return null;
}
}.at;
// The BODY is what you look at, and it follows the mode: in tty the pane
// is the program's own screen, so the prompt is there.
sp.body.mode = .tty;
try std.testing.expectEqualStrings(
"user@box ~/src $ grep -rn TODO src/",
bodyRowOf(p, sp, "grep") orelse return error.MissingPromptRow,
);
sp.body.mode = .normal;
try std.testing.expectEqualStrings(
"grep -rn TODO src/",
bodyRowOf(p, sp, "grep") orelse return error.MissingPromptRow,
);
p.shell_rows.stale = true;
try std.testing.expectEqualStrings(
"grep -rn TODO src/",
rowOf(p, sp, "grep") orelse return error.MissingPromptRow,
);
// ...and a prompt with nothing typed at it yet is all chrome, so the whole
// row goes, which is what it has always done.
p.update(.{ .output = .{
.pane = @intCast(shell),
.bytes = "\r\n\x1b]133;A\x1b\\user@box ~/src $ \x1b]133;B\x1b\\",
} });
p.sync();
p.shell_rows.stale = true;
try std.testing.expect(rowOf(p, sp, "user@box") == null);
}
test "entering tty walks the shell cursor to the column clicked past the prompt" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" });
defer p.deinit();
p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
p.update(.{ .key = .{ .cp = 'n', .alt = true } });
const shell = p.view().active;
const sp = p.panes[shell].?;
p.update(.{ .output = .{
.pane = @intCast(shell),
.bytes = "\x1b]133;A;cl=line\x1b\\prompt> \x1b]133;B\x1b\\0123456789",
} });
p.sync();
sp.body.mode = .normal;
p.shell_rows.stale = true;
// The command shows LEFT-HUGGED, so its column 3 is the '3'...
const rows = try pardes.panes.terminal.shellRows(p, sp);
var row: i32 = 0;
const at = for (rows, 0..) |r, i| {
if (std.mem.indexOf(u8, r, "0123456789") != null) break i;
} else return error.MissingInputRow;
row = @intCast(at);
try std.testing.expectEqualStrings("0123456789", rows[at]);
// ...but the shell's own cursor lives on the real grid, eight cells
// further right, behind the prompt this pane is not showing.
sp.body.cur_row = row;
sp.body.cur_col = 3;
sp.body.cur_pinned = true;
while (p.nextEffect()) |_| {}
pardes.panes.terminal.enterTty(p, shell);
// The walk is arrow keys the shell understands. Seven lefts: readline's
// cursor sits past the '9' and the click was on the '3'.
var lefts: usize = 0;
var rights: usize = 0;
while (p.nextEffect()) |effect| switch (effect) {
.write => |wr| {
if (std.mem.eql(u8, wr.bytes.slice(), "\x1b[D")) lefts += 1;
if (std.mem.eql(u8, wr.bytes.slice(), "\x1b[C")) rights += 1;
},
else => {},
};
try std.testing.expectEqual(@as(usize, 0), rights);
try std.testing.expectEqual(@as(usize, 7), lefts);
}
test "every allocation failure during boot is a clean OutOfMemory" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, bootAndTearDown, .{});
}
|