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
3992
3993
3994
3995
|
const filesystem = @import("../fs.zig");
const std = @import("std");
const builtin = @import("builtin");
const posix = std.posix;
const libc = std.c;
const vaxis = @import("vaxis");
const pardes = @import("../pardes.zig");
const vaxis_input = @import("../vaxis_input.zig");
const dump = @import("../dump.zig");
const tracy = @import("../tracy.zig");
const look = @import("../look.zig");
const message = pardes.Messages.Message;
const file_watch = @import("../file_watch.zig");
const selection_pipe = @import("../selection_pipe.zig");
const ninep_io = @import("../9p_io.zig");
const panel_compositor = @import("panel_compositor.zig");
const daemon = @import("../daemon.zig");
const host_io = @import("../host_io.zig");
const upgrade = @import("../upgrade.zig");
const replica = @import("../replica.zig");
const wire = @import("../detached/wire.zig");
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467));
/// What a terminal's input reader keeps, one a terminal (views.zig): its
/// graphemes, the frame it waits on the answer to, the shm probe, and the
/// view its input is.
const Feed = struct {
view: u8 = 0,
cache: vaxis.GraphemeCache = .{},
ack: FrameAck = .{},
/// The terminal answered the shared-memory probe (`kittyShmProbe`): it
/// can read a raster from a POSIX shm object, so a page costs a name on
/// the wire instead of its whole base64 body. Set by the input reader,
/// which sees the reply before vaxis' parser swallows every graphics APC
/// alike.
shm: std.atomic.Value(bool) = .init(false),
/// Only a reply that arrives while the probe is out counts. The id is
/// one vaxis' own image numbering (1, 2, ...) never reaches, because a
/// terminal answers every transmission `i=<id>;OK` and one of those must
/// not pass.
shm_probing: std.atomic.Value(bool) = .init(false),
};
/// A terminal's input onto the loop's queue, as its view's: a `from` goes
/// ahead of it whenever another terminal posted last. With one terminal
/// none ever does.
const Poster = struct {
loop: *Loop,
view: u8,
var lock: std.Io.Mutex = .init;
var last: u8 = 0;
pub fn postEvent(p: Poster, ev: @TypeOf(Command.value)) !void {
lock.lockUncancelable(p.loop.io);
defer lock.unlock(p.loop.io);
if (last != p.view) {
try p.loop.postEvent(.{ .from = p.view });
last = p.view;
}
try p.loop.postEvent(ev);
}
};
const kitty_shm_probe_id = 0x7fff_fff1;
var kitty_shm_serial: u32 = 0;
/// Transmissions an unread shm segment outlives before it is removed.
const kitty_shm_window = 64;
fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 {
return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0);
}
/// A terminal unlinks what it reads; whatever it never read (the probe
/// unanswered, a transmission lost with the terminal) is ours to remove.
fn unlinkKittyShm() void {
var name_buf: [64]u8 = undefined;
var n: u32 = 0;
while (n <= kitty_shm_serial) : (n += 1) {
if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {}
}
}
/// Write `bytes` to a fresh shm object; the terminal unlinks it after reading.
fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool {
const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600));
if (fd < 0) return false;
defer _ = libc.close(fd);
if (libc.ftruncate(fd, @intCast(bytes.len)) != 0) {
_ = libc.shm_unlink(name);
return false;
}
var off: usize = 0;
while (off < bytes.len) {
const n = libc.write(fd, bytes[off..].ptr, bytes.len - off);
if (n <= 0) {
_ = libc.shm_unlink(name);
return false;
}
off += @intCast(n);
}
return true;
}
/// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A
/// remote terminal cannot see our shm and answers an error (or nothing).
fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void {
var buf: [64]u8 = undefined;
const name = kittyShmName(&buf, 0) catch return;
if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return;
var b64: [64]u8 = undefined;
const enc = std.base64.standard.Encoder.encode(&b64, name);
feed.shm_probing.store(true, .release);
w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return;
w.flush() catch {};
}
pub const Command = struct {
pub var value: union(enum) {
nop,
/// The terminal's input ended: its end of file, a hangup. A session
/// a daemon keeps carries on detached; any other ends.
quit,
/// A terminal for this detached session, and its stub's pipe
/// (daemon.Note.attach).
attach: struct { tty: posix.fd_t, stub: posix.fd_t },
/// A shell a dead session left, its pty's master (daemon.Note.adopted).
adopted: struct { pid: posix.pid_t, fd: posix.fd_t },
/// A timed wait ran out: the core's next wake has come.
wake,
/// The input after this is the terminal of this view's (Poster).
from: u8,
/// A SIGWINCH: a terminal changed size (Shell.winched).
winched,
/// A SIGHUP: the session's own terminal hung up.
hangup,
key_press: vaxis.Key,
pty_read: struct { id: usize, gen: u32, bytes: []u8 },
pty_eof: struct { id: usize, gen: u32 },
winsize: vaxis.Winsize,
mouse: vaxis.Mouse,
focus_in,
focus_out,
paste: []const u8,
paste_start,
paste_end,
lsp_done: struct { id: u32, rows: ?[]u8 },
lsp_status: []u8,
pipe_done: selection_pipe.Response,
/// A streaming search's rows (pardes.Stream).
search_rows: pardes.Stream.Batch,
files_changed,
fs_ready,
/// A replica's connection, handed over by the daemon (Peers).
replica: posix.fd_t,
/// A replica's reader posted: the step boundary takes it in.
replica_mail,
/// A replica client's: what the session streamed (replica.Client).
unit: []u8,
/// The session's digest, asked by PARDES_REPLICA_CHECK.
checked: u64,
link_gone,
} = .nop;
};
const Loop = vaxis.Loop(@TypeOf(Command.value));
fn startInput(loop: *Loop, sc: *Screen) !void {
if (comptime builtin.os.tag == .windows) return loop.start();
if (sc.thread != null) return;
sc.thread = try loop.io.concurrent(inputThread, .{ loop, sc });
}
fn stopInput(io: std.Io, thread: *?std.Io.Future(void)) void {
if (thread.*) |*t| {
t.cancel(io);
thread.* = null;
}
}
fn inputThread(loop: *Loop, sc: *Screen) void {
// vaxis's test terminal reads nothing off Linux: it has no read at all.
if (comptime !@hasDecl(vaxis.Tty, "read")) return;
inputReader(loop, &sc.tty, &sc.vx, &sc.feed);
}
fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void {
readInput(loop, tty, vx, feed) catch |err| {
if (err == error.Canceled) return;
std.log.err("terminal input: {s}", .{@errorName(err)});
};
(Poster{ .loop = loop, .view = feed.view }).postEvent(.quit) catch {};
}
fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void {
const post: Poster = .{ .loop = loop, .view = feed.view };
try post.postEvent(.{ .winsize = try tty.getWinsize() });
var parser: vaxis.Parser = .{};
var buf: [1024]u8 = undefined;
var carried: usize = 0;
while (true) { // stopInput cancels the task; the read then fails with Canceled
if (carried == buf.len) return error.InputSequenceTooLong;
const received = try tty.read(buf[carried..]);
if (received == 0) return;
// The terminal's answers to frames (FrameAck) come out first,
// wherever they sit: never events, and never glued to a key (an
// Escape pressed just before one would read as Alt on it).
const end = feed.ack.take(buf[0 .. carried + received], loop);
if (end == 0) {
carried = 0;
continue;
}
if (feed.shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| {
feed.shm_probing.store(false, .release);
feed.shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release);
// Answered either way: a terminal that could not read it left it.
var name_buf: [64]u8 = undefined;
if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {}
};
var parse_end = end;
var lead = end;
while (lead > 0 and buf[lead - 1] & 0xc0 == 0x80) lead -= 1;
if (lead > 0) {
const scalar_len = std.unicode.utf8ByteSequenceLength(buf[lead - 1]) catch 1;
if (scalar_len > end - (lead - 1)) parse_end = lead - 1;
}
var consumed: usize = 0;
// A read that is one ESC and nothing else is the Escape key: a
// terminal writes each key's sequence whole and ssh carries each of
// its writes whole, so no sequence arrives cut right after its ESC.
// Waiting on it cost every Escape press 50 ms on a legacy terminal
// (tmux, most ssh sessions), and 1 s before kitty's flags were on.
// (A terminal's answer to a frame is one write too: FrameAck.)
var waited = carried == 0 and end == 1;
while (consumed < parse_end) {
// A lone ESC that ends a longer read is the Escape key, or the
// first byte of a sequence whose rest the read boundary held
// back (an ssh packet, a busy link), which parsed now left the
// rest to be typed as text. Wait a moment for more. Under the
// kitty keyboard protocol Escape is `CSI 27 u`, so there the ESC
// can only start a sequence and the wait can be long.
const rest = buf[consumed..parse_end];
// A frame's answer cut short by the read waits for its rest.
if (parse_end == end and rest.len > 1 and rest.len < FrameAck.answer.len and
std.mem.startsWith(u8, FrameAck.answer, rest)) break;
if (!waited and parse_end == end and rest[0] == 0x1b and (rest.len == 1 or (rest.len == 2 and rest[1] == 0x1b))) {
waited = true;
if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) break;
}
const result = try parser.parse(buf[consumed..parse_end], vx.opts.system_clipboard_allocator);
if (result.n == 0) break;
consumed += result.n;
// A modifier pressed on its own, which the kitty keyboard
// protocol reports: pardes binds none, it would break a pending
// chord, and a shell pane was typed its private-use code.
if (result.event) |event| if (event == .key_press and event.key_press.isModifier()) continue;
if (result.event) |event|
vaxis.loop.handleEventGeneric(post, vx, &feed.cache, @TypeOf(Command.value), event, vx.opts.system_clipboard_allocator) catch |err| {
if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste));
return err;
};
// The last answer to the startup queries is no event of its
// own: wake the loop so it takes the capabilities up (pollFrame)
// now. Left to the first key, that key paid for the full redraw
// they cost, and kitty's keys came in the legacy way till then.
if (result.event) |event| if (event == .cap_da1) {
_ = loop.tryPostEvent(.nop) catch {};
};
}
carried = end - consumed;
std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]);
}
}
/// One frame in flight at most. Each frame the tty draws ends with a device
/// status request (`CSI 5 n`), and no other frame is drawn until the
/// terminal's `CSI 0 n` comes back: over ssh the frames a burst of scrolling
/// or typing would queue behind each other (sshd's window holds megabytes)
/// are never drawn, and the burst ends one frame and one round trip after
/// its last input. On a local terminal the answer is back in well under a
/// millisecond. A terminal that never answers turns this off for good after
/// `timeout_ns`.
const FrameAck = struct {
const request = "\x1b[5n";
const answer = "\x1b[0n";
const timeout_ns: u64 = std.time.ns_per_s;
waiting: std.atomic.Value(bool) = .init(false),
off: std.atomic.Value(bool) = .init(false),
/// When the request went out (the loop's thread only).
sent_ns: u64 = 0,
/// Take every answer out of `bytes`, closing up the rest; the new
/// length. The loop is woken for the frame that waited on one.
fn take(a: *FrameAck, bytes: []u8, loop: *Loop) usize {
var len = bytes.len;
var found = false;
while (std.mem.indexOf(u8, bytes[0..len], answer)) |at| {
std.mem.copyForwards(u8, bytes[at..], bytes[at + answer.len .. len]);
len -= answer.len;
found = true;
}
if (found and a.waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {};
return len;
}
/// Whether a new frame must wait (and the loop has a wake at the
/// timeout); past the timeout the terminal is taken to never answer.
fn holds(a: *FrameAck, now_ns: u64, io: std.Io) bool {
if (a.off.load(.acquire) or !a.waiting.load(.acquire)) return false;
const waited_ns = now_ns -| a.sent_ns;
if (waited_ns >= timeout_ns) {
a.off.store(true, .release);
a.waiting.store(false, .release);
return false;
}
requestWake(io, @intCast((timeout_ns - waited_ns + std.time.ns_per_ms - 1) / std.time.ns_per_ms));
return true;
}
/// After a frame that wrote something: ask for the answer.
fn ask(a: *FrameAck, w: *std.Io.Writer, now_ns: u64) void {
if (a.off.load(.acquire)) return;
// Waiting before the request goes: a local terminal can answer
// before the write returns, and an answer nobody waited for is lost.
a.sent_ns = now_ns;
a.waiting.store(true, .release);
w.writeAll(request) catch return a.waiting.store(false, .release);
w.flush() catch return a.waiting.store(false, .release);
}
};
/// Whether more input is readable within `ms`, polled in short slices so
/// that a cancel of the input thread is still seen. A test reader answers
/// for itself.
fn inputFollows(tty: anytype, io: std.Io, ms: u32) !bool {
if (@hasDecl(@TypeOf(tty.*), "inputFollows")) return tty.inputFollows(ms);
const handle = if (@TypeOf(tty.fd) == std.Io.File) tty.fd.handle else tty.fd;
var fds = [_]posix.pollfd{.{ .fd = handle, .events = posix.POLL.IN, .revents = 0 }};
var left = ms;
while (left > 0) : (left -|= 10) {
try io.checkCancel();
if (try posix.poll(&fds, @intCast(@min(left, 10))) > 0) return true;
}
return false;
}
test "terminal input preserves fragmented keys queries paste and text after EOF" {
if (comptime builtin.os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa });
var output: std.Io.Writer.Allocating = .init(gpa);
defer output.deinit();
defer vx.deinit(gpa, &output.writer);
vx.queries_done.store(false, .unordered);
var tty: vaxis.Tty = undefined;
var loop: Loop = .init(io, &tty, &vx);
var feed: Feed = .{};
const Reader = struct {
parts: []const []const u8,
next: usize = 0,
fn getWinsize(_: *@This()) !vaxis.Winsize {
return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
}
pub fn inputFollows(self: *@This(), _: u32) bool {
return self.next < self.parts.len;
}
fn read(self: *@This(), buf: []u8) !usize {
if (self.next == self.parts.len) return 0;
const part = self.parts[self.next];
self.next += 1;
@memcpy(buf[0..part.len], part);
return part.len;
}
};
var reader: Reader = .{ .parts = &.{
"plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95",
"\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b",
} };
try readInput(&loop, &reader, &vx, &feed);
try std.testing.expect(vx.queries_done.load(.unordered));
var text: std.ArrayList(u8) = .empty;
defer text.deinit(gpa);
var resized = false;
var up = false;
var in_paste = false;
var pasted = false;
var clipboard = false;
var escape = false;
while (try loop.tryEvent()) |event| switch (event) {
.winsize => |size| {
try std.testing.expect(!resized);
resized = true;
try std.testing.expectEqual(@as(u16, 80), size.cols);
},
.key_press => |key| {
try std.testing.expect(resized);
if (key.codepoint == vaxis.Key.up) {
up = true;
} else if (key.codepoint == vaxis.Key.escape) {
escape = true;
} else if (key.text) |bytes| {
if (in_paste) try std.testing.expect(up);
try text.appendSlice(gpa, bytes);
} else return error.UnexpectedInputKey;
},
.paste_start => {
try std.testing.expect(up and !in_paste);
in_paste = true;
},
.paste_end => {
try std.testing.expect(in_paste);
in_paste = false;
pasted = true;
},
.paste => |bytes| {
defer gpa.free(@constCast(bytes));
try std.testing.expect(pasted and !in_paste);
try std.testing.expectEqualStrings("clip", bytes);
clipboard = true;
},
// The device attributes' wake (a capability answer).
.nop => try std.testing.expect(vx.queries_done.load(.unordered)),
else => return error.UnexpectedInputEvent,
};
try std.testing.expectEqualStrings("plain café 界 😀tail", text.items);
try std.testing.expect(resized and up and pasted and clipboard and escape);
}
test "terminal replies and malformed sequences never become typed text" {
if (comptime builtin.os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa });
var output: std.Io.Writer.Allocating = .init(gpa);
defer output.deinit();
defer vx.deinit(gpa, &output.writer);
vx.queries_done.store(false, .unordered);
var tty: vaxis.Tty = undefined;
var loop: Loop = .init(io, &tty, &vx);
var feed: Feed = .{};
const Reader = struct {
parts: []const []const u8,
next: usize = 0,
fn getWinsize(_: *@This()) !vaxis.Winsize {
return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
}
pub fn inputFollows(self: *@This(), _: u32) bool {
return self.next < self.parts.len;
}
fn read(self: *@This(), buf: []u8) !usize {
if (self.next == self.parts.len) return 0;
const part = self.parts[self.next];
self.next += 1;
@memcpy(buf[0..part.len], part);
return part.len;
}
};
var reader: Reader = .{
.parts = &.{
// The startup width queries' answers where the terminal has no
// explicit width: both used to arrive as a bare F3, typed as text.
"a\x1b[1;1R\x1b[1;1R",
// A late report somewhere else on the screen, and DECXCPR.
"\x1b[12;40R\x1b[?3;7;1R",
// rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`.
"b\x1b\x1b[A",
// A kitty graphics reply cut inside its ST sliced past its input.
"\x1b_Gi=1;OK\x1b",
"\\",
// An X10 mouse report cut after `CSI M` left three bytes as text.
"\x1b[M",
" !!",
// Malformed color and clipboard replies failed the parse, which
// ended input altogether; and a reply ended by BEL ran on to the
// next sequence's ESC, leaving what lay between as text.
"\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07",
// Device reports whose fields end early.
"\x1b[?1;y\x1b[?997;n\x1b[c",
"\x1b[?62;c",
"c",
},
};
try readInput(&loop, &reader, &vx, &feed);
try std.testing.expect(vx.queries_done.load(.unordered));
try std.testing.expect(vx.caps.kitty_graphics);
var text: std.ArrayList(u8) = .empty;
defer text.deinit(gpa);
var alt_up = false;
var clicked = false;
while (try loop.tryEvent()) |event| switch (event) {
.winsize => {},
.key_press => |key| {
if (key.codepoint == vaxis.Key.up and key.mods.alt) {
alt_up = true;
} else if (key.text) |bytes| {
try text.appendSlice(gpa, bytes);
} else return error.UnexpectedInputKey;
},
.mouse => |mouse| {
try std.testing.expectEqual(@as(i16, 0), mouse.col);
clicked = true;
},
.nop => {}, // the device attributes' wake
else => return error.UnexpectedInputEvent,
};
try std.testing.expectEqualStrings("abc", text.items);
try std.testing.expect(alt_up and clicked);
}
test "terminal input split at every byte with a gap reads as it does whole" {
if (comptime builtin.os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa });
var output: std.Io.Writer.Allocating = .init(gpa);
defer output.deinit();
defer vx.deinit(gpa, &output.writer);
var tty: vaxis.Tty = undefined;
var loop: Loop = .init(io, &tty, &vx);
var feed: Feed = .{};
// Two reads with `gap_ms` between them, as an ssh link delivers a
// sequence cut across two packets.
const Reader = struct {
parts: [2][]const u8,
gap_ms: u32,
next: usize = 0,
fn getWinsize(_: *@This()) !vaxis.Winsize {
return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
}
pub fn inputFollows(self: *@This(), ms: u32) bool {
return self.next < self.parts.len and self.gap_ms <= ms;
}
fn read(self: *@This(), buf: []u8) !usize {
while (self.next < self.parts.len) {
const part = self.parts[self.next];
self.next += 1;
if (part.len == 0) continue;
@memcpy(buf[0..part.len], part);
return part.len;
}
return 0;
}
/// What the loop was handed, one line per event.
fn events(l: *Loop, out: *std.ArrayList(u8)) !void {
out.clearRetainingCapacity();
while (try l.tryEvent()) |event| switch (event) {
.winsize => {},
.key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }),
.mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }),
.paste => |bytes| {
try out.print(std.testing.allocator, "paste {s}\n", .{bytes});
std.testing.allocator.free(@constCast(bytes));
},
else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}),
};
}
};
const Case = struct { bytes: []const u8, kitty: bool = false };
const cases = [_]Case{
.{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V
.{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text
.{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own
.{ .bytes = "\x1b[27u", .kitty = true }, // Escape
.{ .bytes = "\x1b[A" },
.{ .bytes = "\x1bOA" },
.{ .bytes = "\x1b[3;5~" },
.{ .bytes = "\x1b\x1b[A" },
// Four wheel notches: cut at a `;` with 60 ms between the halves,
// ssh's framing lost all four.
.{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" },
.{ .bytes = "\x1b[200~pasted\x1b[201~" },
.{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" },
.{ .bytes = "\x1b_Gi=1;OK\x1b\\" },
.{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" },
};
var whole: std.ArrayList(u8) = .empty;
defer whole.deinit(gpa);
var split: std.ArrayList(u8) = .empty;
defer split.deinit(gpa);
for (cases) |case| {
vx.caps.kitty_keyboard = case.kitty;
const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" });
defer gpa.free(all);
var one: Reader = .{ .parts = .{ all, "" }, .gap_ms = 0 };
try readInput(&loop, &one, &vx, &feed);
try Reader.events(&loop, &whole);
for (1..all.len) |cut| {
// A cut just after an ESC is the one that has to wait, and a
// legacy terminal's Escape waits only 50 ms: 40 ms there. A cut
// anywhere else is carried however long the gap.
const after_esc = all[cut - 1] == 0x1b;
var two: Reader = .{ .parts = .{ all[0..cut], all[cut..] }, .gap_ms = if (after_esc and !case.kitty) 40 else 60 };
try readInput(&loop, &two, &vx, &feed);
try Reader.events(&loop, &split);
std.testing.expectEqualStrings(whole.items, split.items) catch |err| {
std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut });
return err;
};
}
}
vx.caps.kitty_keyboard = false;
}
test "an ESC read by itself is the Escape key at once" {
if (comptime builtin.os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(io, gpa, &env, .{});
var output: std.Io.Writer.Allocating = .init(gpa);
defer output.deinit();
defer vx.deinit(gpa, &output.writer);
var tty: vaxis.Tty = undefined;
var loop: Loop = .init(io, &tty, &vx);
var feed: Feed = .{};
// More always follows at once: a reader that waited on the ESC would
// take `j` for the rest of its sequence (Alt-j).
const Reader = struct {
parts: []const []const u8,
next: usize = 0,
asked: bool = false,
fn getWinsize(_: *@This()) !vaxis.Winsize {
return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
}
pub fn inputFollows(self: *@This(), _: u32) bool {
self.asked = true;
return self.next < self.parts.len;
}
fn read(self: *@This(), buf: []u8) !usize {
if (self.next == self.parts.len) return 0;
const part = self.parts[self.next];
self.next += 1;
@memcpy(buf[0..part.len], part);
return part.len;
}
};
for ([_]bool{ false, true }) |kitty| {
vx.caps.kitty_keyboard = kitty;
var reader: Reader = .{ .parts = &.{ "\x1b", "j" } };
try readInput(&loop, &reader, &vx, &feed);
try std.testing.expect(!reader.asked);
try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?));
const escape = (try loop.tryEvent()).?.key_press;
try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
try std.testing.expect(!escape.mods.alt);
const j = (try loop.tryEvent()).?.key_press;
try std.testing.expectEqual(@as(u21, 'j'), j.codepoint);
try std.testing.expect(!j.mods.alt);
try std.testing.expect(try loop.tryEvent() == null);
}
vx.caps.kitty_keyboard = false;
}
test "a frame's answer is taken wherever the reads cut it, and never typed" {
if (comptime builtin.os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(io, gpa, &env, .{});
var output: std.Io.Writer.Allocating = .init(gpa);
defer output.deinit();
defer vx.deinit(gpa, &output.writer);
var tty: vaxis.Tty = undefined;
var loop: Loop = .init(io, &tty, &vx);
var feed: Feed = .{};
const Reader = struct {
parts: [2][]const u8,
next: usize = 0,
fn getWinsize(_: *@This()) !vaxis.Winsize {
return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
}
pub fn inputFollows(self: *@This(), _: u32) bool {
return self.next < self.parts.len;
}
fn read(self: *@This(), buf: []u8) !usize {
while (self.next < self.parts.len) {
const part = self.parts[self.next];
self.next += 1;
if (part.len == 0) continue;
@memcpy(buf[0..part.len], part);
return part.len;
}
return 0;
}
};
const all = "x" ++ FrameAck.answer ++ "y";
defer feed.ack.waiting.store(false, .release);
for (0..all.len) |cut| {
feed.ack.waiting.store(true, .release);
var reader: Reader = .{ .parts = .{ all[0..cut], all[cut..] } };
try readInput(&loop, &reader, &vx, &feed);
try std.testing.expect(!feed.ack.waiting.load(.acquire));
var typed: std.ArrayList(u8) = .empty;
defer typed.deinit(gpa);
var woke = false;
while (try loop.tryEvent()) |event| switch (event) {
.winsize => {},
.nop => woke = true,
.key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey),
else => return error.UnexpectedInputEvent,
};
std.testing.expectEqualStrings("xy", typed.items) catch |err| {
std.debug.print("cut at {d}\n", .{cut});
return err;
};
try std.testing.expect(woke);
}
// An Escape pressed just before an answer, in the same read, is the
// Escape key, not Alt on the answer.
feed.ack.waiting.store(true, .release);
var glued: Reader = .{ .parts = .{ "\x1b" ++ FrameAck.answer, "j" } };
try readInput(&loop, &glued, &vx, &feed);
try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?));
try std.testing.expectEqual(.nop, std.meta.activeTag((try loop.tryEvent()).?));
const escape = (try loop.tryEvent()).?.key_press;
try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
try std.testing.expect(!escape.mods.alt);
try std.testing.expectEqual(@as(u21, 'j'), (try loop.tryEvent()).?.key_press.codepoint);
try std.testing.expect(try loop.tryEvent() == null);
}
test "a terminal that never answers a frame stops being asked after one timeout" {
const io = std.testing.io;
var ack: FrameAck = .{};
var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer out.deinit();
const t0: u64 = 5 * std.time.ns_per_s;
ack.ask(&out.writer, t0);
try std.testing.expectEqualStrings(FrameAck.request, out.written());
// Unanswered: the next frame waits, until the timeout.
try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io));
try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io));
try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io));
// Then never again: no request, no wait.
out.clearRetainingCapacity();
ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s);
try std.testing.expectEqual(@as(usize, 0), out.written().len);
try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io));
}
test "terminal input cancellation joins blocked reads and queued EOF" {
if (comptime builtin.os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(io, gpa, &env, .{});
var output: std.Io.Writer.Allocating = .init(gpa);
defer output.deinit();
defer vx.deinit(gpa, &output.writer);
const Reader = struct {
file: std.Io.File,
eof: bool,
entered: std.Io.Event = .unset,
release: std.Io.Event = .unset,
returned: std.Io.Event = .unset,
fn getWinsize(_: *@This()) !vaxis.Winsize {
return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
}
pub fn inputFollows(_: *@This(), _: u32) bool {
return false;
}
fn read(self: *@This(), buf: []u8) !usize {
self.entered.set(std.testing.io);
if (self.eof) {
try self.release.wait(std.testing.io);
self.returned.set(std.testing.io);
return 0;
}
return self.file.readStreaming(std.testing.io, &.{buf});
}
fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void {
inputReader(loop, reader, vx_, feed);
}
};
const Case = enum { blocked_read, cancel_eof, deliver_eof };
for (std.enums.values(Case)) |case| {
const eof = case != .blocked_read;
var fds: [2]c_int = undefined;
if (libc.pipe(&fds) != 0) return error.PipeFailed;
defer _ = libc.close(fds[0]);
defer _ = libc.close(fds[1]);
var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof };
var tty: vaxis.Tty = undefined;
var loop: Loop = .init(io, &tty, &vx);
var feed: Feed = .{};
var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &vx, &feed });
defer stopInput(io, &thread);
try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent()));
try reader.entered.wait(io);
if (eof) {
for (0..512) |_| try loop.postEvent(.nop);
reader.release.set(io);
try reader.returned.wait(io);
}
if (case == .deliver_eof) {
try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent()));
thread.?.await(io);
}
stopInput(io, &thread);
try std.testing.expect(thread == null);
var count: usize = 0;
while (try loop.tryEvent()) |event| {
const expected: std.meta.Tag(@TypeOf(Command.value)) = if (case == .deliver_eof and count == 511) .quit else .nop;
try std.testing.expectEqual(expected, std.meta.activeTag(event));
count += 1;
}
try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count);
}
}
const PipeTasks = selection_pipe.Tasks;
const Pty = struct {
file: std.Io.File,
pid: posix.pid_t,
reader: std.Io.Future(anyerror!void),
/// A command pane's child, watched to its exit (host_io.watchExit);
/// the pty stays open until both its end of file and its exit.
cmd: host_io.CommandWatch = .{},
};
/// A watched child exited: wake the loop, which takes it (`takeExits`).
fn wakeForExit(ctx: ?*anyopaque) void {
const loop: *Loop = @ptrCast(@alignCast(ctx.?));
_ = loop.tryPostEvent(.nop) catch {};
}
const KittyPlacement = struct {
cell_x: u16,
cell_y: u16,
cell_cols: u16,
cell_rows: u16,
options: vaxis.Image.DrawOptions,
};
fn terminalCellPixels(total_pixels: u16, cells: u16, fallback: u32) u32 {
if (total_pixels == 0 or cells == 0) return fallback;
return @max(1, @as(u32, total_pixels) / cells);
}
fn updateCoreTerminalSize(core: *pardes.Pardes, cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) void {
core.update(.{ .resize = terminalSize(cols, rows, pixel_w, pixel_h) });
}
fn terminalSize(cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) @FieldType(pardes.Event, "resize") {
return .{
.cols = cols,
.rows = rows,
.cell_pixels = .{
.w = @intCast(terminalCellPixels(pixel_w, cols, 8)),
.h = @intCast(terminalCellPixels(pixel_h, rows, 16)),
},
};
}
/// A terminal pane's image fragment (`native.exact`): its `src` into its
/// `dst`, inside one cell row. Kitty scales a source rectangle to whole
/// cells, so the source is trimmed to the cells' scale rather than the
/// picture stretched: a fragment loses under a cell at its right edge.
/// A full row is declared one row high; a part of one (an image's top or
/// bottom edge) only its columns, its height then following the source.
fn exactKittyPlacement(
place: pardes.ImagePlace,
screen_cols: u16,
screen_rows: u16,
screen_pixel_w: u16,
screen_pixel_h: u16,
) ?KittyPlacement {
if (comptime !pardes.pdf_enabled) return null;
const g = place.native.geometry orelse return null;
const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8);
const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16);
if (g.dst.w == 0 or g.dst.h == 0 or g.src.w == 0 or g.src.h == 0) return null;
const cell_x = g.dst.x / cell_w;
const pixel_x = g.dst.x % cell_w;
const pixel_y = @min(g.dst.y, cell_h - 1);
const cols: u32 = @max(1, (g.dst.w + cell_w / 2) / cell_w);
if (cell_x >= place.w) return null;
const declared_w = cols * cell_w;
// At the cells' scale, the source that fills `cols` cells.
var src_w = g.src.w;
if (declared_w < g.dst.w) src_w = @max(1, @as(u32, @intCast(@as(u64, g.src.w) * declared_w / g.dst.w)));
var src_h = g.src.h;
const full = g.dst.y == 0 and g.dst.h >= cell_h;
if (!full) {
// As tall as it is at that scale, and no taller than the row.
const room = cell_h - pixel_y;
const fits: u32 = @intCast(@as(u64, room) * src_w / declared_w);
if (fits == 0) return null;
src_h = @min(src_h, fits);
}
return .{
.cell_x = std.math.cast(u16, cell_x) orelse return null,
.cell_y = 0,
.cell_cols = std.math.cast(u16, @min(@as(u32, place.w) - cell_x, (pixel_x + declared_w + cell_w - 1) / cell_w)) orelse return null,
.cell_rows = 1,
.options = .{
.clip_region = .{
.x = std.math.cast(u16, g.src.x) orelse return null,
.y = std.math.cast(u16, g.src.y) orelse return null,
.width = std.math.cast(u16, src_w) orelse return null,
.height = std.math.cast(u16, src_h) orelse return null,
},
.pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = @intCast(pixel_x), .y = @intCast(pixel_y) } else null,
// The outer terminal stacks them, under the text below 0.
.z_index = if (place.z != 0) place.z else null,
.size = if (full)
.{ .cols = std.math.cast(u16, cols) orelse return null, .rows = 1 }
else
.{ .cols = std.math.cast(u16, cols) orelse return null },
},
};
}
fn kittyPlacement(
place: pardes.ImagePlace,
screen_cols: u16,
screen_rows: u16,
screen_pixel_w: u16,
screen_pixel_h: u16,
) ?KittyPlacement {
if (comptime pardes.pdf_enabled) {
if (place.native.fit == .contain) return null;
const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8);
const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16);
const body_w = std.math.mul(u32, place.w, cell_w) catch return null;
const body_h = std.math.mul(u32, place.h, cell_h) catch return null;
const geometry = place.native.geometry orelse pardes.image.nativeGeometry(
place.iw,
place.ih,
body_w,
body_h,
place.native.fit,
place.native.pan_x,
place.native.pan_y,
) orelse return null;
const safe_rows_u32 = geometry.dst.h / cell_h;
if (safe_rows_u32 == 0) return null;
const safe_pixel_h = safe_rows_u32 * cell_h;
var safe_src_h: u32 = geometry.src.h;
var declared_cols: u32 = 0;
var declared_rows: u32 = 0;
switch (place.native.fit) {
.width => {
declared_cols = @intCast(@max(
@as(u64, 1),
(@as(u64, geometry.dst.w) + cell_w - 1) / cell_w,
));
const declared_pixel_w = @as(u64, declared_cols) * cell_w;
const max_src_h: u32 = @intCast(
@as(u64, safe_pixel_h) * geometry.src.w / declared_pixel_w,
);
if (max_src_h == 0) return null;
safe_src_h = @min(safe_src_h, max_src_h);
const aspect_pixel_h: u32 = @intCast(
(@as(u64, safe_src_h) * declared_pixel_w + geometry.src.w - 1) /
geometry.src.w,
);
declared_rows = @intCast(
(@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h,
);
},
.height => {
declared_rows = safe_rows_u32;
safe_src_h = @max(@as(u32, 1), @as(u32, @intCast(
@as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h,
)));
safe_src_h = @min(safe_src_h, geometry.src.h);
const aspect_pixel_w: u32 = @intCast(
(@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) /
safe_src_h,
);
declared_cols = @intCast(
(@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w,
);
},
.contain => unreachable,
}
if (declared_rows == 0 or declared_rows > safe_rows_u32) return null;
const src_x = std.math.cast(u16, geometry.src.x) orelse return null;
const src_y = std.math.cast(u16, geometry.src.y) orelse return null;
const src_w = std.math.cast(u16, geometry.src.w) orelse return null;
const src_h = std.math.cast(u16, safe_src_h) orelse return null;
const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null;
const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null;
if (cell_x >= place.w or cell_y >= place.h) return null;
const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null;
const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null;
const cell_cols = std.math.cast(u16, @min(
@as(u32, place.w - cell_x),
(@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w,
)) orelse return null;
const cell_rows = std.math.cast(u16, @min(
@as(u32, place.h - cell_y),
(@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h,
)) orelse return null;
if (cell_cols == 0 or cell_rows == 0) return null;
return .{
.cell_x = cell_x,
.cell_y = cell_y,
.cell_cols = cell_cols,
.cell_rows = cell_rows,
.options = .{
.clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h },
.pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null,
.size = switch (place.native.fit) {
.width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null },
.height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null },
.contain => unreachable,
},
},
};
} else {
return null;
}
}
test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" {
if (comptime !pardes.pdf_enabled) return;
var place = pardes.ImagePlace{
.pane = 0,
.serial = 3,
.native = .{ .page = 7, .exact = true, .geometry = .{
.src = .{ .x = 0, .y = 40, .w = 240, .h = 20 },
.dst = .{ .x = 0, .y = 0, .w = 240, .h = 20 },
} },
.x = 99,
.y = 4,
.w = 24,
.h = 1,
.rgba = &.{},
.iw = 240,
.ih = 160,
};
// 10x20 pixel cells: a whole row, one to one.
const full = exactKittyPlacement(place, 100, 30, 1000, 600).?;
try std.testing.expectEqual(@as(u16, 0), full.cell_x);
try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols);
try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows);
try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y);
try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width);
try std.testing.expect(full.options.pixel_offset == null);
// The top of a letterboxed picture: 7 pixels down into the row, 13
// tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns
// only, its source no taller than the 13 pixels left in the row at
// that scale.
place.native.geometry = .{
.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 },
.dst = .{ .x = 35, .y = 7, .w = 205, .h = 13 },
};
const top = exactKittyPlacement(place, 100, 30, 1000, 600).?;
try std.testing.expectEqual(@as(u16, 3), top.cell_x);
try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x);
try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y);
try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols);
try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows);
const w = top.options.clip_region.?.width.?;
const h = top.options.clip_region.?.height.?;
try std.testing.expectEqual(@as(u16, 205), w);
try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13);
// Narrower than its cells round to: the source is cut to their scale.
place.native.geometry = .{
.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 },
.dst = .{ .x = 0, .y = 0, .w = 204, .h = 20 },
};
const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?;
try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols);
try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width);
}
test "Kitty PDF fragments never declare pixels beyond their clipped bottom" {
if (comptime !pardes.pdf_enabled) return;
const base = pardes.ImagePlace{
.pane = 0,
.serial = 1,
.native = .{
.revision = 1,
.page = 0,
.fit = .width,
.geometry = .{
.src = .{ .w = 96, .h = 10 },
.dst = .{ .y = 195, .w = 304, .h = 29 },
},
},
.x = 0,
.y = 0,
.w = 38,
.h = 14,
.rgba = &.{},
.iw = 96,
.ih = 64,
};
const width = kittyPlacement(base, 80, 16, 640, 256) orelse
return error.MissingSafeKittyWidthFragment;
const width_clip = width.options.clip_region.?;
const width_size = width.options.size.?;
try std.testing.expectEqual(@as(u16, 5), width_clip.height.?);
try std.testing.expectEqual(@as(u16, 38), width_size.cols.?);
try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y);
const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? +
width_clip.width.? - 1) / width_clip.width.?;
const inferred_rows = (aspect_pixels + 15) / 16;
try std.testing.expect(inferred_rows * 16 <= base.native.geometry.?.dst.h);
var height = base;
height.native.fit = .height;
height.native.geometry.?.src.h = 9;
const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse
return error.MissingSafeKittyHeightFragment;
try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?);
try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <=
height.native.geometry.?.dst.h);
height.native.geometry.?.dst.h = 13;
try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null);
}
test "host watch closes initial race and reloads rename-over PDF while idle" {
if (comptime !file_watch.supported or !pardes.pdf_enabled) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const original = try pardes.pdf.makeOutlineTestPdf(gpa);
defer gpa.free(original);
const replacement = try pardes.pdf.makeNoOutlineTestPdf(gpa);
defer gpa.free(replacement);
try tmp.dir.writeFile(io, .{ .sub_path = "live.pdf", .data = original });
try tmp.dir.writeFile(io, .{ .sub_path = "initial.pdf", .data = replacement });
try tmp.dir.writeFile(io, .{ .sub_path = "live-replacement.pdf", .data = original });
var path_buf: [256]u8 = undefined;
const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/live.pdf", .{tmp.sub_path});
const fd = file_watch.init(true);
if (fd < 0) return error.WatchInitFailed;
defer _ = libc.close(fd);
var watches: file_watch.Table = @splat(null);
defer for (0..pardes.MAX_PANES) |id| file_watch.watchPane(
fd,
&watches,
@intCast(id),
null,
0,
.{ .text = 0 },
);
const core = try pardes.Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
defer core.deinit();
try std.testing.expectEqual(@as(usize, 3), core.panes[0].?.pdf.?.page_count);
try tmp.dir.rename("initial.pdf", tmp.dir, "live.pdf", io);
var armed = false;
while (core.nextEffect()) |effect| switch (effect) {
.watch => |watch| if (watch.pane == 0 and watch.on) {
armed = true;
try std.testing.expect(!file_watch.applyEffect(core, io, fd, &watches, 0, true, watch.mode));
},
else => {},
};
try std.testing.expect(armed and watches[0] != null);
try std.testing.expectEqual(@as(usize, 1), core.panes[0].?.pdf.?.page_count);
try tmp.dir.rename("live-replacement.pdf", tmp.dir, "live.pdf", io);
try std.testing.expect(file_watch.drain(fd));
try std.testing.expect(!file_watch.reloadChanged(core, io, gpa, &watches));
const pane = core.panes[0].?;
try std.testing.expectEqual(@as(usize, 3), pane.pdf.?.page_count);
const disk_identity = try file_watch.identify(io, path);
switch (watches[0].?.generation) {
.pdf => |accepted| try std.testing.expect(accepted != null and accepted.?.eql(disk_identity)),
.text => return error.PdfWatchStoredTextGeneration,
}
try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "reloaded") != null);
core.native_images = true;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
const surface = try core.render(frame.allocator());
try std.testing.expect(surface.nimages > 0);
try std.testing.expectEqual(@as(u32, 0), surface.images[0].?.native.page);
}
fn kittyImageRepresentable(place: pardes.ImagePlace) bool {
return place.iw > 0 and place.ih > 0 and
place.iw <= std.math.maxInt(u16) and place.ih <= std.math.maxInt(u16);
}
fn surfaceHasKittyKey(surface: *const pardes.Surface, key: pardes.ImageCacheKey) bool {
for (surface.images[0..surface.nimages]) |maybe| {
const place = maybe orelse continue;
if (comptime pardes.pdf_enabled) if (!kittyImageRepresentable(place)) continue;
if (place.cacheKey().eql(key)) return true;
}
return false;
}
const PdfWheelTarget = struct { pane: usize, page: usize };
fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWheelTarget {
if (comptime !pardes.pdf_enabled) return null;
if (!core.native_images or mouse.type != .press or
(mouse.button != .wheel_up and mouse.button != .wheel_down) or
mouse.col < 0 or mouse.row < 0) return null;
const col: u16 = @intCast(mouse.col);
const row: u16 = @intCast(mouse.row);
for (core.panes, 0..) |slot, id| {
const pane = slot orelse continue;
const rect = core.rects[id];
if (col < rect.x or col >= rect.x + rect.w or
row < rect.y or row >= rect.y + rect.h) continue;
const page = pane.pdfPage() orelse return null;
return .{ .pane = id, .page = page };
}
return null;
}
/// Where a session's terminal comes from: /dev/tty, as a plain `pardes`
/// opens it; one open already (a session forked off its stub,
/// daemon.forkSession); or none, until one is attached (`--detach`).
/// The terminal a session starts on: /dev/tty, one its stub opened (an
/// upgraded session's is raw already, `termios` the cooked one), or none.
pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, none };
pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
const io = init.io;
const gpa = init.gpa;
var winch_set = posix.sigemptyset();
posix.sigaddset(&winch_set, posix.SIG.WINCH);
// Kept by a daemon, a hangup is the terminal's end, not the session's:
// winchWatch takes it, and the session carries on detached.
if (daemon.link >= 0) posix.sigaddset(&winch_set, posix.SIG.HUP);
// FreeBSD drops a signal whose action is to be ignored (WINCH's
// default) as it is sent, sigwait or not: a handler keeps it.
if (comptime builtin.os.tag == .freebsd)
posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null);
posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null);
var tty_buf: [0x10000]u8 = undefined;
var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true };
defer screen.kitty.deinit();
switch (term) {
.open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)),
.fd => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)),
.none => {},
}
defer screen.leave();
var paste_buf: std.Io.Writer.Allocating = .init(gpa);
defer paste_buf.deinit();
var loop: Loop = .init(io, &screen.tty, &screen.vx);
try localSession(init, opts, &screen, &loop, &paste_buf);
}
/// A replica client's link to its session (`remote`).
const Remote = struct {
r: *replica.Replica,
fd: posix.fd_t,
quit: bool = false,
/// The session hung up.
gone: bool = false,
/// Something to draw: an input applied, a unit taken.
dirty: bool = true,
/// The last frame was held for the terminal's answer (FrameAck).
owed: bool = false,
/// PARDES_REPLICA_CHECK=<file>: once quiet a while after a change, the
/// session's digest is asked, and whether this replica's agrees is
/// written there, a line a check.
check: ?[:0]const u8 = null,
changed: bool = false,
asked: bool = false,
/// How many of its own inputs the session recorded otherwise when it
/// last drew: a frame after one that writes to the terminal is a
/// rollback that may have been seen (counted so: an upper bound, the
/// frame shows the inputs after it too).
mispredicted: u32 = 0,
visible: u32 = 0,
/// PARDES_REPLICA_STATS=<file>: how its inputs and the session's units
/// went, a line at its end (test/daemon.py, the gates).
fn writeStats(c: *Remote, path: []const u8) void {
const st = &c.r.stats;
var buf: [600]u8 = undefined;
const line = std.fmt.bufPrint(&buf, "inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d}\n", .{
st.inputs, st.speculated, st.stopped, st.units, st.fast,
c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, pct(st.spec_ns.items, 50) / 1000,
pct(st.spec_ns.items, 99) / 1000, pct(st.copy_ns.items, 50) / 1000, pct(st.copy_ns.items, 99) / 1000, pct(st.rollback_ns.items, 50) / 1000, pct(st.rollback_ns.items, 99) / 1000,
}) catch return;
var z: [4096]u8 = undefined;
const pz = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return;
const fd = libc.open(pz, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) return;
_ = libc.write(fd, line.ptr, line.len);
_ = libc.close(fd);
}
fn pct(samples: []u64, p: usize) u64 {
if (samples.len == 0) return 0;
std.mem.sort(u64, samples, {}, std.sort.asc(u64));
return samples[@min(samples.len - 1, samples.len * p / 100)];
}
/// The session's digest against this replica's, if it is quiet still.
fn checked(c: *Remote, theirs: u64) void {
c.asked = false;
const path = c.check orelse return;
if (!c.r.quiet()) return;
const mine = c.r.digest();
var buf: [96]u8 = undefined;
const line = (if (mine == theirs) std.fmt.bufPrint(&buf, "agree {x:0>16}\n", .{mine}) else std.fmt.bufPrint(&buf, "differ {x:0>16} {x:0>16}\n", .{ mine, theirs })) catch return;
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) return;
_ = libc.write(fd, line.ptr, line.len);
_ = libc.close(fd);
}
/// The client's own view drawn on its terminal, outside any step: the
/// replica's digest stays the session's (views.drawOne). What the host
/// writes in the core as it presents (a frame skipped, one owed) is put
/// back, as the frame statistics are this process's.
fn draw(c: *Remote, s: *Shell) void {
const core = c.r.core();
const skipped = core.present_skipped;
const needs = core.needs_frame;
core.frames.mark_start = pardes.FrameStats.nowNs();
core.frames.mark_update = core.frames.mark_start;
c.r.draw(.{ .ctx = s, .f = Shell.present });
core.frames.mark_render = core.frames.mark_update;
if (c.r.stats.mispredicted > c.mispredicted) {
c.mispredicted = c.r.stats.mispredicted;
if (core.frames.bytes > 0) c.visible += 1;
}
c.owed = core.present_skipped;
core.frames.record(pardes.FrameStats.nowNs(), false, c.owed);
core.present_skipped = skipped;
core.needs_frame = needs;
c.dirty = false;
}
};
/// The session's stream, onto the loop: its units, and its end.
fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loop: *Loop, done: *std.atomic.Value(bool)) void {
defer done.store(true, .release);
const Take = struct {
fn take(l: *Loop, tag: u8, payload: []const u8) bool {
const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false;
switch (t) {
.unit => {
const bytes = std.heap.c_allocator.dupe(u8, payload) catch return false;
l.postEvent(.{ .unit = bytes }) catch std.heap.c_allocator.free(bytes);
},
.check => {
const d = (wire.decodeServer(tag, payload) catch return false).check;
l.postEvent(.{ .checked = d }) catch {};
},
.refused => return false,
// ponytail: a terminal's delta (rterm's, src/screen_state.zig)
// applies here once terminals cross as screens.
.screen, .pong, .welcome, .dump => {},
}
return true;
}
};
replica.readStream(gpa, fd, rest, loop, Take.take);
loop.postEvent(.link_gone) catch {};
}
/// `pardes --attach=<socket>:<session>` (and `<host>:<session>`, through
/// ssh, main.zig): this terminal a replica client of a session elsewhere
/// (docs/next-daemon.md, "Phase 5 part B notes"). Its own core, loaded
/// from the session's dump, applies its keys at once (src/replica.zig);
/// the session's units are the truth it rolls back to. Its own view of the
/// session is drawn here, as the session draws its terminals'.
pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8) !void {
const io = init.io;
const gpa = init.gpa;
var why: [600]u8 = @splat(0);
var joined = replica.dial(gpa, path, session, &why) orelse {
var said: [700]u8 = undefined;
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: {s}\n", .{std.mem.sliceTo(&why, 0)}) catch "pardes: --attach failed\n") catch {};
std.process.exit(1);
};
defer _ = libc.close(joined.fd);
defer joined.rest.deinit(gpa);
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
pardes.image.start(io, allocs.image);
if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf);
pardes.syntax.start(allocs.tree_sitter);
defer {
pardes.image.stop();
if (comptime pardes.pdf_enabled) pardes.pdf.stop();
pardes.syntax.stop();
}
var o = opts;
o.image_allocator = allocs.image;
o.pdf_allocator = allocs.pdf;
const r = replica.Replica.initDump(gpa, joined.client, joined.view, joined.dump, o) catch |err| {
gpa.free(joined.dump);
var said: [200]u8 = undefined;
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: the session's dump would not load: {t}\n", .{err}) catch "pardes: --attach: the dump would not load\n") catch {};
std.process.exit(1);
};
gpa.free(joined.dump);
defer r.deinit();
r.gmtoff = joined.gmtoff;
if (!r.loaded(joined.digest)) {
std.Io.File.stderr().writeStreamingAll(io, "pardes: --attach: the session's dump loaded as another session (a build's dump is not complete)\n") catch {};
std.process.exit(1);
}
var winch_set = posix.sigemptyset();
posix.sigaddset(&winch_set, posix.SIG.WINCH);
if (comptime builtin.os.tag == .freebsd)
posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null);
posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null);
var tty_buf: [0x10000]u8 = undefined;
var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true };
defer screen.kitty.deinit();
try screen.enter(try vaxis.Tty.init(io, &tty_buf));
defer screen.leave();
defer screen.glide.deinit(gpa);
screen.feed.view = joined.view;
var paste_buf: std.Io.Writer.Allocating = .init(gpa);
defer paste_buf.deinit();
var loop: Loop = .init(io, &screen.tty, &screen.vx);
var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame);
defer frame_arena.deinit();
var link: Remote = .{ .r = r, .fd = joined.fd };
if (init.environ_map.get("PARDES_REPLICA_CHECK")) |file| link.check = try gpa.dupeSentinel(u8, file, 0);
defer if (link.check) |file| gpa.free(file);
var sh: Shell = .{
.io = io,
.gpa = gpa,
.lsp_gpa = allocs.lsp,
.core = r.core(),
.prompt_rcs = undefined,
.loop = &loop,
.frame = &frame_arena,
.paste_buf = &paste_buf,
.inotify_fd = -1,
.from = joined.view,
.remote = &link,
};
sh.terms[joined.view] = &screen;
try startInput(&loop, &screen);
defer stopInput(io, &screen.thread);
(try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach();
var reader_done: std.atomic.Value(bool) = .init(false);
const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done });
if (link.check != null) (try std.Thread.spawn(.{}, wakeWatch, .{ io, &loop })).detach();
try screen.vx.queryTerminalSend(screen.tty.writer());
// Its size is its view's first input.
sh.winched();
while (!link.quit) {
if (link.dirty) link.draw(&sh);
const first = (loop.tryEvent() catch null) orelse idle: {
// Idle, its frame drawn: the next key needs no copy taken.
r.ready();
break :idle loop.nextEvent() catch break;
};
var ev = first;
var batch: usize = 1;
while (true) {
_ = sh.apply(ev);
if (link.quit or (!sh.in_paste and batch >= 64)) break;
ev = (loop.tryEvent() catch null) orelse break;
batch += 1;
}
r.settle();
if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) {
screen.caps_pending = false;
screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {};
screen.vx.queueRefresh();
link.dirty = true;
}
if (link.owed) link.dirty = true;
if (link.check != null) {
// Quiet a while after a change: asked once (a wake, then the
// next quiet one).
if (first == .wake and link.changed and !link.asked and r.quiet()) {
link.changed = false;
link.asked = replica.askCheck(joined.fd);
} else if (link.changed and r.quiet()) requestWake(io, 300);
}
if (r.diverged) |reason| {
screen.leave();
var said: [700]u8 = undefined;
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: this replica diverged from '{s}': {s}\n", .{ session, reason }) catch "pardes: --attach: diverged\n") catch {};
std.process.exit(1);
}
}
if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
if (!link.gone) replica.bye(joined.fd);
// The link's reader ends with the link, posting as it goes: what it
// and the terminal posted is let go until it has.
_ = libc.shutdown(joined.fd, 2);
while (true) {
while (loop.tryEvent() catch null) |ev| switch (ev) {
.unit => |b| std.heap.c_allocator.free(b),
.paste => |b| gpa.free(@constCast(b)),
else => {},
};
if (reader_done.load(.acquire)) break;
std.Thread.yield() catch {};
}
reader.join();
if (link.gone) {
screen.leave();
var said: [300]u8 = undefined;
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: '{s}' let this client go (a Detach in it, or the session's end)\n", .{session}) catch "pardes: --attach: the session let this client go\n") catch {};
}
}
/// A terminal a session draws on, while it has one: entered (raw, the
/// alternate screen, mouse and paste reports) and left (all of it put back,
/// the terminal closed) at the session's start and end, and at a detach and
/// a reattach in between (daemon.zig). One a view (views.zig): the session's
/// own (`primary`, its stub `daemon.stub`), and one more for each terminal
/// `pardes --attach`ed while it is attached, which keeps its own.
const Screen = struct {
io: std.Io,
gpa: std.mem.Allocator,
env: *std.process.Environ.Map,
buf: []u8,
tty: vaxis.Tty = undefined,
vx: vaxis.Vaxis = undefined,
on: bool = false,
primary: bool = false,
/// The pipe to its stub, an attached one's (the primary's is daemon.stub).
stub: posix.fd_t = -1,
/// Its slot in Killed.
killed: ?usize = null,
feed: Feed = .{},
thread: ?std.Io.Future(void) = null,
kitty: std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image),
caps_pending: bool = true,
/// Its size as last taken (`Shell.resized`).
size: ?vaxis.Winsize = null,
tracks: []const pardes.animation.Track = &.{},
/// T2: the cursor's jump trail (JumpTrail).
trail: JumpTrail = .{},
/// The view's glide, the GUI's motion drawn at whole rows (anim 12).
glide: pardes.glide.Glide = .{},
/// T7: when each pane's view last moved (ThumbFlash).
flash: ThumbFlash = .{},
/// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a
/// forked session is no controlling terminal of its, which /dev/tty is.
/// An upgraded session's is raw already, `cooked` what it goes back to.
fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t, cooked: ?posix.termios) !vaxis.Tty {
if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty
const termios = cooked orelse try vaxis.Tty.makeRaw(fd);
const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } };
return .{ .io = io, .fd = file, .termios = termios, .tty_writer = file.writerStreaming(io, buf) };
}
fn enter(sc: *Screen, tty: vaxis.Tty) !void {
sc.tty = tty;
errdefer sc.tty.deinit();
sc.vx = try vaxis.init(sc.io, sc.gpa, sc.env, .{ .system_clipboard_allocator = sc.gpa });
errdefer sc.vx.deinit(sc.gpa, sc.tty.writer());
try sc.vx.enterAltScreen(sc.tty.writer());
try sc.vx.setMouseMode(sc.tty.writer(), true);
try sc.vx.setBracketedPaste(sc.tty.writer(), true);
if (comptime !builtin.is_test) {
sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios);
// What a panic puts back (vaxis.recover).
if (sc.primary) vaxis.tty.global_tty = sc.tty;
}
const view = sc.feed.view;
sc.feed = .{ .view = view };
sc.caps_pending = true;
sc.size = null;
sc.on = true;
}
fn leave(sc: *Screen) void {
if (!sc.on) return;
sc.on = false;
if (sc.killed) |slot| Killed.disarm(slot);
sc.killed = null;
clearNativeImages(&sc.kitty, &sc.vx, &sc.tty);
sc.vx.exitAltScreen(sc.tty.writer()) catch {};
sc.vx.deinit(sc.gpa, sc.tty.writer());
if (comptime !builtin.is_test) if (sc.primary) {
vaxis.tty.global_tty = null;
};
sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets
}
/// Its stub told the terminal is detached (it ends, and its shell has
/// the terminal back).
fn sayDetached(sc: *Screen) void {
if (sc.primary) return daemon.tellStubDetached();
daemon.tellDetached(sc.stub);
sc.stub = -1;
}
/// Its terminal hung up, or the stub that waits on it is gone.
fn hungUp(sc: *const Screen) bool {
const stub = if (sc.primary) daemon.stub else sc.stub;
const handle = if (@TypeOf(sc.tty.fd) == std.Io.File) sc.tty.fd.handle else sc.tty.fd;
var fds = [_]posix.pollfd{
.{ .fd = handle, .events = 0, .revents = 0 },
.{ .fd = stub, .events = 0, .revents = 0 },
};
_ = posix.poll(fds[0..if (stub >= 0) 2 else 1], 0) catch return false;
const gone = posix.POLL.HUP | posix.POLL.ERR;
return fds[0].revents & gone != 0 or (stub >= 0 and fds[1].revents & gone != 0);
}
fn setStub(sc: *Screen, fd: posix.fd_t) void {
if (sc.primary) daemon.stub = fd else sc.stub = fd;
}
};
/// SIGTERM or SIGHUP: each terminal put back as a clean exit leaves it --
/// the main screen, no mouse, paste or keyboard modes, the cursor shown,
/// cooked termios -- and then the signal's own death. A nested editor
/// killed in a pane must not leave that pane's terminal wedged.
/// Async-signal-safe: write, tcsetattr, sigaction, raise.
const Killed = struct {
var fds: [pardes.views.max]posix.fd_t = @splat(-1);
var cooked: [pardes.views.max]posix.termios = undefined;
const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[0m\x1b[?25h\x1b[?1049l";
fn arm(tty_fd: posix.fd_t, termios: posix.termios) ?usize {
const slot = std.mem.findScalar(posix.fd_t, &fds, -1) orelse return null;
cooked[slot] = termios;
fds[slot] = tty_fd;
const on: posix.Sigaction = .{ .handler = .{ .handler = handle }, .mask = posix.sigemptyset(), .flags = posix.SA.RESETHAND };
posix.sigaction(.TERM, &on, null);
// A hangup a daemon keeps the session through is winchWatch's.
if (daemon.link < 0) posix.sigaction(.HUP, &on, null);
return slot;
}
/// The terminal gone (put back, or detached): a TERM still takes the
/// socket, the prompt files and the shells with it, and leaves the
/// terminal alone.
fn disarm(slot: usize) void {
fds[slot] = -1;
}
fn handle(sig: posix.SIG) callconv(.c) void {
for (fds, &cooked) |fd, *termios| if (fd >= 0) {
_ = std.c.write(fd, reset, reset.len);
_ = std.c.tcsetattr(fd, .FLUSH, termios);
};
// The 9P socket and private prompt files go too: a killed editor
// leaves none behind. Its shells too, the daemon's dups let go.
ninep_io.unlinkOwnSocket();
host_io.Shell.unlinkOwnedRcs();
daemon.hangUp();
// SA_RESETHAND put the default back: the same signal, now fatal.
_ = std.c.raise(sig);
}
};
fn localSession(
init: std.process.Init,
opts: pardes.Options,
screen: *Screen,
loop: *Loop,
paste_buf: *std.Io.Writer.Allocating,
) !void {
const io = init.io;
const gpa = init.gpa;
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
var options = opts;
options.image_allocator = allocs.image;
options.pdf_allocator = allocs.pdf;
options.tree_sitter_allocator = allocs.tree_sitter;
options.frame_allocator = allocs.frame;
pardes.image.start(io, allocs.image);
if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf);
// Pages render on lanes off the loop (pdf_view.workers).
if (comptime pardes.pdf_enabled) pardes.panes.Pdf.workers = io;
pardes.syntax.start(allocs.tree_sitter);
defer {
pardes.image.stop();
if (comptime pardes.pdf_enabled) pardes.panes.Pdf.dropKept();
if (comptime pardes.pdf_enabled) pardes.pdf.stop();
pardes.syntax.stop();
}
var core = if (upgrade.resumed) |*rec|
try upgrade.load(gpa, allocs.pardes, options, rec)
else if (options.load_path) |lp| blk: {
const bytes = try filesystem.readFile(gpa, lp);
defer gpa.free(bytes);
break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes);
} else try pardes.Pardes.init(allocs.pardes, options);
defer core.deinit();
var prompt_rcs = host_io.Shell.prepare();
defer prompt_rcs.deinit();
var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame);
defer frame_arena.deinit();
var fs = ninep_io.start(io, gpa, core);
defer if (fs) |f| f.deinit(gpa);
var sh: Shell = .{
.io = io,
.gpa = gpa,
.lsp_gpa = allocs.lsp,
.core = core,
.prompt_rcs = &prompt_rcs,
.loop = loop,
.frame = &frame_arena,
.paste_buf = paste_buf,
.inotify_fd = file_watch.init(false),
.fs = fs,
.test_clock = host_io.testClock(),
};
sh.terms[0] = screen;
sh.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake_ctx = loop, .wake = wakeForReplica };
defer sh.peers.deinit();
// Before the core goes: each client sees its link end.
defer sh.peers.dropAll(sh.core);
pardes.lsp.setStatusSink(&sh, lspStatusSink);
host_io.setExitWake(loop, wakeForExit);
defer screen.glide.deinit(gpa);
// The terminals of the other views end with the session: each put back,
// its stub told.
defer for (&sh.terms) |*slot| if (slot.*) |sc| if (!sc.primary) {
stopInput(io, &sc.thread);
sh.dropScreen(sc, .exit);
slot.* = null;
};
defer {
host_io.setExitWake(null, null);
pardes.lsp.setStatusSink(null, null);
for (&sh.ptys) |*slot| if (slot.*) |*pt| {
pt.reader.cancel(io) catch {};
_ = libc.close(pt.file.handle);
slot.* = null;
};
for (sh.adoptions[0..sh.adoptions_len]) |a| _ = libc.close(a.fd);
if (sh.lsp_task) |*t| {
t.future.cancel(io);
sh.lsp_task = null;
}
sh.pipe_tasks.cancelAll(io);
// Its worker may be waiting on the loop's queue for room.
core.stream.cancelTask();
file_watch.stop(sh.inotify_fd);
if (sh.watch_task) |*t| {
t.cancel(io) catch {};
sh.watch_task = null;
}
if (sh.inotify_fd >= 0) {
_ = libc.close(sh.inotify_fd);
sh.inotify_fd = -1;
}
while (loop.tryEvent() catch null) |ev| switch (ev) {
.pty_read => |pr| {
tookRead(io, pr.id);
gpa.free(pr.bytes);
},
.paste => |b| gpa.free(@constCast(b)),
.lsp_done => |d| if (d.rows) |rows| allocs.lsp.free(rows),
.lsp_status => |text| allocs.lsp.free(text),
.pipe_done => |response_value| {
var response = response_value;
response.deinit(gpa);
},
.search_rows => |b| b.deinit(gpa),
.attach => |a| {
_ = libc.close(a.tty);
if (a.stub >= 0) _ = libc.close(a.stub);
},
.adopted => |a| _ = libc.close(a.fd),
else => {},
};
}
const host = sh.host();
core.host = host;
// An upgraded session's terminals, its own again.
if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec, screen);
// Nobody to see it, and nobody to size it: `size` sets it (ctl.zig).
sh.setAttended(sh.attached());
while (core.nextEffect()) |effect| core.perform(effect);
// ...and its shells, once a fresh session's own has a directory to
// adopt them in.
if (upgrade.resumed) |*rec| {
sh.resumePtys(rec);
while (core.nextEffect()) |effect| core.perform(effect);
}
if (screen.on) try startInput(loop, screen);
defer stopInput(io, &screen.thread);
(try std.Thread.spawn(.{}, winchWatch, .{loop})).detach();
(try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach();
if (fs) |f| try f.watch(loop, wakeFs);
if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer());
// Detached from the start, nothing else may wake the first wait.
if (!screen.on) daemon.watch(loop, deliverNote);
// PARDES_TEST_VIEWS: the terminals at these paths are views of the
// session too, from its start, as `pardes --attach`ed ones are (the
// snapshot harness's `start ... views=N`).
if (upgrade.resumed == null) if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| {
var it = std.mem.tokenizeScalar(u8, paths, ' ');
while (it.next()) |path| {
var path_buf: [256]u8 = undefined;
const z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch continue;
const fd = libc.open(z, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(libc.mode_t, 0));
if (fd >= 0) sh.attachTerminal(fd, -1, null);
}
};
sh.threads_ok = true;
for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| {
pt.reader = try io.concurrent(readPty, .{ io, gpa, pt.file, id, sh.gens[id], loop });
};
if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null;
defer unlinkKittyShm();
while (!core.quit) {
pardes.turn.bump(&pardes.turn.restores);
try core.pump(host);
// Its unit to each replica client, and theirs taken in.
sh.peers.boundary(core);
upgrade.locate();
// Asked in the step (the word), done between steps: the session whole.
if (sh.upgrade_asked) |pane| sh.upgradeNow(pane);
// A terminal (`pardes --attach`) or an adopted shell, handed on by
// the daemon's thread to this loop; started after the first frame,
// off a startup's way.
daemon.watch(loop, deliverNote);
if (core.takeRestore()) |rp| blk: {
// ponytail: a Restore replaces the core its clients replicate;
// they are let go, and attach again.
sh.peers.dropAll(core);
const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| {
core.reportError(core.active, "Restore", err);
break :blk;
};
defer gpa.free(bytes);
const nc = dump.restore(core, bytes, rp) catch |err| {
core.reportError(core.active, "Restore", err);
break :blk;
};
if (sh.lsp_task) |*task| {
task.future.cancel(io);
sh.lsp_task = null;
}
sh.pipe_tasks.cancelAll(io);
for (&sh.gens) |*generation| generation.* +%= 1;
for (&sh.ptys) |*slot| if (slot.*) |*pt| {
pt.reader.cancel(io) catch {};
_ = libc.close(pt.file.handle);
daemon.closed(pt.pid);
host_io.retireShell(pt.pid);
slot.* = null;
};
for (0..pardes.MAX_PANES) |wid| file_watch.watchPane(
sh.inotify_fd,
&sh.watches,
@intCast(wid),
null,
0,
.{ .text = 0 },
);
_ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false);
// ponytail: a restored session is one view, the live one's
// terminal: the others are let go, as a detach of each.
const live = sh.term().?;
for (&sh.terms) |*slot| if (slot.*) |sc| if (sc != live) {
stopInput(io, &sc.thread);
sh.dropScreen(sc, .detach);
slot.* = null;
};
sh.terms = @splat(null);
sh.terms[0] = live;
stopInput(io, &live.thread);
live.feed.view = 0;
sh.from = 0;
if (live.on) startInput(loop, live) catch {};
if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty);
nc.native_images = live.on and live.vx.caps.kitty_graphics;
nc.unattended = !live.on;
sh.peers.alone_unattended = !live.on;
if (fs) |f| f.reset(nc);
core.deinit();
core = nc;
sh.core = nc;
if (comptime pardes.pdf_enabled) if (live.on) {
updateCoreTerminalSize(core, live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix);
};
}
}
if (fs) |f| {
f.deinit(gpa);
fs = null;
sh.fs = null;
}
}
fn clearNativeImages(
kitty_handles: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image),
vx: *vaxis.Vaxis,
tty: *vaxis.Tty,
) void {
var iterator = kitty_handles.valueIterator();
while (iterator.next()) |handle| vx.freeImage(tty.writer(), handle.id);
kitty_handles.clearRetainingCapacity();
}
const Adoption = struct { pid: posix.pid_t, fd: posix.fd_t, pane: ?u8 };
/// The daemon's thread: what it says, onto the loop's queue.
fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
const loop: *Loop = @ptrCast(@alignCast(ctx));
switch (note) {
.attach => |a| if (a.tty < 0) {
if (a.stub >= 0) daemon.refuseStub(a.stub, "a terminal session takes a terminal");
} else loop.postEvent(.{ .attach = .{ .tty = a.tty, .stub = a.stub } }) catch {
_ = libc.close(a.tty);
_ = libc.close(a.stub);
},
.adopted => |a| {
for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch {
_ = libc.close(fd);
};
loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {};
},
.replica => |fd| loop.postEvent(.{ .replica = fd }) catch {
_ = libc.close(fd);
},
}
}
/// A replica reader's post: the session's wait ends, and its step
/// boundary takes the post in.
fn wakeForReplica(ctx: ?*anyopaque) void {
const loop: *Loop = @ptrCast(@alignCast(ctx.?));
// Never waits: a full queue wakes the loop anyway, and a reader the
// loop is joining (a client let go) must not wait on it.
_ = loop.tryPostEvent(.replica_mail) catch {};
}
const Shell = struct {
io: std.Io,
gpa: std.mem.Allocator,
lsp_gpa: std.mem.Allocator,
core: *pardes.Pardes,
prompt_rcs: *const host_io.Shell.PromptFiles,
loop: *Loop,
/// Each view's terminal, by view (views.zig): the session's own first;
/// none in tests.
terms: [pardes.views.max]?*Screen = @splat(null),
/// The view the input taken now is from (`Command.value.from`).
from: u8 = 0,
frame: *std.heap.ArenaAllocator,
paste_buf: *std.Io.Writer.Allocating,
inotify_fd: c_int,
/// Shells a dead session left (Adopt), each waiting for the spawn of
/// the terminal pane made for it.
adoptions: [pardes.MAX_PANES]Adoption = undefined,
adoptions_len: usize = 0,
adopted: usize = 0,
fs: ?*ninep_io.Listener = null,
ptys: [pardes.MAX_PANES]?Pty = @splat(null),
gens: [pardes.MAX_PANES]u32 = @splat(0),
watches: file_watch.Table = @splat(null),
watch_task: ?std.Io.Future(anyerror!void) = null,
lsp_task: ?host_io.Lsp.Task = null,
pipe_tasks: PipeTasks = .{},
threads_ok: bool = false,
check_files: bool = false,
// ponytail: one bracketed paste at a time for every terminal: keys
// another terminal sends while one pastes join its paste.
in_paste: bool = false,
/// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the
/// running-out wait moves it: the core's next wake.
test_clock: ?u64 = null,
/// The tick the last paced frame was due at (waitInput), and whether
/// this wait read an input (its frame is drawn at once).
pace_ns: u64 = 0,
input_seen: bool = false,
wake_to: u64 = 0,
/// waitInput's pacing of output: whether this wait read a pane's output,
/// and when the last frame was written, the last input was read and the
/// focused pane's output last was.
output_seen: bool = false,
drawn_ns: u64 = 0,
input_ns: u64 = 0,
focused_ns: u64 = 0,
/// Upgrade was asked from this pane, to be done between steps (`upgradeNow`).
upgrade_asked: ?u8 = null,
/// Its pty readers stopped for it: their end of file is not a shell's.
upgrading: bool = false,
/// The session's replica clients (src/replica.zig), on sockets.
peers: replica.Peers = .{},
/// This wait took only a replica's post (its input, its join): the
/// pump after it reads no new time, so it moves nothing the replicas'
/// speculations stand on (a replica takes such a unit as is).
mail_only: bool = false,
waited: bool = false,
/// This process a replica client of a session elsewhere (`remote`):
/// its inputs go to the replica, never straight to the core.
remote: ?*Remote = null,
const Leaving = enum { detach, exit };
/// A terminal's input, to the core, or to a replica client's engine
/// (applied at once there, and sent to the session).
fn feed(s: *Shell, ev: pardes.Event) void {
const c = s.remote orelse return s.core.update(ev);
const msg = c.r.input(ev) catch return;
if (!replica.sendInput(c.fd, msg)) c.quit = true;
c.dirty = true;
}
/// Whether a terminal of this process's shows the session, or
/// nothing (a test) can.
fn local(s: *const Shell) bool {
for (s.terms) |slot| if (slot != null) return true;
return false;
}
/// Whether anyone looks at the session: a terminal here, or a replica
/// client (Peers keeps it attended while one is there).
fn setAttended(s: *Shell, on: bool) void {
s.peers.alone_unattended = !on;
s.core.unattended = !on and s.peers.count() == 0;
}
fn of(ctx: ?*anyopaque) *Shell {
return @ptrCast(@alignCast(ctx.?));
}
fn host(s: *Shell) host_io.Host {
return .{ .ctx = s, .vtable = if (comptime pardes.isolated) &isolated_vtable else &vtable };
}
const isolated_vtable: host_io.Host.VTable = .{
.wait_input = waitInput,
.now = clockNow,
.present = present,
.post_present = postPresent,
.poll_frame = stepGlide,
};
const vtable: host_io.Host.VTable = .{
.wait_input = waitInput,
.now = clockNow,
.present = present,
.post_present = postPresent,
.poll_frame = pollFrame,
.watched = watched,
.detach = detach,
.adopt = adopt,
.upgrade = upgradeAsked,
.spawn = spawn,
.pty_write = ptyWrite,
.pty_resize = ptyResize,
.pty_signal = ptySignal,
.close_pty = closePty,
.tty_taken = ttyTaken,
.fg_name = fgName,
.kill_job = killJob,
.write_file = writeFile,
.write_dump = writeDump,
.watch_file = watchFile,
.watch_theme = watchTheme,
.dump_themes = dumpThemes,
.set_clipboard = setClipboard,
.read_clipboard = readClipboard,
.open_link = openLink,
.lsp = lsp,
.pipe = pipe,
.search = search,
};
fn clockNow(ctx: ?*anyopaque) u64 {
const s = of(ctx);
if (s.waited) {
s.waited = false;
if (s.mail_only and s.peers.count() > 0 and s.core.clock_started) return s.core.now_ns;
}
return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
}
/// The live view's terminal (null in tests).
fn term(s: *const Shell) ?*Screen {
return s.terms[s.core.view];
}
fn attached(s: *const Shell) bool {
const screen = s.term() orelse return true;
return screen.on;
}
/// Drawn only while a terminal shows it: a replica client's view live
/// (its input the last), whichever terminal here shows another.
fn watched(ctx: ?*anyopaque) bool {
const s = of(ctx);
if (s.term() == null and s.local()) {
for (s.terms) |slot| if (slot) |sc| if (sc.on) return true;
return false;
}
return s.attached();
}
/// Detach: the terminal put back and let go, the stub told (it ends,
/// and the shell has its terminal again), the session left running.
fn detach(ctx: ?*anyopaque) void {
const s = of(ctx);
// A replica client's: its link ends.
if (s.peers.detach(s.core.view)) return;
if (!s.attached()) return s.core.reportFailure(s.core.active, "Detach: no terminal is attached");
// One of several: its view goes, and the session stays on the rest.
if (pardes.views.count(s.core) > 1) return s.dropView(s.core.view, .detach);
if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session (it is its terminal's job)");
s.leaveTerminal();
}
/// View `k`'s terminal let go (detached, or gone) while others stay: the
/// view goes with it.
fn dropView(s: *Shell, k: u8, how: Leaving) void {
const sc = s.terms[k] orelse return;
stopInput(s.io, &sc.thread);
s.terms[k] = null;
s.core.closeView(k);
s.dropScreen(sc, how);
}
/// A terminal put back and its stub told; an attached one's Screen freed
/// (the session's own stays, a view of none).
fn dropScreen(s: *Shell, sc: *Screen, how: Leaving) void {
if (sc.primary) {
sc.leave();
return sc.sayDetached();
}
sc.leave();
switch (how) {
.detach => sc.sayDetached(),
.exit => {
daemon.tellExit(sc.stub, 0);
sc.stub = -1;
},
}
sc.glide.deinit(s.gpa);
sc.kitty.deinit();
s.gpa.free(sc.buf);
s.gpa.destroy(sc);
}
fn leaveTerminal(s: *Shell) void {
const screen = s.term() orelse return;
stopInput(s.io, &screen.thread);
screen.leave();
s.core.native_images = false;
s.setAttended(false);
// The stub's stdin, stdout and stderr were its terminal too.
const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0));
if (null_fd >= 0) {
for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i));
if (null_fd > 2) _ = libc.close(null_fd);
}
screen.sayDetached();
daemon.setState(true);
}
/// `pardes --attach`'s terminal: for a detached session its own again,
/// entered as the first one was; for one attached already, a view of
/// its own (views.zig). Sized, asked what it can do, and drawn whole.
fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void {
const live = s.term() orelse return;
const screen = if (!live.on) live else extra: {
const sc = s.gpa.create(Screen) catch break :extra null;
const buf = s.gpa.alloc(u8, 0x10000) catch {
s.gpa.destroy(sc);
break :extra null;
};
sc.* = .{ .io = s.io, .gpa = s.gpa, .env = live.env, .buf = buf, .kitty = .init(s.gpa) };
break :extra sc;
} orelse {
_ = libc.close(fd);
return refuse(stub, "that session has no room for another terminal");
};
const extra = screen != live;
const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch {
_ = libc.close(fd);
if (extra) s.freeScreen(screen) else daemon.setState(true);
return refuse(stub, "that terminal would not go raw");
};
screen.enter(tty) catch {
if (extra) s.freeScreen(screen) else daemon.setState(true);
return refuse(stub, "that terminal would not take the screen");
};
if (extra) {
const k = s.core.openView() orelse {
screen.leave();
s.freeScreen(screen);
return refuse(stub, "that session has as many terminals as it takes");
};
screen.feed.view = k;
s.terms[k] = screen;
}
screen.setStub(stub);
s.setAttended(true);
startInput(s.loop, screen) catch {};
screen.vx.queryTerminalSend(screen.tty.writer()) catch {};
s.core.needs_frame = true;
daemon.setState(false);
}
fn freeScreen(s: *Shell, sc: *Screen) void {
sc.kitty.deinit();
s.gpa.free(sc.buf);
s.gpa.destroy(sc);
}
/// A terminal refused: its stub told why (a test's has none).
fn refuse(stub: posix.fd_t, why: []const u8) void {
if (stub >= 0) daemon.refuseStub(stub, why);
}
/// Adopt: the daemon is asked for the shells of sessions that died
/// holding them; each comes back (`adopted`) as a terminal pane here.
fn adopt(ctx: ?*anyopaque, pane: u8) void {
const s = of(ctx);
if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session");
s.adopted = 0;
daemon.adopt();
}
fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void {
const s = of(ctx);
if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place");
s.upgrade_asked = pane;
}
/// Upgrade, between steps: this process exec'd as the pardes now at the
/// path it was started from, the session in its dump, and its ptys,
/// terminals, stubs and daemon link kept open across (upgrade.zig).
/// Returns only when it could not be, the session going on as it was.
fn upgradeNow(s: *Shell, pane: u8) void {
if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty
s.upgrade_asked = null;
const core = s.core;
var why: [800]u8 = undefined;
const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from");
// 9P is served while the new binary is asked (its clients' clunks
// and reads after the word are answered), and not after.
pardes.turn.rest();
const checked = upgrade.check(path, &why);
pardes.turn.wake();
switch (checked) {
.no => |w| return core.reportFailure(pane, w),
.ok => {},
}
// Nothing more read from a pty or a terminal, and what was read
// goes in; a reader's cancel posts an end of file, passed over.
s.upgrading = true;
defer s.upgrading = false;
for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {};
for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread);
while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev);
core.settle();
var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path };
for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle);
for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{
.view = @intCast(k),
.fd = sc.tty.fd.handle,
.stub = if (sc.primary) daemon.stub else sc.stub,
.primary = sc.primary,
.termios = sc.tty.termios,
});
var popped = false;
var at_buf: [1024:0]u8 = undefined;
const failed: []const u8 = failed: {
const at = pardes.dump.upgradePath(&at_buf, core.settings.dump_dir.get()) orelse break :failed "Upgrade: no directory for the session's dump; this session stays as it is";
const bytes = pardes.dump.dumpBytes(core) catch |err| {
var words: [128]u8 = undefined;
break :failed std.fmt.bufPrint(&why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump";
};
defer s.gpa.free(bytes);
if (!upgrade.writeDump(at, bytes)) break :failed std.fmt.bufPrint(&why, "Upgrade: the session's dump could not be written to {s}; it stays as it is", .{at[0..@min(at.len, 600)]}) catch "Upgrade: its dump could not be written";
rec.dump = at;
rec.old = upgrade.openSelf();
// What this process put in its terminals that the next puts in
// again: its images, and its keyboard mode, a stack.
for (s.terms) |slot| if (slot) |sc| if (sc.on) {
clearNativeImages(&sc.kitty, &sc.vx, &sc.tty);
if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[<u") catch {};
sc.vx.state.kitty_keyboard = false;
sc.tty.writer().flush() catch {};
};
popped = true;
unlinkKittyShm();
daemon.upgraded();
if (s.fs) |f| f.flushOut();
const err_words = upgrade.exec(s.gpa, path, -1, &rec);
// Still here: the exec failed.
_ = libc.unlink(at);
if (rec.old >= 0) _ = libc.close(rec.old);
break :failed std.fmt.bufPrint(&why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start";
};
// As it was: its ptys read on, its terminals' keys as they were.
for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| {
pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader;
};
for (s.terms) |slot| if (slot) |sc| if (sc.on) {
if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {};
startInput(s.loop, sc) catch {};
};
core.reportFailure(pane, failed);
}
/// An upgraded session's shells, running on: each its pane's pty again,
/// or, when its dump would not load (`fresh`), adopted as new panes.
fn resumePtys(s: *Shell, rec: *const upgrade.Record) void {
for (rec.ptys[0..rec.nptys]) |k| {
const pane = if (rec.fresh) null else s.core.panes[k.pane];
if (pane == null or !pane.?.isTerminal()) {
s.adoptShell(k.pid, k.fd);
continue;
}
const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } };
s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } };
}
}
/// An upgraded session's terminals, each its view's again (`primary`,
/// run's, entered already); in a fresh session each but the primary a
/// view of its own, as `--attach` makes one. A view left with none
/// closes.
fn resumeTerminals(s: *Shell, rec: *const upgrade.Record, primary: *Screen) void {
if (comptime builtin.is_test) unreachable;
const core = s.core;
if (rec.fresh) {
for (rec.ttys[0..rec.nttys]) |t| if (!t.primary) s.attachTerminal(t.fd, t.stub, t.termios);
return;
}
s.terms = @splat(null);
if (rec.nttys == 0) {
pardes.views.only(core);
s.terms[core.view] = primary;
return;
}
for (rec.ttys[0..rec.nttys]) |t| {
if (!pardes.views.isOpen(core, t.view) or s.terms[t.view] != null) {
if (t.primary) continue;
_ = libc.close(t.fd);
if (t.stub >= 0) daemon.tellDetached(t.stub);
continue;
}
const sc = if (t.primary) primary else extra: {
const sc = s.gpa.create(Screen) catch break :extra null;
const buf = s.gpa.alloc(u8, 0x10000) catch {
s.gpa.destroy(sc);
break :extra null;
};
sc.* = .{ .io = s.io, .gpa = s.gpa, .env = primary.env, .buf = buf, .kitty = .init(s.gpa) };
const tty = Screen.ttyOn(s.io, sc.buf, t.fd, t.termios) catch {
s.freeScreen(sc);
break :extra null;
};
sc.enter(tty) catch {
s.freeScreen(sc);
break :extra null;
};
sc.setStub(t.stub);
startInput(s.loop, sc) catch {};
sc.vx.queryTerminalSend(sc.tty.writer()) catch {};
break :extra sc;
} orelse {
_ = libc.close(t.fd);
if (t.stub >= 0) daemon.tellDetached(t.stub);
continue;
};
sc.feed.view = t.view;
s.terms[t.view] = sc;
}
for (0..pardes.views.max) |k| if (pardes.views.isOpen(core, @intCast(k)) and s.terms[k] == null) core.closeView(@intCast(k));
if (s.terms[core.view] == null) s.terms[core.view] = primary;
}
/// One shell of a dead session (`pid` 0: the last of them was told).
fn adoptShell(s: *Shell, pid: posix.pid_t, fd: posix.fd_t) void {
const core = s.core;
if (pid == 0) {
var buf: [96]u8 = undefined;
return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in");
}
var newest: u32 = 0;
for (core.panes) |slot| if (slot) |pn| {
newest = @max(newest, pn.serial);
};
if (s.adoptions_len < s.adoptions.len) {
// A terminal pane, as the Tty word makes one; its spawn takes
// this pty instead of forking a shell (`spawn`).
s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null };
s.adoptions_len += 1;
_ = core.executeBuiltinLine(core.active, "Tty");
for (core.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) {
// Its shell is up already: nothing to greet with `ls`.
pn.greet = false;
s.adoptions[s.adoptions_len - 1].pane = @intCast(id);
s.adopted += 1;
return;
};
s.adoptions_len -= 1;
}
// No room for it: its master goes, and the shell with this session.
_ = libc.close(fd);
var buf: [96]u8 = undefined;
core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell");
}
fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
const s = of(ctx);
// The wait is the 9P connections' turn with the core. A timeout (the
// core's next wake) arrives through the same queue (`wakeWatch`).
// While anything moves, a frame a tick (animation.frame_ns) on a grid
// of them, as the GUI paces to its display: the loop ran as fast as
// the terminal answered, a frame every 2 ms, each a write. An input
// ends the wait at once and its frame is drawn then; the ticks after
// it run from it.
var wait = timeout_ms;
// Detached, nobody's key dismisses a message: they go on the clock.
if (!s.attached()) {
pardes.Messages.expireUnattended(s.core);
for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) {
wait = if (wait == 0) 100 else @min(wait, 100);
break;
};
}
const paced = s.test_clock == null and s.core.continuous();
var tick: u64 = 0;
if (paced) {
const period = pardes.animation.frame_ns;
const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
tick = if (s.pace_ns != 0 and now -| s.pace_ns < 2 * period) s.pace_ns + period else now;
if (tick < now) tick += (now - tick) / period * period;
s.pace_ns = tick;
wait = @intCast(@max(1, (tick -| now) / std.time.ns_per_ms));
}
s.input_seen = false;
s.output_seen = false;
s.mail_only = true;
defer s.waited = true;
// Paced, what is not an input (a frame's ack, a pty's output) is
// taken in and the wait goes on to the tick: the acks alone ran the
// loop at the terminal's round trip.
while (true) {
s.waitOnce(wait);
if (!paced or s.input_seen or s.core.quit) break;
const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
if (now + std.time.ns_per_ms > tick) break;
wait = @intCast((tick - now) / std.time.ns_per_ms);
}
if (paced and s.input_seen) s.pace_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
// Output alone is drawn a frame a tick at most, what came in till
// then in one: a flood (`yes`, 4 KB a read) was drawn a read at a
// time, nearly all of its frames written over before they were
// seen. Never while what someone waits on is undrawn: an input
// (its frame held for the terminal's answer, FrameAck), or the
// focused pane's output soon after one, its echo (a remote shell's
// an RTT later).
while (!paced and s.output_seen and !s.input_seen and !s.core.quit and s.test_clock == null) {
if (s.input_ns > s.drawn_ns) break;
if (s.focused_ns > s.drawn_ns and s.focused_ns -| s.input_ns < std.time.ns_per_s) break;
const due = s.drawn_ns + pardes.animation.frame_ns;
const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
if (now + std.time.ns_per_ms > due) break;
s.waitOnce(@intCast((due - now) / std.time.ns_per_ms));
}
}
fn waitOnce(s: *Shell, wait: u32) void {
var batch: usize = 0;
if (wait != 0) {
// A virtual clock moves a frame a wake while anything moves
// continuously (the glide), as the real one would.
s.wake_to = s.core.nextWake() orelse if (s.core.continuous()) s.core.now_ns + pardes.animation.frame_ns else 0;
requestWake(s.io, wait);
}
pardes.turn.rest();
const first = s.loop.nextEvent() catch {
pardes.turn.wake();
s.core.quit = true;
return s.reloadWatched();
};
pardes.turn.wake();
batch = 1;
// A run of queued motions is one move to its last cell: each would
// otherwise redo hover and selection work the next one undoes.
var motion: ?@TypeOf(Command.value) = null;
var ev = first;
while (true) {
if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) {
if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or
@as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods)))
{
_ = s.apply(m);
};
motion = ev;
} else {
if (motion) |m| _ = s.apply(m);
motion = null;
if (s.apply(ev)) break;
}
if (!s.in_paste and batch >= 64) break;
ev = (s.loop.tryEvent() catch null) orelse break;
batch += 1;
}
if (motion) |m| _ = s.apply(m);
// An exit's wake (a .nop) or output an exit waited behind: told
// here, inside the step, so the frame after it shows it.
s.takeExits();
s.reloadWatched();
}
fn apply(s: *Shell, event: @TypeOf(Command.value)) bool {
const core = s.core;
const tz_event = tracy.zone(@src(), "event");
defer tz_event.end();
// A key's or a click's time, for its latency to the frame that
// answers it (FrameStats): when the loop takes it in.
switch (event) {
.key_press => {
core.frames.input(pardes.FrameStats.nowNs());
s.input_seen = true;
},
.mouse => |m| if (m.type == .press) {
core.frames.input(pardes.FrameStats.nowNs());
s.input_seen = true;
},
.paste, .paste_start, .winsize => s.input_seen = true,
else => {},
}
if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
if (event != .replica_mail) s.mail_only = false;
// A terminal's input goes into its view; a closed one's last is
// dropped.
switch (event) {
.key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => {
if (s.terms[s.from] == null and s.local()) {
if (event == .paste) s.gpa.free(@constCast(event.paste));
return false;
}
if (s.local() and s.remote == null) core.toView(s.from);
},
else => {},
}
switch (event) {
.nop => {},
.from => |k| s.from = k,
.winched => s.winched(),
// A terminal hung up (its stub passes the hangup on) or its stub
// died (a forked session's death signal): that one's input has
// ended. A HUP says not whose: each is asked.
.hangup => for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on and sc.hungUp()) {
s.from = @intCast(k);
if (s.apply(.quit)) return true;
},
.wake => if (s.test_clock) |*virtual| {
virtual.* = @max(virtual.*, s.wake_to);
},
.quit => {
if (s.remote) |c| {
c.quit = true;
return true;
}
// One of several: its view goes with it.
if (pardes.views.count(core) > 1) {
s.dropView(core.view, .detach);
return true;
}
// The terminal went: a session the daemon keeps carries on
// without it, to be attached again. Gone before the first
// frame, the reader that takes the daemon's `ok` (kept
// waits on it) is not started yet: started here.
daemon.watch(s.loop, deliverNote);
if (daemon.kept()) {
if (s.attached()) s.leaveTerminal();
return true;
}
core.quit = true;
return true;
},
.attach => |a| s.attachTerminal(a.tty, a.stub, null),
.adopted => |a| s.adoptShell(a.pid, a.fd),
.replica => |fd| {
s.peers.handed(fd);
s.input_seen = true;
},
.replica_mail => s.input_seen = true,
.unit => |bytes| {
if (s.remote) |c| {
c.r.confirm(bytes);
if (c.r.moved) c.dirty = true;
c.r.moved = false;
c.changed = true;
}
std.heap.c_allocator.free(bytes);
},
.checked => |d| if (s.remote) |c| c.checked(d),
.link_gone => if (s.remote) |c| {
c.quit = true;
c.gone = true;
return true;
},
.focus_in => {
s.feed(.{ .focus = true });
// A client's core is the session's: the notice is the session's to give.
// ponytail: not while clients replicate it (set outside a step).
if (s.remote == null and !s.peers.recording) upgrade.noticeNewer(core);
},
.focus_out => {
s.feed(.pointer_leave);
s.feed(.{ .focus = false });
},
.winsize => |ws| if (s.attached()) s.resized(s.terms[s.from], ws),
.pty_read => |pr| {
tookRead(s.io, pr.id);
s.output_seen = true;
if (pr.id == core.active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
if (s.gens[pr.id] == pr.gen)
core.update(.{ .output = .{ .pane = @intCast(pr.id), .bytes = pr.bytes } });
s.gpa.free(pr.bytes);
// An exit waiting behind this output may be told now.
s.takeExits();
return true;
},
.pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) {
if (s.ptys[e.id]) |*pt| {
pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks
// A command's pty stays open until its child has exited:
// closing it would hang up one that runs on without it.
// Its exit, if it came first, is told now its output is in.
if (pt.cmd.watched) {
host_io.commandEof(core, &s.ptys, e.id, s, closeWatched);
return true;
}
_ = libc.close(pt.file.handle);
// Unwatched, a command's exit is read here, as its end,
// and a shell's, for a run waiting on it and the log.
const command = if (core.panes[e.id]) |pn| pn.command != null else false;
const status = host_io.exitStatus(pt.pid, 100);
if (status == null) host_io.retireShell(pt.pid);
s.ptys[e.id] = null;
if (command or status != null) core.update(.{ .exited = .{ .pane = @intCast(e.id), .status = status } });
}
core.update(.{ .eof = .{ .pane = @intCast(e.id) } });
},
.key_press => |key| if (s.in_paste) {
const bytes = pasteBytes(key);
const room = max_paste_bytes -| s.paste_buf.written().len;
s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {};
} else s.feed(vaxis_input.keyEvent(key)),
.mouse => |m| {
const pdf_before = nativePdfWheelTarget(core, m);
if (mouseEvent(m)) |ev| s.feed(ev);
if (pdf_before) |before| {
if (core.panes[before.pane]) |pane| {
if (pane.pdfPage()) |page| {
if (page != before.page) return true;
}
}
}
},
.paste => |bytes| {
s.feed(.{ .paste = bytes });
s.gpa.free(@constCast(bytes));
},
.paste_start => {
s.in_paste = true;
s.paste_buf.clearRetainingCapacity();
},
.paste_end => {
s.in_paste = false;
const pasted = s.paste_buf.written();
if (pasted.len > 0) s.feed(.{ .paste = pasted });
s.paste_buf.clearRetainingCapacity();
},
.files_changed => s.check_files = true,
.fs_ready => {},
.lsp_done => |d| {
core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } });
if (d.rows) |rows| s.lsp_gpa.free(rows);
if (s.lsp_task) |*t| if (t.id == d.id) {
t.future.await(s.io);
s.lsp_task = null;
};
},
.lsp_status => |text| {
var mbuf: [256]u8 = undefined;
core.setStatus(core.active, message.stamp(&mbuf, "lsp", text));
s.lsp_gpa.free(text);
},
.pipe_done => |response_value| {
var response = response_value;
core.update(.{ .pipe_resp = .{
.id = response.id,
.success = response.success,
.outputs = response.outputs,
.failure = response.failure,
} });
response.deinit(s.gpa);
s.pipe_tasks.finish(s.io, response_value.id);
},
.search_rows => |b| {
core.update(.{ .search = b });
b.deinit(s.gpa);
},
}
return false;
}
/// Terminal `screen` (the live view's) is `ws` big.
fn resized(s: *Shell, screen: ?*Screen, ws: vaxis.Winsize) void {
if (screen) |sc| {
sc.size = ws;
sc.vx.resize(s.gpa, sc.tty.writer(), ws) catch {};
}
s.feed(.{ .resize = if (comptime pardes.pdf_enabled) terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) else .{ .cols = ws.cols, .rows = ws.rows } });
}
/// A SIGWINCH: each terminal whose size it changed is resized, in its
/// view (a terminal reporting in band says so as input).
fn winched(s: *Shell) void {
for (s.terms, 0..) |slot, k| {
const sc = slot orelse continue;
if (!sc.on or sc.vx.state.in_band_resize) continue;
const ws = sc.tty.getWinsize() catch continue;
if (sc.size) |was| if (std.meta.eql(was, ws)) continue;
if (s.remote == null) s.core.toView(@intCast(k));
s.resized(sc, ws);
}
}
fn reloadWatched(s: *Shell) void {
if (!s.check_files) return;
s.check_files = false;
if (file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches))
s.loop.postEvent(.files_changed) catch {};
}
/// ponytail: a terminal's scrollback under the wheel lands here (the
/// wheel reaches the core as a mouse event, not counted as the GUI's
/// notches are); `wheeled` from the mouse event if it should glide.
fn stepGlide(ctx: ?*anyopaque) void {
const s = of(ctx);
if (s.term()) |sc| sc.glide.step(s.core, s.gpa, null, null);
}
fn pollFrame(ctx: ?*anyopaque) void {
const s = of(ctx);
stepGlide(ctx);
if (s.fs) |f| if (f.tick().pending) {
_ = s.loop.tryPostEvent(.fs_ready) catch {};
};
for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| {
var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd);
};
const sc = s.term() orelse return;
s.core.native_image_patches = sc.feed.shm.load(.acquire);
if (sc.caps_pending and sc.on and sc.vx.queries_done.load(.unordered)) {
sc.caps_pending = false;
sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {};
s.core.native_images = sc.vx.caps.kitty_graphics;
if (sc.vx.caps.kitty_graphics) kittyShmProbe(sc.tty.writer(), &sc.feed);
sc.vx.queueRefresh();
s.core.needs_frame = true;
}
}
fn present(ctx: ?*anyopaque, canonical: *const pardes.Surface) void {
const s = of(ctx);
const sc = s.term() orelse return;
const vx = &sc.vx;
sc.tracks = canonical.panelTracks();
// The last frame is not answered yet: this one stays owed, and the
// answer's wake draws the state as it is then.
if (sc.feed.ack.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) {
s.core.present_skipped = true;
return;
}
_ = s.frame.reset(.retain_capacity);
const surface = panel_compositor.compose(
s.frame.allocator(),
@constCast(canonical),
sc.tracks,
s.core.theme().bg,
) catch return;
const tz_cells = tracy.zone(@src(), "surface->vaxis");
const win = vx.window();
const truecolor = vx.caps.rgb or colortermTruecolor();
// Each of the shell's own motions below asks for frames while it runs.
if (sc.glide.pending) sc.glide.measure(s.gpa, canonical);
if (sc.glide.moving()) sc.glide.advance(s.core.now_ns, sc.glide.motion);
s.core.shell_continuous = sc.glide.moving();
s.core.frames.scroll = @round(sc.glide.follow.offset);
const glided = pardes.glide.shifted(&sc.glide, s.frame.allocator(), surface) catch surface;
const shadowed = chipShadows(s.frame.allocator(), glided, s.core, truecolor) catch glided;
const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed;
const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed;
paintCells(win, trailed.cells, trailed.cols, trailed.rows);
tz_cells.end();
for (surface.images[0..surface.nimages]) |maybe| {
const place = maybe orelse continue;
if (panel_compositor.hidesAttachment(surface.panelTracks(), place.serial)) continue;
if (comptime pardes.pdf_enabled) {
if (!kittyImageRepresentable(place)) continue;
}
const key = place.cacheKey();
if (!sc.kitty.contains(key) and vx.caps.kitty_graphics and sc.feed.shm.load(.acquire)) shm: {
var buf: [64]u8 = undefined;
kitty_shm_serial +%= 1;
// Bounded: a segment this many transmissions old was never
// read (a terminal reads one as its command arrives), and a
// tmpfs holds it in memory until it goes.
if (kitty_shm_serial > kitty_shm_window) {
var old_buf: [64]u8 = undefined;
if (kittyShmName(&old_buf, kitty_shm_serial - kitty_shm_window)) |old| _ = libc.shm_unlink(old) else |_| {}
}
const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm;
if (!kittyShmWrite(name, place.rgba)) break :shm;
if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle|
sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id)
else
_ = libc.shm_unlink(name);
}
if (!sc.kitty.contains(key) and vx.caps.kitty_graphics) {
const enc = std.base64.standard.Encoder;
if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| {
defer s.gpa.free(b64);
_ = enc.encode(b64, place.rgba);
if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle|
sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id);
} else |_| {}
}
if (sc.kitty.get(key)) |cached| {
if (comptime !pardes.pdf_enabled) {
const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h });
cached.draw(child, .{ .scale = .contain }) catch {};
} else {
if (place.native.exact) {
if (exactKittyPlacement(place, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix)) |placement| {
// The cell keeps its own glyph and colours
// (Image.draw would reset them): a fragment
// short of the cell shows the pane under it.
const x = place.x + placement.cell_x;
if (win.readCell(x, place.y)) |under| {
var cell = under;
cell.image = .{ .img_id = cached.id, .options = placement.options };
win.writeCell(x, place.y, cell);
}
}
} else if (place.native.fit == .contain) {
const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h });
cached.draw(child, .{ .scale = .contain }) catch {};
} else if (kittyPlacement(
place,
vx.screen.width,
vx.screen.height,
vx.screen.width_pix,
vx.screen.height_pix,
)) |placement| {
const child = win.child(.{
.x_off = @as(i17, place.x) + placement.cell_x,
.y_off = @as(i17, place.y) + placement.cell_y,
.width = placement.cell_cols,
.height = placement.cell_rows,
});
cached.draw(child, placement.options) catch {};
}
}
}
}
while (true) {
var stale: [pardes.MAX_PANES]pardes.ImageCacheKey = undefined;
var stale_len: usize = 0;
var image_iterator = sc.kitty.iterator();
while (image_iterator.next()) |entry| {
if (surfaceHasKittyKey(surface, entry.key_ptr.*)) continue;
stale[stale_len] = entry.key_ptr.*;
stale_len += 1;
if (stale_len == stale.len) break;
}
for (stale[0..stale_len]) |key| if (sc.kitty.fetchRemove(key)) |removed|
vx.freeImage(sc.tty.writer(), removed.value.id);
if (stale_len < stale.len) break;
}
if (glided.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar);
const tz_render = tracy.zone(@src(), "vx.render");
const before = sc.tty.tty_writer.pos + sc.tty.writer().end;
vx.render(sc.tty.writer()) catch {};
// The frame's cost to the terminal (FrameStats.Frame.bytes): what
// vaxis's diff of the cells wrote.
s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), sc.tty.tty_writer.pos + sc.tty.writer().end -| before));
if (sc.tty.tty_writer.pos + sc.tty.writer().end != before) sc.feed.ack.ask(sc.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds));
s.drawn_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
tz_render.end();
}
fn postPresent(ctx: ?*anyopaque) void {
const s = of(ctx);
if (s.term()) |sc| s.core.acknowledgePanelPresentation(sc.tracks);
tracy.frameMark();
}
fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void {
const s = of(ctx);
for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) {
std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]);
s.adoptions_len -= 1;
return s.takeShell(pane, a);
};
// The new shell starts before a running one goes: one that cannot
// start leaves the running one be (pty/ctl's exec).
const running = s.ptys[pane] != null;
const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.screen_h, s.core.screen_w, s.fs) catch |err| {
if (running) return s.core.restartFailed(pane, err);
return s.core.shellFailed(pane, err);
};
closePty(ctx, pane); // a shell still in the slot goes, reaped
s.gens[pane] +%= 1;
const command = if (s.core.panes[pane]) |pn| pn.command != null else false;
s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } };
var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
// Only a shell given no directory is asked where it is: one given a
// directory is named by it already (newShell), and asked now, before
// its chdir, it would answer this process's, a rename to undo.
if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd);
if (s.threads_ok) {
if (s.ptys[pane]) |*pt| {
pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader;
}
}
}
/// An adopted shell, running already, as pane `pane`'s: told the size
/// twice (a size it never had, then the pane's), which makes it redraw.
fn takeShell(s: *Shell, pane: u8, a: Adoption) void {
closePty(s, pane);
s.gens[pane] +%= 1;
const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } };
s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} };
var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid));
var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd);
const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 };
_ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny));
if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1));
if (s.threads_ok) if (s.ptys[pane]) |*pt| {
pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader;
};
}
fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void {
const s = of(ctx);
if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes);
}
fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void {
const s = of(ctx);
if (s.ptys[pane]) |pt| {
const ws = host_io.ptyWinsize(s.core, cols, rows);
_ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws));
}
}
fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void {
const s = of(ctx);
// A command whose exit is recorded is reaped: its group may be
// another's by now.
if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched);
}
/// The pane is gone: hang its pty up, which the kernel passes on to the
/// shell as SIGHUP, and retire the shell. Output still in flight
/// carries the old generation and is dropped.
fn closePty(ctx: ?*anyopaque, pane: u8) void {
const s = of(ctx);
var pt = s.ptys[pane] orelse return;
s.ptys[pane] = null;
s.gens[pane] +%= 1;
pt.reader.cancel(s.io) catch {};
_ = libc.close(pt.file.handle);
daemon.closed(pt.pid);
host_io.retireShell(pt.pid);
}
fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool {
const s = of(ctx);
const pt = s.ptys[pane] orelse return false;
return host_io.ttyTaken(pt.pid, pt.file.handle);
}
fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 {
const s = of(ctx);
const pt = s.ptys[pane] orelse return null;
return host_io.foregroundName(pt.pid, pt.file.handle, buf);
}
/// The command panes' exits, told once their output is in (host_io).
fn takeExits(s: *@This()) void {
host_io.takeExits(s.core, &s.ptys, s, closeWatched);
}
fn closeWatched(s: *@This(), id: usize) void {
const pt = &(s.ptys[id] orelse return);
_ = libc.close(pt.file.handle);
s.ptys[id] = null;
}
fn killJob(ctx: ?*anyopaque, pane: u8) bool {
const s = of(ctx);
const pt = s.ptys[pane] orelse return false;
return host_io.killJob(pt.pid, pt.file.handle);
}
fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void {
const s = of(ctx);
host_io.writeFile(s.core, &s.watches, pane, path, bytes);
}
fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void {
host_io.writeDump(of(ctx).core, bytes);
}
fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void {
const s = of(ctx);
if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode))
s.loop.postEvent(.files_changed) catch {};
}
fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void {
const s = of(ctx);
if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on, s.threads_ok))
s.loop.postEvent(.files_changed) catch {};
}
fn dumpThemes(ctx: ?*anyopaque, pane: u8) void {
const s = of(ctx);
host_io.dumpThemes(s.core, s.io, s.gpa, pane);
}
fn setClipboard(ctx: ?*anyopaque, text: []const u8) void {
const s = of(ctx);
// Detached, the session keeps it (a 9P read, a paste here).
const sc = s.term() orelse return s.core.fallback.setClipboard(text);
if (!sc.on) return s.core.fallback.setClipboard(text);
copyToClipboard(&sc.vx, &sc.tty, s.gpa, text);
}
fn readClipboard(ctx: ?*anyopaque) void {
const s = of(ctx);
const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items });
if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items });
requestClipboard(&sc.vx, &sc.tty);
}
fn openLink(_: ?*anyopaque, url: []const u8) void {
look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly
}
fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void {
const s = of(ctx);
if (!s.threads_ok) {
s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } });
return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable);
}
host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows);
}
fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
const s = of(ctx);
s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned);
}
fn pipe(ctx: ?*anyopaque, id: u32) void {
const s = of(ctx);
if (!s.threads_ok) {
s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
return s.core.reportError(s.core.active, "pipe", error.WorkersUnavailable);
}
selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe);
}
fn search(ctx: ?*anyopaque, gen: u32) void {
const s = of(ctx);
if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch);
pardes.Stream.runHere(s.core, gen);
}
/// The loop's queue waits for room (a wait the worker's cancel ends).
fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool {
const s = of(ctx);
s.loop.postEvent(.{ .search_rows = batch }) catch {
batch.deinit(s.gpa);
return false;
};
return true;
}
fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
const s = of(ctx);
var owned = response;
s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa);
}
};
test "TTY queued results reject old PTY generations and LSP request IDs" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer core.deinit();
var shell: Shell = .{
.io = std.testing.io,
.gpa = gpa,
.lsp_gpa = gpa,
.core = core,
.prompt_rcs = undefined,
.loop = undefined,
.frame = undefined,
.paste_buf = undefined,
.inotify_fd = -1,
};
shell.gens[0] = 2;
_ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } });
_ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } });
const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa);
defer gpa.free(text);
try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null);
try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null);
core.lspRequest(0, .status, "");
const old_id = core.lsp_wait.?.id;
core.lspRequest(0, .status, "");
const current_id = core.lsp_wait.?.id;
shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } };
_ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } });
try std.testing.expect(shell.lsp_task != null);
try std.testing.expectEqual(current_id, shell.lsp_task.?.id);
try std.testing.expectEqual(current_id, core.lsp_wait.?.id);
_ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } });
try std.testing.expect(shell.lsp_task == null);
try std.testing.expect(core.lsp_wait == null);
}
test "TTY worker setup failures finish matching LSP and pipe requests" {
const gpa = std.testing.allocator;
var failing_vtable = std.testing.io.vtable.*;
failing_vtable.concurrent = std.Io.failingConcurrent;
const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable };
for (0..2) |failure| {
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer core.deinit();
const pane = try core.setTestFile("abc");
var failing = std.testing.FailingAllocator.init(gpa, .{
.fail_index = if (failure == 0) 0 else std.math.maxInt(usize),
});
var shell: Shell = .{
.io = failing_io,
.gpa = failing.allocator(),
.lsp_gpa = failing.allocator(),
.core = core,
.prompt_rcs = undefined,
.loop = undefined,
.frame = undefined,
.paste_buf = undefined,
.inotify_fd = -1,
.threads_ok = true,
};
core.lspRequest(core.active, .status, "");
const req: host_io.Lsp.Request = .{
.id = core.lsp_wait.?.id,
.kind = .status,
.pane = @intCast(core.active),
.offset = 0,
.arg = "",
};
Shell.lsp(&shell, req);
try std.testing.expect(core.lsp_wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
pane.body.cur_col = 2;
pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
core.update(.{ .key = .{ .cp = '|' } });
core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
core.update(.{ .key = .{ .cp = pardes.Key.enter } });
const pipe_id = core.pipe.wait.?.id;
Shell.pipe(&shell, pipe_id);
try std.testing.expect(core.pipe.wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
try std.testing.expect(shell.lsp_task == null);
try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len);
}
}
fn copyToClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty, gpa: std.mem.Allocator, text: []const u8) void {
if (text.len == 0) return;
vx.copyToSystemClipboard(tty.writer(), text, gpa) catch {};
}
fn requestClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty) void {
vx.requestSystemClipboard(tty.writer()) catch {};
}
fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void {
const s: *Shell = @ptrCast(@alignCast(ctx orelse return));
const copy = s.lsp_gpa.dupe(u8, text) catch return;
const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false;
if (!posted) s.lsp_gpa.free(copy);
}
fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void {
if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) {
while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break;
return;
}
const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } };
// One buffer, read into directly: a Reader around it only added a second
// (and in a safe build, filled both as `undefined` on every start).
var buf: [4096]u8 = undefined;
while (true) {
const n = file.readStreaming(io, &.{&buf}) catch break;
if (n == 0) break;
loop.postEvent(.files_changed) catch break;
}
}
fn keepSignal(_: posix.SIG) callconv(.c) void {}
fn winchWatch(loop: *Loop) void {
var set = posix.sigemptyset();
posix.sigaddset(&set, posix.SIG.WINCH);
if (daemon.link >= 0) posix.sigaddset(&set, posix.SIG.HUP);
while (true) {
var sig: c_int = 0;
if (libc.sigwait(&set, &sig) != 0) continue;
// The terminals are the loop's: it asks each its size, and takes a
// hangup as the end of the one that hung up.
loop.postEvent(if (sig == @backingInt(posix.SIG.HUP)) .hangup else .winched) catch {};
}
}
/// A wait with a timeout: post one `.wake` when it runs out. The wake joins
/// the input queue, so a key or a click that lands first is handled at once
/// instead of after a blind sleep; vaxis's queue has no timed wait. Each
/// request bumps `wake_gen`, which cuts short a sleep still timing an
/// earlier, longer request (an 800 ms linger interrupted by a key that
/// starts a 16 ms fall) and times the new one instead.
var wake_gen: std.atomic.Value(u32) = .init(0);
var wake_ms: std.atomic.Value(u32) = .init(0);
fn requestWake(io: std.Io, ms: u32) void {
wake_ms.store(ms, .release);
_ = wake_gen.fetchAdd(1, .acq_rel);
io.futexWake(u32, &wake_gen.raw, 1);
}
fn wakeWatch(io: std.Io, loop: *Loop) void {
var seen = wake_gen.load(.acquire);
while (true) {
// Asleep until a request.
while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen);
seen = wake_gen.load(.acquire);
if (timeWake(io, &seen)) loop.postEvent(.wake) catch {};
}
}
/// Sleep out the latest request; true when it ran its course, false when
/// none is pending. A newer request met on the way restarts the timing.
fn timeWake(io: std.Io, seen: *u32) bool {
while (true) {
const ms = wake_ms.load(.acquire);
const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms;
while (true) {
const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds);
if (now >= deadline) return true;
io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{
.raw = .fromNanoseconds(@intCast(deadline - now)),
.clock = .awake,
} }) catch {};
const gen = wake_gen.load(.acquire);
if (gen != seen.*) {
seen.* = gen;
break;
}
}
}
}
test "a short wake request cuts short a long one still sleeping" {
const io = std.testing.io;
var seen = wake_gen.load(.acquire);
requestWake(io, 800);
seen = wake_gen.load(.acquire);
const Timer = struct {
fn run(timer_io: std.Io, start_seen: u32, done: *std.atomic.Value(u64)) void {
var local = start_seen;
_ = timeWake(timer_io, &local);
done.store(@intCast(std.Io.Clock.awake.now(timer_io).nanoseconds), .release);
}
};
var done: std.atomic.Value(u64) = .init(0);
const start: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds);
const thread = try std.Thread.spawn(.{}, Timer.run, .{ io, seen, &done });
try io.sleep(.fromMilliseconds(50), .awake);
requestWake(io, 16);
thread.join();
// The 16 ms request lands about 66 ms in: well before the 800 ms one
// would have, however loaded the machine.
try std.testing.expect(done.load(.acquire) - start < 700 * std.time.ns_per_ms);
}
fn wakeFs(ctx: ?*anyopaque) void {
const loop: *Loop = @ptrCast(@alignCast(ctx.?));
_ = loop.tryPostEvent(.fs_ready) catch {};
}
/// Each pane's reads posted and not yet taken in. Two at most: a flood the
/// loop cannot keep up with waits in its pty, not in the queue ahead of a
/// key and its echo (hundreds of 4 KB reads queued were half a second).
var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0));
/// A read of pane `id` taken in (or dropped): its reader may read on. Never
/// below zero, for an event no reader posted (a test's).
fn tookRead(io: std.Io, id: usize) void {
var queued = reads_queued[id].load(.acquire);
while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse {
if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1);
return;
};
}
fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void {
// One buffer, read into directly: a Reader around it only added a second
// (and in a safe build, filled both as `undefined` on every start).
var buf: [0x10000]u8 = undefined;
read: while (true) {
while (true) {
const queued = reads_queued[id].load(.acquire);
if (queued < 2) break;
io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read;
}
const n = pty.readStreaming(io, &.{&buf}) catch break;
if (n == 0) break;
const bytes = try gpa.dupe(u8, buf[0..n]);
_ = reads_queued[id].fetchAdd(1, .acq_rel);
loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch {
tookRead(io, id);
gpa.free(bytes);
break;
};
}
_ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {};
}
const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes;
fn pasteBytes(key: vaxis.Key) []const u8 {
const text = key.text orelse "";
if (text.len > 0) return text;
const cp = vaxis_input.mapKey(vaxis_input.effCp(key));
if (cp == pardes.Key.tab) return "\t";
if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) return "\n";
return "";
}
test "a terminal pane gets function keys as their sequences and lone modifiers not at all" {
if (comptime builtin.os.tag == .windows) return error.SkipZigTest;
const gpa = std.testing.allocator;
const io = std.testing.io;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(io, gpa, &env, .{});
var output: std.Io.Writer.Allocating = .init(gpa);
defer output.deinit();
defer vx.deinit(gpa, &output.writer);
vx.queries_done.store(false, .unordered);
var tty: vaxis.Tty = undefined;
var loop: Loop = .init(io, &tty, &vx);
var feed: Feed = .{};
const Reader = struct {
parts: []const []const u8,
next: usize = 0,
fn getWinsize(_: *@This()) !vaxis.Winsize {
return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
}
pub fn inputFollows(self: *@This(), _: u32) bool {
return self.next < self.parts.len;
}
fn read(self: *@This(), buf: []u8) !usize {
if (self.next == self.parts.len) return 0;
const part = self.parts[self.next];
self.next += 1;
@memcpy(buf[0..part.len], part);
return part.len;
}
};
var reader: Reader = .{
.parts = &.{
// The startup width queries' answers from a terminal without
// explicit width (foot, ghostty, tmux): two F3s, typed at the prompt.
"\x1b[1;1R\x1b[1;1R\x1b[?62;c",
// Kitty reports Ctrl and Shift pressed on their own: the Ctrl of a
// Ctrl-V typed `\x1b[57442;5u` into the shell.
"\x1b[57442;5u\x1b[57441;2u\x1b[57358u",
// F3, F5 and Insert the kitty way, F3 the legacy way and the
// keypad's Up: once typed as private-use junk, now what htop,
// mc and vim read them as.
"\x1b[13~\x1b[15~\x1b[2~\x1bOR\x1b[57419u",
"\x1b[104;;104u",
},
};
try readInput(&loop, &reader, &vx, &feed);
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer core.deinit();
core.panes[0].?.body.mode = .tty;
while (core.nextEffect()) |_| {}
while (try loop.tryEvent()) |event| switch (event) {
.key_press => |key| core.update(vaxis_input.keyEvent(key)),
else => {},
};
var written: std.Io.Writer.Allocating = .init(gpa);
defer written.deinit();
while (core.nextEffect()) |effect| {
if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice());
}
try std.testing.expectEqualStrings("\x1bOR\x1b[15~\x1b[2~\x1bOR\x1b[Ah", written.written());
}
test "the terminal's keys reach a program as its cursor keys' mode and keyboard flags say" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer core.deinit();
core.panes[0].?.body.mode = .tty;
while (core.nextEffect()) |_| {}
var written: std.Io.Writer.Allocating = .init(gpa);
defer written.deinit();
// What the outer terminal sends, what the program asked for, and what
// it should read.
const Case = struct { modes: []const u8, in: []const u8, sent: []const u8 };
const cases = [_]Case{
.{ .modes = "", .in = "\x1b[A\x1b[H\x1bOP\x1b[15~", .sent = "\x1b[A\x1b[H\x1bOP\x1b[15~" },
.{ .modes = "\x1b[?1h", .in = "\x1b[A\x1b[F\x1b[1;5D", .sent = "\x1bOA\x1bOF\x1b[1;5D" },
.{ .modes = "\x1b[?1l\x1b[>7u", .in = "\x1b[99;5u\x1b[97;3u\x1b[A", .sent = "\x1b[99;5u\x1b[97;3u\x1b[1;1:1A" },
};
for (cases) |case| {
core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } });
while (core.nextEffect()) |_| {}
var parser: vaxis.Parser = .{};
var bytes = case.in;
while (bytes.len > 0) {
const result = try parser.parse(bytes, gpa);
if (result.n == 0) break;
bytes = bytes[result.n..];
if (result.event) |event| switch (event) {
.key_press => |key| core.update(vaxis_input.keyEvent(key)),
else => {},
};
}
written.clearRetainingCapacity();
while (core.nextEffect()) |effect| {
if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice());
}
try std.testing.expectEqualStrings(case.sent, written.written());
}
}
test "keypad Enter matches Return for editor input terminal writes and paste" {
for ([_]u21{ vaxis.Key.enter, vaxis.Key.kp_enter }) |codepoint| {
const key: vaxis.Key = .{ .codepoint = codepoint };
const event = vaxis_input.keyEvent(key);
try std.testing.expectEqual(pardes.Key.enter, event.key.cp);
try std.testing.expectEqualStrings("\n", pasteBytes(key));
{
const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer core.deinit();
const pane = try core.setTestFile("ab");
core.update(.{ .key = .{ .cp = 'i' } });
core.update(event);
try std.testing.expectEqualStrings("\nab", pane.file.?.content);
}
{
const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer core.deinit();
core.panes[0].?.body.mode = .tty;
while (core.nextEffect()) |_| {}
core.update(event);
var written: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer written.deinit();
while (core.nextEffect()) |effect| {
if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice());
}
try std.testing.expectEqualStrings("\r", written.written());
}
}
}
fn mouseEvent(m: vaxis.Mouse) ?pardes.Event {
const button: pardes.Mouse.Button = switch (m.button) {
.left => .left,
.middle => .middle,
.right => .right,
.wheel_up => .wheel_up,
.wheel_down => .wheel_down,
.wheel_left => .wheel_left,
.wheel_right => .wheel_right,
// A mouse's side buttons, as xterm reports them: Back and Forward.
.button_8 => .back,
.button_9 => .forward,
.none => .none, // button-less motion: hover tracking
else => return null,
};
return .{ .mouse = .{
.button = button,
.kind = switch (m.type) {
.press => .press,
.release => .release,
.motion => .motion,
.drag => .drag,
},
.col = cellOf(m.col),
.row = cellOf(m.row),
.ctrl = m.mods.ctrl,
.shift = m.mods.shift,
.alt = m.mods.alt,
} };
}
/// A report's cell, 0-based: one before the first (SGR's 0, a drag past
/// the window's top or left edge, in cells or in 1016's pixels) is the
/// first, never a panic; past the far edge the core clamps it.
pub fn cellOf(v: i16) u16 {
return @intCast(@max(0, v));
}
test "a mouse report at row or column 0, or before it, is the window's edge, never a panic" {
const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
for ([_][]const u8{ "\x1b[<1;42;0M", "\x1b[<0;0;5M", "\x1b[<32;0;0M", "\x1b[<0;0;0m" }) |sequence| {
var parser: vaxis.Parser = .{};
const result = try parser.parse(sequence, std.testing.allocator);
const m = result.event.?.mouse;
const event = mouseEvent(m) orelse continue;
try std.testing.expect(event.mouse.col <= 41 and event.mouse.row <= 4);
p.update(event);
}
}
test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 and X2 are" {
for ([_]vaxis.Mouse.Button{ .button_8, .button_9 }, [_]pardes.Mouse.Button{ .back, .forward }) |from, to| {
const event = mouseEvent(.{ .col = 3, .row = 2, .button = from, .mods = .{}, .type = .press }).?;
try std.testing.expectEqual(to, event.mouse.button);
}
}
/// A blank whose ink alone changed is not sent: vaxis's render skips it
/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows
/// nowhere. Deciding that here cost every cell of every frame a look at the
/// frame before; vaxis already makes that comparison.
fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void {
win.clear();
var y: u16 = 0;
while (y < rows) : (y += 1) {
var x: u16 = 0;
while (x < cols) : (x += 1) {
const cell = &cells[@as(usize, y) * cols + x];
if (cell.default) continue;
win.writeCell(x, y, .{
.char = .{ .grapheme = cell.grapheme() },
.style = vaxisStyle(cell.style),
});
}
}
}
test "a fade sends the text it dims, not the blanks beside it" {
const gpa = std.testing.allocator;
var env = try std.testing.environ.createMap(gpa);
defer env.deinit();
var vx = try vaxis.init(std.testing.io, gpa, &env, .{});
var out: std.Io.Writer.Allocating = .init(gpa);
defer out.deinit();
defer vx.deinit(gpa, &out.writer);
try vx.resize(gpa, &out.writer, .{ .rows = 1, .cols = 32, .x_pixel = 0, .y_pixel = 0 });
// `a`, a gap, `b`, a two-cell gap, `c`, a gap, an underlined blank
// (which shows its ink) and one more blank.
var cells: [32]pardes.Cell = @splat(.{ .default = false });
cells[0].text[0] = 'a';
cells[12].text[0] = 'b';
cells[15].text[0] = 'c';
cells[30].style.ul = .single;
var sent: [2][]u8 = .{ &.{}, &.{} };
defer for (sent) |bytes| gpa.free(bytes);
for ([_][3]u8{ .{ 200, 200, 200 }, .{ 90, 90, 90 } }, 0..) |ink, frame| {
for (&cells) |*cell| cell.style.fg = .{ .rgb = ink };
out.clearRetainingCapacity();
paintCells(vx.window(), &cells, 32, 1);
try vx.render(&out.writer);
sent[frame] = try out.toOwnedSlice();
}
// Against a cleared screen every cell goes. After the fade the letters
// go and the underlined blank; every plain blank is jumped.
try std.testing.expectEqual(@as(usize, 29), std.mem.count(u8, sent[0], " "));
try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, sent[1], " "));
try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'b') != null);
try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'c') != null);
try std.testing.expect(std.mem.indexOf(u8, sent[1], "90:90:90") != null);
try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'a') != null);
}
/// T1 (§9.2): each notice chip casts a shadow one cell right and one down,
/// inside its own pane's body: its ground 35% toward black in OKLab on a
/// cell with text; on a blank one a half block (▌ on the right, ▀ below,
/// ▘ at the corner) in the darker colour, so the shadow is half a cell
/// thick and reads as one. Never the cursor's cell, a selection, a tag or
/// another chip. Truecolor terminals only.
fn chipShadows(arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface {
if (!core.settings.chip_shadow or !truecolor) return surface;
const regions = surface.regionList();
const any = for (regions) |region| {
if (region.kind == .notice) break true;
} else false;
if (!any) return surface;
const out = try arena.create(pardes.Surface);
out.* = surface.*;
out.cells = try arena.dupe(pardes.Cell, surface.cells);
const theme = core.theme();
const page = theme.bg orelse pardes.colors.null_page;
for (regions) |chip| {
if (chip.kind != .notice or chip.rect.w == 0) continue;
const body = for (regions) |region| {
if (region.kind == .body and region.owner == chip.owner) break region.rect;
} else continue;
const right = chip.rect.x + chip.rect.w;
const below = chip.rect.y + chip.rect.h;
// The column right of it (from its second row), the row below (from
// its second column), and the corner.
var y = chip.rect.y;
while (y <= below) : (y += 1) {
var x = chip.rect.x;
while (x <= right) : (x += 1) {
const side = x == right and y > chip.rect.y and y < below;
const foot = y == below and x > chip.rect.x and x < right;
const corner = x == right and y == below;
if (!side and !foot and !corner) continue;
if (x < body.x or y < body.y or x >= body.x + body.w or y >= body.y + body.h or x >= out.cols or y >= out.rows) continue;
if (surface.cursor) |cu| if (cu.x == x and cu.y == y) continue;
const covered = for (regions) |region| {
if ((region.kind == .notice or region.kind == .tag or region.kind == .grip) and x >= region.rect.x and x < region.rect.x + region.rect.w and y >= region.rect.y and y < region.rect.y + region.rect.h) break true;
} else false;
if (covered) continue;
const cell = &out.cells[@as(usize, y) * out.cols + x];
const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) {
.rgb => |rgb| rgb,
else => page,
};
if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue;
const dark = pardes.colors.mixOklab(ground, .{ 0, 0, 0 }, 0.35);
const blank = cell.default or cell.len == 0 or (cell.len == 1 and cell.text[0] == ' ');
if (blank) {
const glyph: []const u8 = if (corner) "▘" else if (side) "▌" else "▀";
cell.* = .{ .default = false, .style = .{ .fg = .{ .rgb = dark }, .bg = .{ .rgb = ground } } };
@memcpy(cell.text[0..glyph.len], glyph);
cell.len = @intCast(glyph.len);
} else {
cell.default = false;
cell.style.bg = .{ .rgb = dark };
}
}
}
}
return out;
}
/// T7 (§9.2): a pane whose view moved (Region.line) has its scroll thumb
/// brighten, drawn most of the way to the text's colour, and fade back
/// over 250 ms with an ease-out: where you are in the file, as you move.
/// The rail is chrome, not a focus indicator. Truecolor terminals only.
const ThumbFlash = struct {
lines: [pardes.MAX_PANES]i32 = @splat(std.math.minInt(i32)),
since: [pardes.MAX_PANES]u64 = @splat(0),
const life_ns: u64 = 250 * std.time.ns_per_ms;
fn apply(flash: *ThumbFlash, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface {
const on = core.settings.thumb_flash and truecolor and core.settings.motion != .off;
var out: ?*pardes.Surface = null;
const theme = core.theme();
const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc };
for (surface.regionList()) |body| {
if (body.kind != .body or body.owner >= flash.lines.len) continue;
const id = body.owner;
if (flash.lines[id] != std.math.minInt(i32) and flash.lines[id] != body.line) flash.since[id] = core.now_ns;
flash.lines[id] = body.line;
const age = core.now_ns -| flash.since[id];
if (!on or flash.since[id] == 0 or age >= life_ns) continue;
const rail = for (surface.regionList()) |region| {
if (region.kind == .rail and region.owner == id) break region;
} else continue;
if (rail.thumb_h == 0) continue;
const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns));
const strength = 0.6 * (1 - t) * (1 - t);
if (out == null) {
const copy = try arena.create(pardes.Surface);
copy.* = surface.*;
copy.cells = try arena.dupe(pardes.Cell, surface.cells);
out = copy;
}
const o = out.?;
var y = rail.rect.y + rail.thumb_y;
while (y < rail.rect.y + rail.thumb_y + rail.thumb_h and y < o.rows) : (y += 1) {
var x = rail.rect.x;
while (x < rail.rect.x + rail.rect.w and x < o.cols) : (x += 1) {
const cell = &o.cells[@as(usize, y) * o.cols + x];
const ground: [3]u8 = switch (cell.style.bg) {
.rgb => |rgb| rgb,
else => continue,
};
if (!std.mem.eql(u8, &ground, &core.chromeTheme().scroll_thumb)) continue;
cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) };
}
}
core.shell_continuous = true;
}
return out orelse surface;
}
};
/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does
/// not answer vaxis's query (§9.2: vaxis caps or COLORTERM).
fn colortermTruecolor() bool {
const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false);
return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit");
}
/// T2 (docs/render-pipeline.md §9.2): the cursor jumping three cells or
/// more leaves a trail of three to five cells along its path, just behind
/// it, their ground drawn toward the text's colour, most beside the
/// cursor, all fading out over 120 ms. Truecolor terminals only; a cell a
/// frame changes, a few bytes. Never the cursor's own cell, a selection or
/// anything outside the focused pane's body; off with Motion off.
const JumpTrail = struct {
last: ?[2]u16 = null,
from: [2]u16 = .{ 0, 0 },
to: [2]u16 = .{ 0, 0 },
start_ns: u64 = 0,
active: bool = false,
const life_ns: u64 = 120 * std.time.ns_per_ms;
fn apply(trail: *JumpTrail, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface {
defer core.shell_continuous = trail.active or core.shell_continuous;
const on = core.settings.jump_trail and truecolor and core.settings.motion != .off;
const cursor = surface.cursor orelse {
trail.active = false;
return surface;
};
const here: [2]u16 = .{ cursor.x, cursor.y };
if (trail.last) |was| {
const dx = @as(i32, here[0]) - was[0];
const dy = @as(i32, here[1]) - was[1];
if (on and @max(@abs(dx), @abs(dy)) >= 3) {
trail.* = .{ .last = here, .from = was, .to = here, .start_ns = core.now_ns, .active = true };
}
}
trail.last = here;
if (!on or !trail.active) {
trail.active = false;
return surface;
}
const age = core.now_ns -| trail.start_ns;
if (age >= life_ns or !std.meta.eql(trail.to, here)) {
trail.active = false;
return surface;
}
const out = try arena.create(pardes.Surface);
out.* = surface.*;
out.cells = try arena.dupe(pardes.Cell, surface.cells);
const theme = core.theme();
const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc };
const page = theme.bg orelse pardes.colors.null_page;
const body = for (surface.regionList()) |region| {
if (region.kind == .body and region.owner == core.active) break region.rect;
} else return out;
const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns));
const fade = (1 - t) * (1 - t);
const dx = @as(f32, @floatFromInt(@as(i32, trail.from[0]) - trail.to[0]));
const dy = @as(f32, @floatFromInt(@as(i32, trail.from[1]) - trail.to[1]));
const span = @max(@abs(dx), @abs(dy));
const n: usize = @intFromFloat(std.math.clamp(@round(span / 4), 3, 5));
var k: usize = 1;
var last_cell: ?[2]i32 = null;
var step: f32 = 1;
while (k <= n and step <= span) : (step += 1) {
const x: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[0])) + dx * step / span));
const y: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[1])) + dy * step / span));
if (last_cell) |seen| if (seen[0] == x and seen[1] == y) continue;
last_cell = .{ x, y };
defer k += 1;
if (x < body.x or y < body.y or x >= @as(i32, body.x) + body.w or y >= @as(i32, body.y) + body.h) continue;
const cell = &out.cells[@as(usize, @intCast(y)) * out.cols + @as(usize, @intCast(x))];
const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) {
.rgb => |rgb| rgb,
else => page,
};
if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue;
const strength = 0.55 * fade * (1 - @as(f32, @floatFromInt(k - 1)) / @as(f32, @floatFromInt(n)));
if (strength < 0.02) continue;
const was_default = cell.default;
cell.default = false;
if (was_default) cell.style = .{};
cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) };
}
return out;
}
};
fn paintCursor(win: vaxis.Window, x: u16, y: u16, bar: bool) void {
win.showCursor(x, y);
win.setCursorShape(if (bar) .beam else .default);
}
fn vaxisStyle(s: pardes.CellStyle) vaxis.Style {
return .{
.fg = vaxisColor(s.fg),
.bg = vaxisColor(s.bg),
.bold = s.bold,
.dim = s.dim,
.italic = s.italic,
.blink = s.blink,
.reverse = s.reverse,
.invisible = s.invisible,
.strikethrough = s.strikethrough,
.ul_style = switch (s.ul) {
.off => .off,
.single => .single,
.double => .double,
.curly => .curly,
.dotted => .dotted,
.dashed => .dashed,
},
};
}
fn vaxisColor(c: pardes.Color) vaxis.Color {
return switch (c) {
.default => .default,
.index => |i| .{ .index = i },
.rgb => |rgb| .{ .rgb = rgb },
};
}
test "a jump leaves a trail of a few cells behind the cursor that fades in 120 ms" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer core.deinit();
_ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*))));
try std.testing.expect(core.executeBuiltinLine(0, "Theme forge"));
core.settings.jump_trail = true;
for (0..40) |_| core.update(.tick);
core.sync();
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const s = try core.render(arena.allocator());
const body = for (s.regionList()) |region| {
if (region.kind == .body) break region.rect;
} else return error.NoBody;
var trail: JumpTrail = .{};
core.now_ns = std.time.ns_per_s;
s.cursor = .{ .x = body.x + 2, .y = body.y + 1 };
_ = try trail.apply(arena.allocator(), s, core, true);
// Ten cells right: a trail back toward where it was.
s.cursor = .{ .x = body.x + 12, .y = body.y + 1 };
core.now_ns += 16 * std.time.ns_per_ms;
const lit = try trail.apply(arena.allocator(), s, core, true);
try std.testing.expect(trail.active and core.shell_continuous);
var changed: usize = 0;
for (lit.cells, s.cells, 0..) |a, b, i| {
if (std.meta.eql(a.style.bg, b.style.bg)) continue;
changed += 1;
// On the cursor's row, behind it, never its own cell.
try std.testing.expectEqual(@as(usize, body.y + 1), i / s.cols);
try std.testing.expect(i % s.cols < body.x + 12 and i % s.cols > body.x + 2);
}
try std.testing.expect(changed >= 3 and changed <= 5);
// Gone by 120 ms; a step of a cell leaves none; nor a terminal without
// truecolor.
core.now_ns += 130 * std.time.ns_per_ms;
core.shell_continuous = false;
const faded = try trail.apply(arena.allocator(), s, core, true);
try std.testing.expect(faded == s and !trail.active and !core.shell_continuous);
s.cursor = .{ .x = body.x + 13, .y = body.y + 1 };
try std.testing.expect(try trail.apply(arena.allocator(), s, core, true) == s);
s.cursor = .{ .x = body.x + 2, .y = body.y + 1 };
try std.testing.expect(try trail.apply(arena.allocator(), s, core, false) == s);
}
test "a notice chip casts a cell's shadow right and down, inside its body, off the cursor" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer core.deinit();
_ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*))));
try std.testing.expect(core.executeBuiltinLine(0, "Theme forge"));
core.settings.chip_shadow = true;
try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice"));
for (0..60) |_| core.update(.tick);
core.sync();
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const s = try core.render(arena.allocator());
const chip = for (s.regionList()) |region| {
if (region.kind == .notice) break region.rect;
} else return error.NoNotice;
s.cursor = null;
const out = try chipShadows(arena.allocator(), s, core, true);
try std.testing.expect(out != s);
var changed: usize = 0;
for (out.cells, s.cells, 0..) |a, b, i| {
if (std.meta.eql(a, b)) continue;
changed += 1;
const x = i % s.cols;
const y = i / s.cols;
// Right of the chip or below it, never inside it.
try std.testing.expect(x == chip.x + chip.w or y == chip.y + chip.h);
try std.testing.expect(!(x >= chip.x and x < chip.x + chip.w and y >= chip.y and y < chip.y + chip.h));
}
try std.testing.expect(changed >= chip.w - 1);
// Off, or without truecolor: the frame as it was.
try std.testing.expect(try chipShadows(arena.allocator(), s, core, false) == s);
core.settings.chip_shadow = false;
try std.testing.expect(try chipShadows(arena.allocator(), s, core, true) == s);
}
test "a scrolled pane's thumb brightens and fades back in 250 ms" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer core.deinit();
const pane = try core.setTestFile(std.mem.asBytes(&@as([200][20]u8, @splat("some text on a line\n".*))));
try std.testing.expect(core.executeBuiltinLine(0, "Theme forge"));
core.settings.thumb_flash = true;
for (0..40) |_| core.update(.tick);
core.sync();
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
var flash: ThumbFlash = .{};
core.now_ns = std.time.ns_per_s;
const first = try core.render(arena.allocator());
try std.testing.expect(try flash.apply(arena.allocator(), first, core, true) == first);
pane.scrollBy(20);
core.now_ns += 16 * std.time.ns_per_ms;
const moved = try core.render(arena.allocator());
const lit = try flash.apply(arena.allocator(), moved, core, true);
try std.testing.expect(lit != moved and core.shell_continuous);
var brighter: usize = 0;
for (lit.cells, moved.cells) |a, b| {
if (!std.meta.eql(a.style.bg, b.style.bg)) brighter += 1;
}
try std.testing.expect(brighter >= 1);
core.now_ns += 300 * std.time.ns_per_ms;
core.shell_continuous = false;
const later = try core.render(arena.allocator());
try std.testing.expect(try flash.apply(arena.allocator(), later, core, true) == later);
try std.testing.expect(!core.shell_continuous);
}
|