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
|
//! Colour themes: the curated and generated ring, every colour a surface
//! draws worked out from a theme once (`Chrome`, DESIGN.md B4 and B6, the
//! themes programme's), theme files, and switching themes at runtime.
//! What a theme says is theme_schema.zig's.
const pardes = @import("root.zig");
const builtin = @import("builtin");
const schema = @import("theme_schema.zig");
pub const Theme = schema.Theme;
pub const LegacyTheme = schema.LegacyTheme;
const tagline = @import("tagline.zig");
const panes = @import("panes.zig");
const std = @import("std");
const Color = @import("surface.zig").Color;
const FontRole = @import("surface.zig").FontRole;
const config = @import("config.zig");
const platform = pardes.platform;
const BOX_H = pardes.BOX_H;
const Pardes = pardes.Pardes;
/// The 256-colour palette a terminal starts from (its emulator's default):
/// sixteen named colours, a 6x6x6 cube at xterm's levels (0, then 95 to
/// 255 by 40) and a ramp of 24 greys from 8 by 10.
pub const xterm: [256][3]u8 = blk: {
var p: [256][3]u8 = undefined;
p[0..16].* = .{
.{ 0x1D, 0x1F, 0x21 }, // black
.{ 0xCC, 0x66, 0x66 }, // red
.{ 0xB5, 0xBD, 0x68 }, // green
.{ 0xF0, 0xC6, 0x74 }, // yellow
.{ 0x81, 0xA2, 0xBE }, // blue
.{ 0xB2, 0x94, 0xBB }, // magenta
.{ 0x8A, 0xBE, 0xB7 }, // cyan
.{ 0xC5, 0xC8, 0xC6 }, // white
.{ 0x66, 0x66, 0x66 }, // bright black
.{ 0xD5, 0x4E, 0x53 }, // bright red
.{ 0xB9, 0xCA, 0x4A }, // bright green
.{ 0xE7, 0xC5, 0x47 }, // bright yellow
.{ 0x7A, 0xA6, 0xDA }, // bright blue
.{ 0xC3, 0x97, 0xD8 }, // bright magenta
.{ 0x70, 0xC0, 0xB1 }, // bright cyan
.{ 0xEA, 0xEA, 0xEA }, // bright white
};
for (0..216) |i| {
for (0..3, [3]usize{ i / 36, i / 6 % 6, i % 6 }) |c, v| p[16 + i][c] = if (v == 0) 0 else 55 + 40 * v;
}
for (0..24) |i| p[232 + i] = @splat(8 + 10 * i);
break :blk p;
};
/// sRGB channel to linear light.
pub const to_linear: [256]f32 = blk: {
@setEvalBranchQuota(100_000);
var table: [256]f32 = undefined;
for (&table, 0..) |*out, i| {
const c = @as(f64, @floatFromInt(i)) / 255;
out.* = @floatCast(if (c <= 0.04045) c / 12.92 else std.math.pow(f64, (c + 0.055) / 1.055, 2.4));
}
break :blk table;
};
/// WCAG relative luminance, and the contrast of two colours.
pub fn relativeLuminance(rgb: [3]u8) f32 {
return 0.2126 * to_linear[rgb[0]] + 0.7152 * to_linear[rgb[1]] + 0.0722 * to_linear[rgb[2]];
}
pub fn contrast(a: [3]u8, b: [3]u8) f32 {
return luminanceContrast(relativeLuminance(a), relativeLuminance(b));
}
fn luminanceContrast(x: f32, y: f32) f32 {
return (@max(x, y) + 0.05) / (@min(x, y) + 0.05);
}
/// The rules between panes and columns: acme's contrast, black on white.
/// A theme's own rule, or its rail, as long as it stands off the page by
/// 1.5:1; one that does not (on a near-black page, a dark rule all but
/// vanishes) is held until it does, to 1.6:1 (R11, Chrome.separator_lift).
pub const separator_floor: f32 = 1.5;
/// The page a theme with none (`dark`: the host's own) is judged against:
/// the GUI's default ground, and a dark terminal's.
pub const null_page: [3]u8 = .{ 18, 18, 18 };
/// The ink of a theme with none, on a dark page and on a light one.
pub const null_text: [3]u8 = .{ 0xcc, 0xcc, 0xcc };
const null_text_light: [3]u8 = .{ 0x22, 0x22, 0x22 };
/// sRGB bytes to OKLab and back (Björn Ottosson's), and a mix in it.
fn toOklab(rgb: [3]u8) [3]f32 {
var l: [3]f32 = undefined;
for (&l, rgb) |*out, v| {
const x = @as(f32, @floatFromInt(v)) / 255;
out.* = if (x <= 0.04045) x / 12.92 else std.math.pow(f32, (x + 0.055) / 1.055, 2.4);
}
const lm = std.math.cbrt(0.4122214708 * l[0] + 0.5363325363 * l[1] + 0.0514459929 * l[2]);
const mm = std.math.cbrt(0.2119034982 * l[0] + 0.6806995451 * l[1] + 0.1073969566 * l[2]);
const sm = std.math.cbrt(0.0883024619 * l[0] + 0.2817188376 * l[1] + 0.6299787005 * l[2]);
return .{
0.2104542553 * lm + 0.7936177850 * mm - 0.0040720468 * sm,
1.9779984951 * lm - 2.4285922050 * mm + 0.4505937099 * sm,
0.0259040371 * lm + 0.7827717662 * mm - 0.8086757660 * sm,
};
}
fn oklabLinear(lab: [3]f32) [3]f32 {
const lm = lab[0] + 0.3963377774 * lab[1] + 0.2158037573 * lab[2];
const mm = lab[0] - 0.1055613458 * lab[1] - 0.0638541728 * lab[2];
const sm = lab[0] - 0.0894841775 * lab[1] - 1.2914855480 * lab[2];
const l = lm * lm * lm;
const m = mm * mm * mm;
const s = sm * sm * sm;
return .{
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
};
}
fn fromOklab(lab: [3]f32) [3]u8 {
const linear = oklabLinear(lab);
var out: [3]u8 = undefined;
for (&out, linear) |*o, v| {
const x = std.math.clamp(v, 0, 1);
const srgb = if (x <= 0.0031308) x * 12.92 else 1.055 * std.math.pow(f32, x, 1.0 / 2.4) - 0.055;
o.* = @intFromFloat(@round(std.math.clamp(srgb, 0, 1) * 255));
}
return out;
}
pub fn mixOklab(a: [3]u8, b: [3]u8, t: f32) [3]u8 {
if (std.mem.eql(u8, &a, &b)) return a;
const x = toOklab(a);
const y = toOklab(b);
return fromOklab(.{ x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t, x[2] + (y[2] - x[2]) * t });
}
fn oklabDistance(a: [3]f32, b: [3]f32) f32 {
return @sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2]));
}
/// How far a name's tint stands off its tag's ink in OKLab: a hue you see
/// at a glance, not a shade you look for.
pub const name_tint_distance: f32 = 0.07;
/// How much hue a colour needs to lend a name its tint.
const name_tint_chroma: f32 = 0.06;
/// A name's tint for a theme that sets none (the faithful ports, the
/// imports, a theme file): a hue of the theme's own -- its keyword colour,
/// else the first of its ANSI accents, syntax, grip, selection or
/// diagnostic colours that has one -- at the lightness nearest the tag's
/// ink where that hue holds, the name reads on its ground (nameTintFloor)
/// and it stands off the ink. Null when no colour of the theme will do.
fn derivedNameTint(th: *const Theme, ink: [3]u8, ground: [3]u8) ?[3]u8 {
const pal = th.ansi orelse @as([16][3]u8, @splat(th.keyword));
const sources = [_][3]u8{ th.keyword, pal[4], pal[5], pal[6], pal[3], pal[2], pal[1], th.number, th.string, th.accent } ++
[_][3]u8{ th.column_grip orelse th.number, th.dirty orelse th.number, th.selection, th.hit orelse th.number } ++
[_][3]u8{ th.info orelse th.number, th.hint orelse th.number, th.warning orelse th.number } ++
// A theme with no hue of its own at all (flatwhite): acme's DMedblue's.
[_][3]u8{.{ 0x00, 0x00, 0x99 }};
// Near the ink's lightness first, from any of the theme's hues; only
// then further off it.
// then further off it (the near steps already tried).
for ([2][2]f32{ .{ -1, 0.15 }, .{ 0.15, 1 } }) |steps| for (sources, 0..) |source, i| {
// A hue already tried finds nothing again.
const tried = for (sources[0..i]) |before| {
if (std.mem.eql(u8, &before, &source)) break true;
} else false;
if (tried) continue;
if (nameTintFrom(toOklab(source), ink, ground, steps[0], steps[1])) |tint| return tint;
};
return null;
}
/// A name's tint from `source`'s hue: the first, by its lightness's step
/// off the ink's (over `tried`, up to `reach`), then by the most chroma,
/// that reads on `ground` and stands off the ink.
fn nameTintFrom(source: [3]f32, ink: [3]u8, ground: [3]u8, tried: f32, reach: f32) ?[3]u8 {
const chroma = @sqrt(source[1] * source[1] + source[2] * source[2]);
if (chroma < name_tint_chroma) return null;
const ink_lab = toOklab(ink);
const floor = nameTintFloor(ink, ground);
const ground_y = relativeLuminance(ground);
var step: f32 = 0;
while (step <= reach) : (step += 0.01) {
if (step <= tried) continue;
for ([2]f32{ 1, -1 }) |sign| {
const lightness = ink_lab[0] + sign * step;
if (lightness < 0 or lightness > 1) continue;
// As much of the hue as that lightness holds, up to a tint's.
var want = @min(chroma, 0.12);
while (want >= 0.04) : (want -= 0.01) {
const lab: [3]f32 = .{ lightness, source[1] / chroma * want, source[2] / chroma * want };
const linear = oklabLinear(lab);
const in_gamut = for (linear) |v| {
if (v < -0.001 or v > 1.001) break false;
} else true;
if (!in_gamut) continue;
// A certain miss by its luminance before the bytes round it
// (they move it by under 0.005) skips the conversion: the
// search's cost, never its answer.
const y = 0.2126 * std.math.clamp(linear[0], 0, 1) + 0.7152 * std.math.clamp(linear[1], 0, 1) + 0.0722 * std.math.clamp(linear[2], 0, 1);
if (@max(luminanceContrast(@max(y - 0.01, 0), ground_y), luminanceContrast(@min(y + 0.01, 1), ground_y)) < floor) continue;
const tint = fromOklab(lab);
if (contrast(tint, ground) < floor) continue;
if (oklabDistance(toOklab(tint), ink_lab) < name_tint_distance) continue;
return tint;
}
}
}
return null;
}
/// What a name's tint must read at on its ground: 4.5:1, or within half a
/// point of the ink's own where the ink has less to spare (seoulbones_dark's
/// near-white on grey leaves no hue at the ink's 4.53:1).
pub fn nameTintFloor(ink: [3]u8, ground: [3]u8) f32 {
return @min(4.5, contrast(ink, ground) - 0.5);
}
/// The derivations' OKLab, with no pow (B9's budget): a byte's linear
/// light from `to_linear`, and back to a byte by the light where its
/// rounding turns. `toOklab` and `fromOklab` (their f32 pow) stay the old
/// derivations' until those go, so no value they give moves.
fn labOf(rgb: [3]u8) [3]f32 {
const l = [3]f32{ to_linear[rgb[0]], to_linear[rgb[1]], to_linear[rgb[2]] };
const lm = std.math.cbrt(0.4122214708 * l[0] + 0.5363325363 * l[1] + 0.0514459929 * l[2]);
const mm = std.math.cbrt(0.2119034982 * l[0] + 0.6806995451 * l[1] + 0.1073969566 * l[2]);
const sm = std.math.cbrt(0.0883024619 * l[0] + 0.2817188376 * l[1] + 0.6299787005 * l[2]);
return .{
0.2104542553 * lm + 0.7936177850 * mm - 0.0040720468 * sm,
1.9779984951 * lm - 2.4285922050 * mm + 0.4505937099 * sm,
0.0259040371 * lm + 0.7827717662 * mm - 0.8086757660 * sm,
};
}
fn rgbOf(lab: [3]f32) [3]u8 {
return bytesOf(oklabLinear(lab));
}
fn bytesOf(linear: [3]f32) [3]u8 {
var out: [3]u8 = undefined;
for (&out, linear) |*o, v| {
// The bytes whose turn the light has passed: by halves.
const x = std.math.clamp(v, 0, 1);
var lo: usize = 0;
var hi: usize = byte_turns.len;
while (lo < hi) {
const mid = (lo + hi) / 2;
if (byte_turns[mid] <= x) lo = mid + 1 else hi = mid;
}
o.* = @intCast(lo);
}
return out;
}
/// The linear light at which a channel's byte turns from k to k + 1 (its
/// sRGB value k + 0.5 of 255).
const byte_turns: [255]f32 = blk: {
@setEvalBranchQuota(100_000);
var table: [255]f32 = undefined;
for (&table, 0..) |*out, k| {
const c = (@as(f64, @floatFromInt(k)) + 0.5) / 255;
out.* = @floatCast(if (c <= 0.04045) c / 12.92 else std.math.pow(f64, (c + 0.055) / 1.055, 2.4));
}
break :blk table;
};
/// The least contrast `ink` has on any of `grounds`.
fn leastContrast(ink: [3]u8, grounds: []const [3]u8) f32 {
var least: f32 = 21;
for (grounds) |g| least = @min(least, contrast(ink, g));
return least;
}
/// `toward` in the derivations' OKLab.
fn towardOf(ink: [3]u8, ground: [3]u8, floor: f32) [3]u8 {
var line: Line = .init(ink, ground);
return line.toward(floor);
}
/// The way from an ink to a ground in OKLab, by hundredths, each point
/// worked out once: `toward` for the several floors one ground's inks take
/// along it (its words, dim and rule).
const Line = struct {
a: [3]f32,
b: [3]f32,
ink: [3]u8,
ground: [3]u8,
at: [101]?[3]u8 = @splat(null),
fn init(ink: [3]u8, ground: [3]u8) Line {
return .{ .a = labOf(ink), .b = labOf(ground), .ink = ink, .ground = ground };
}
/// The ink as far toward the ground as it still reads `floor`:1 on it
/// (by halves: its contrast falls as it nears the ground).
fn toward(l: *Line, floor: f32) [3]u8 {
var best = l.ink;
var lo: u32 = 0;
var hi: u32 = 101;
while (hi - lo > 1) {
const mid = (lo + hi) / 2;
const c = l.at[mid] orelse point: {
const t = @as(f32, @floatFromInt(mid)) / 100;
const c = rgbOf(.{ l.a[0] + (l.b[0] - l.a[0]) * t, l.a[1] + (l.b[1] - l.a[1]) * t, l.a[2] + (l.b[2] - l.a[2]) * t });
l.at[mid] = c;
break :point c;
};
if (contrast(c, l.ground) >= floor) {
lo = mid;
best = c;
} else hi = mid;
}
return best;
}
};
/// Whether a colour reads as a dark ground (pardes's one threshold).
fn isDark(rgb: [3]u8) bool {
return relativeLuminance(rgb) < 0.18;
}
/// OKLab's lightness, chroma and hue (in degrees) of a colour.
fn lch(rgb: [3]u8) [3]f32 {
const lab = labOf(rgb);
const h = std.math.radiansToDegrees(std.math.atan2(lab[2], lab[1]));
return .{ lab[0], @sqrt(lab[1] * lab[1] + lab[2] * lab[2]), if (h < 0) h + 360 else h };
}
fn fromLch(l: f32, c: f32, h: f32) [3]u8 {
const r = std.math.degreesToRadians(h);
return rgbOf(.{ l, c * @cos(r), c * @sin(r) });
}
fn hueDistance(a: f32, b: f32) f32 {
const d = @abs(a - b);
return @min(d, 360 - d);
}
fn inGamut(lab: [3]f32) bool {
return linearInGamut(oklabLinear(lab));
}
fn linearInGamut(linear: [3]f32) bool {
for (linear) |v| if (v < -0.001 or v > 1.001) return false;
return true;
}
/// The colour at lightness `l` in the hue of (`a`, `b`), with as much of
/// that chroma, in fortieths, as the gamut holds there (found by halves).
fn clip(l: f32, a: f32, b: f32) [3]u8 {
const lightness = std.math.clamp(l, 0, 1);
const whole = oklabLinear(.{ lightness, a, b });
if (linearInGamut(whole)) return bytesOf(whole);
var lo: f32 = 0;
var hi: f32 = 40;
var kept = oklabLinear(.{ lightness, 0, 0 });
while (hi - lo > 1) {
const mid = @floor((lo + hi) / 2);
const m = oklabLinear(.{ lightness, a * mid / 40, b * mid / 40 });
if (linearInGamut(m)) {
lo = mid;
kept = m;
} else hi = mid;
}
return bytesOf(kept);
}
/// R0: `ink` held to `floor` on every one of `grounds` by its OKLab
/// lightness alone, toward whichever end reads better, its hue kept and its
/// chroma as the gamut allows there: a red stays red where a push toward
/// white would wash it out. Found by halves, eight mixes; where no
/// lightness reads, the end.
fn hold(ink: [3]u8, grounds: []const [3]u8, floor: f32) [3]u8 {
if (leastContrast(ink, grounds) >= floor) return ink;
const lab = labOf(ink);
const sign: f32 = if (leastContrast(@splat(255), grounds) >= leastContrast(@splat(0), grounds)) 1 else -1;
const reach = if (sign > 0) 1 - lab[0] else lab[0];
var best = clip(lab[0] + sign * reach, lab[1], lab[2]);
if (leastContrast(best, grounds) < floor) return best;
var lo: f32 = 0;
var hi = reach;
for (0..8) |_| {
const mid = (lo + hi) / 2;
const c = clip(lab[0] + sign * mid, lab[1], lab[2]);
if (leastContrast(c, grounds) >= floor) {
hi = mid;
best = c;
} else lo = mid;
}
return best;
}
/// R0: a ground `step`:1 off `ground` in lightness (lighter on a dark one),
/// carrying `chroma` of `hue`'s hue: tone says how strongly it asks, hue
/// what it is. Never so far that `ink` drops under `ink_floor` on it; as
/// far as 0.6 in lightness where the step is not reached. By halves.
fn hued(ground: [3]u8, hue: [3]u8, step: f32, chroma: f32, ink: ?[3]u8, ink_floor: f32) [3]u8 {
const g = labOf(ground);
const h = labOf(hue);
const n = @sqrt(h[1] * h[1] + h[2] * h[2]);
const a = g[1] + (if (n > 1e-6) h[1] / n else 0) * chroma;
const b = g[2] + (if (n > 1e-6) h[2] / n else 0) * chroma;
const sign: f32 = if (isDark(ground)) 1 else -1;
const start = clip(g[0], a, b);
if (ink) |i| if (contrast(i, start) < ink_floor) return start;
if (contrast(start, ground) >= step) return start;
// The least lightness that stands the step off, then, where the ink
// loses its floor there, the most the ink allows.
var lo: f32 = 0;
var hi: f32 = 0.6;
var at = clip(g[0] + sign * hi, a, b);
if (contrast(at, ground) >= step) for (0..8) |_| {
const mid = (lo + hi) / 2;
const c = clip(g[0] + sign * mid, a, b);
if (contrast(c, ground) >= step) {
hi = mid;
at = c;
} else lo = mid;
};
const i = ink orelse return at;
if (contrast(i, at) >= ink_floor) return at;
var keep = start;
lo = 0;
for (0..8) |_| {
const mid = (lo + hi) / 2;
const c = clip(g[0] + sign * mid, a, b);
if (contrast(i, c) >= ink_floor) {
lo = mid;
keep = c;
} else hi = mid;
}
return keep;
}
/// The six hues a terminal's palette names (R14), in its order from 1:
/// red, green, yellow, blue, magenta, cyan, as OKLab angles.
const ansi_hues = [6]f32{ 25, 145, 95, 255, 330, 195 };
/// A canonical hue at the text's lightness (eased into a readable band),
/// as much chroma as the gamut holds up to 0.13, held 4.5:1 on the page.
fn canonical(hue: f32, page: [3]u8, text: [3]u8) [3]u8 {
const lt = lch(text)[0];
const l = if (isDark(page)) std.math.clamp(lt, 0.72, 0.84) else std.math.clamp(lt, 0.40, 0.52);
const r = std.math.degreesToRadians(hue);
var c: f32 = 0.13;
while (c > 0.02 and !inGamut(.{ l, c * @cos(r), c * @sin(r) })) c -= 0.01;
return hold(fromLch(l, c, hue), &.{page}, Chrome.text_floor);
}
/// The theme's own colour nearest a hue (within 30 degrees, with 0.06 of
/// chroma or more), or null.
fn nearestOwn(hue: f32, own: []const ?[3]u8) ?[3]u8 {
var best: ?[3]u8 = null;
var best_d: f32 = 31;
for (own) |o| {
const c = o orelse continue;
const v = lch(c);
const d = hueDistance(v[2], hue);
if (v[1] >= 0.06 and d <= 30 and d < best_d) {
best = c;
best_d = d;
}
}
return best;
}
/// R14: a theme with no sixteen of its own gets them from its own hues
/// where it has them, else canonical ones at its text's lightness, each
/// held 4.5:1 on the page, a bright one 0.06 further from it; 0 the tag,
/// 7 and 8 the text toward the page to 7:1 and 3:1, 15 the text.
fn derivedAnsi(th: *const Theme, page: [3]u8, text: [3]u8) [16][3]u8 {
const own = [_]?[3]u8{ th.keyword, th.string, th.number, th.accent, th.@"error", th.warning, th.info, th.hint, th.added, th.deleted };
const step: f32 = if (isDark(page)) 0.06 else -0.06;
var pal: [16][3]u8 = undefined;
for (ansi_hues, 1..) |hue, i| {
const c = hold(nearestOwn(hue, &own) orelse canonical(hue, page, text), &.{page}, Chrome.text_floor);
pal[i] = c;
const v = lch(c);
const l = std.math.clamp(v[0] + step, 0, 1);
const r = std.math.degreesToRadians(v[2]);
const bright = if (inGamut(.{ l, v[1] * @cos(r), v[1] * @sin(r) })) fromLch(l, v[1], v[2]) else c;
pal[8 + i] = hold(bright, &.{page}, Chrome.text_floor);
}
pal[0] = th.tag;
pal[7] = towardOf(text, page, 7);
pal[8] = towardOf(text, page, 3);
pal[15] = text;
return pal;
}
/// Every colour a surface draws, worked out from a theme once (DESIGN.md
/// B4 R0-R16; B6 the set): a theme change or a preview resolves it, never a
/// frame, a row or a cell. Each ink is resolved per ground it is drawn on
/// (B1.3), never held to one floor across all of them.
pub const Chrome = struct {
/// The body's page and its inks.
page: Inks,
/// A tag's two grounds, plain and focused, in every mode (`Ground`;
/// R5', G1': the mode is a mark on the grip, never a ground).
tag: [2]Inks,
/// The notice row's (H: the window row and the column tags are drawn
/// on the page, in `page.word`).
status: Inks,
/// The theme leaves page, text and the sixteen to the host terminal
/// (`dark`): a terminal draws its own; a window, `null_page`.
host_page: bool,
/// Where the selection is drawn faintly: a second range, hover, a
/// selecting prompt's dim.
selection_secondary: [3]u8,
/// The pointer buttons' sweeps: select, exec, look (acme's meanings).
sweeps: [3]Theme.Sweep,
/// Search: a hit's ground, and the current one's ground and ink; a
/// search's last places while its field is no regex, dimmed: the page
/// halfway toward the hit (as `selection_secondary` is the selection's).
hit: [3]u8,
hit_current: [3]u8,
hit_current_text: [3]u8,
hit_faint: [3]u8,
add: Diff,
del: Diff,
/// The Changes layer's lanes, a pin each (`lanes_len` of them), and
/// churn's eight steps from cool to hot.
lanes: [8][3]u8,
lanes_len: u8,
heat: [8][3]u8,
grip: Grip,
rule: [3]u8,
tag_rule: [3]u8,
rail: [3]u8,
rail_thumb: [3]u8,
empty_column: [3]u8,
/// A syntax class's ink, by syntax.Syn: none (the text), keyword,
/// string, number, comment.
syntax: [5][3]u8,
line_number: [3]u8,
line_number_current: [3]u8,
/// A name's tint on the plain tag and on the focused one.
name: [2][3]u8,
ansi: [16][3]u8,
rule_px: u8,
rail_px: u8,
/// The inks one ground carries (B1.3): its text (the full ink: the
/// user's, a path, `Keep`), word (computed command words: the text
/// toward the ground to 4.5:1, H), dim (hints, meta, forward steps),
/// rule (spines), key (the accent: keys, `▶`, the walked word), match
/// (a query's letters), kind (a symbol's kind mark in a list, `t`,
/// `f`: the keyword's hue, which spells a kind in the text, held on the
/// ground and on its selection, a list's cursor row), the four
/// severities, and a selection rebuilt on it with its own.
pub const Inks = struct {
ground: [3]u8,
text: [3]u8,
word: [3]u8,
dim: [3]u8,
rule: [3]u8,
key: [3]u8,
match: [3]u8,
kind: [3]u8,
severity: [4][3]u8,
selection: Selection,
};
/// A selection on a ground, and that ground halfway to it (OKLab): a
/// second range, a hovered word (B5); the key and match inks held on
/// the selection, a ground of its own (B1.3: a list's cursor row).
pub const Selection = struct { ground: [3]u8, text: [3]u8, dim: [3]u8, secondary: [3]u8, key: [3]u8, match: [3]u8 };
pub const Ground = enum(u1) { plain, focus };
pub const Severity = enum(u2) { @"error", warning, info, hint };
/// A diff's rows: a row's ground, its changed words', a faint line's,
/// and its marker.
pub const Diff = struct { row: [3]u8, emph: [3]u8, line: [3]u8, ink: [3]u8 };
/// The grips: focused, its ring at rest, a reading pane's mark (its
/// ring; a terminal's cell) and that mark as a glyph on a focused grip,
/// unsaved, a column's grabbed and at rest, the ink on any fill, and a
/// message's mark on each fill a pane's grip has in a grid (`Fill`).
pub const Grip = struct { focus: [3]u8, ring: [3]u8, mode: [3]u8, mode_glyph: [3]u8, dirty: [3]u8, column: [3]u8, column_rest: [3]u8, ink: [3]u8, marks: [4]Marks };
/// A pane's grip in a grid, a cell: focused, unsaved (its second cell),
/// at rest its ring, a reading pane's its mode's mark (R5', R6).
pub const Fill = enum(u2) { focus, dirty, ring, mode };
/// A message's mark on a fill (Messages.inkOn): the severities and the
/// dim ink held there; at rest and reading on the plain tag too, where
/// a window draws those grips hollow (gui.zig gripFill).
pub const Marks = struct { severity: [4][3]u8, dim: [3]u8 };
// The floors (B4's table).
pub const text_floor: f32 = 4.5;
/// A tag's full ink, where its gamut allows (H).
pub const tag_text_floor: f32 = 7;
/// The plain tag off the page (H: K'5.7).
pub const band_floor: f32 = 1.1;
pub const dim_floor: f32 = 3.5;
pub const rule_ink: f32 = 2;
pub const focus_dark: f32 = 1.5;
pub const focus_light: f32 = 1.25;
pub const grip_floor: f32 = 3;
pub const ring_floor: f32 = 2;
pub const selection_dark: f32 = 1.4;
pub const selection_light: f32 = 1.25;
pub const hit_floor: f32 = 1.5;
pub const mode_floor: f32 = 3;
pub const severity_apart: f32 = 0.06;
pub const row_step: f32 = 1.15;
pub const emph_step: f32 = 1.45;
pub const line_step: f32 = 1.06;
pub const separator_lift: f32 = 1.6;
pub fn on(c: *const Chrome, g: Ground) *const Inks {
return &c.tag[@backingInt(g)];
}
pub fn of(th: *const Theme) Chrome {
var c: Chrome = undefined;
// R1, R2: one page for every derivation and frontend.
const page = th.page orelse null_page;
const dark = isDark(page);
const text = th.text orelse if (dark) null_text else null_text_light;
c.host_page = th.page == null;
// R14.
c.ansi = th.ansi orelse derivedAnsi(th, page, text);
const ansi = &c.ansi;
// R11's rule base (the theme's own tag: a lifted one is no rule).
const rule_base = th.rule orelse th.rail orelse th.tag;
c.rule = if (contrast(rule_base, page) >= separator_floor) rule_base else hold(rule_base, &.{page}, separator_lift);
// R3, R4 (H, G1'): the tag's two grounds, focus by tone alone. The
// plain tag a band 1.1:1 off the page (it is all that parts two
// panes in a terminal), unless rules of 3:1 part them (acme's).
var tag = th.tag;
if (contrast(tag, page) < band_floor and contrast(c.rule, page) < 3) tag = liftedOff(tag, page);
var own_text = th.tag_text;
var own_focus_text = th.tag_focus_text orelse th.tag_text;
// The focused band the loudest at the top: a focus step off the
// tag, ending further off the page; a theme's own where it does.
var focus_floor = if (isDark(tag)) focus_dark else focus_light;
var focus = focusOf(th.tag_focus, tag, page, focus_floor);
// A tag no ink reads on at 4.5:1 beside its focus (a mid-grey), or
// one with no focus step louder than it, takes the page a 1.15 step
// off, and the text.
if (focus == null or @max(leastContrast(@splat(255), &.{ tag, focus.? }), leastContrast(@splat(0), &.{ tag, focus.? })) < text_floor) {
tag = hued(page, page, 1.15, 0, null, 0);
own_text = text;
own_focus_text = text;
focus_floor = if (isDark(tag)) focus_dark else focus_light;
focus = stepOff(tag, awayFrom(tag, page), tag, focus_floor, null) orelse tag;
}
const focused = focus.?;
const grounds = [2][3]u8{ tag, focused };
// The full ink up to 7:1 on each, 4.5 at least; the words drawn in
// it toward the ground (`Inks.word`).
const tag_text = hold(own_text, &.{tag}, tag_text_floor);
const focus_text = hold(own_focus_text, &.{focused}, tag_text_floor);
const status = th.workspace orelse tag;
const status_text = hold(th.workspace_text orelse tag_text, &.{status}, text_floor);
// R7: the selection, lifted where it stands too near the page.
const sel_floor = if (dark) selection_dark else selection_light;
const own_sel = th.selection;
const sel = if (contrast(own_sel, page) < sel_floor - 0.005) hued(page, own_sel, sel_floor, chromaOf(own_sel), null, 0) else own_sel;
const sel_text = hold(th.selection_text orelse text, &.{sel}, text_floor);
c.selection_secondary = mixOklab(page, sel, 0.5);
// R9: the severities on the page, each told from the text and the
// ones before it; then on every tag ground and the status row's.
const candidates = [4][6]?[3]u8{
.{ th.@"error", ansi[1], canonical(ansi_hues[0], page, text), null, null, null },
.{ th.warning, ansi[3], canonical(ansi_hues[2], page, text), ansi[11], null, null },
.{ th.info, ansi[4], ansi[6], canonical(ansi_hues[3], page, text), canonical(ansi_hues[5], page, text), null },
.{ th.hint, ansi[6], ansi[2], canonical(ansi_hues[5], page, text), canonical(ansi_hues[1], page, text), canonical(ansi_hues[4], page, text) },
};
const severity = severitiesOn(page, text, candidates, null);
// R8: the hits' hue and grounds; a theme's own where it is a ground
// you see and the text reads on: 1.5:1 off the page, or, where the
// text leaves no room for that (no ground 1.5:1 off keeps it its
// floor), 1.1:1 with 0.08 OKLab (R0).
const ink_floor = @min(text_floor, contrast(text, page) * 0.9);
const own_hit: ?[3]u8 = if (th.hit) |own| own: {
const off = contrast(own, page);
const no_room = contrast(text, page) < hit_floor * ink_floor;
const seen = off >= hit_floor - 0.01 or (no_room and off >= 1.1 and oklabDistance(labOf(own), labOf(page)) >= 0.08);
break :own if (seen and contrast(text, own) >= ink_floor - 0.01) own else null;
} else null;
var hue = severity[1];
if (own_hit) |own| {
hue = own;
c.hit = own;
} else {
// Amber, unless the selection is already that hue: then the
// number's, then the accent's.
const s = lch(sel);
for ([3][3]u8{ severity[1], th.number, th.accent }) |cand| {
if (!(hueDistance(lch(cand)[2], s[2]) < 30 and s[1] > 0.03)) {
hue = cand;
break;
}
}
// A dark yellow is olive: amber on a dark page.
const v = lch(hue);
if (dark and v[2] > 80 and v[2] < 115) hue = fromLch(0.75, @max(v[1], 0.1), 70);
c.hit = hued(page, hue, hit_floor, if (dark) 0.07 else 0.10, text, ink_floor);
}
// The current one: the hue itself as its ground, the page as its
// ink (vim's IncSearch): room for it in every theme.
c.hit_current = hold(hue, &.{page}, text_floor);
c.hit_current_text = page;
c.hit_faint = mixOklab(page, c.hit, 0.5);
// Every ground's inks; on the tags and the status row, the
// tag's selection rebuilt on each where it stands too near it.
c.page = groundInks(th, page, text, sel, sel_text, severity, hue);
const own_tag_sel = th.tag_selection orelse own_sel;
for ([3]*Inks{ &c.tag[0], &c.tag[1], &c.status }, [3][3]u8{ tag, focused, status }, [3][3]u8{ tag_text, focus_text, status_text }, 0..) |inks, ground, ink, i| {
// A status row the plain tag's own (no status bar of its own).
if (i == 2 and std.mem.eql(u8, &ground, &tag) and std.mem.eql(u8, &ink, &tag_text)) {
inks.* = c.tag[0];
continue;
}
const floor = if (isDark(ground)) selection_dark else selection_light;
const tag_sel = if (contrast(own_tag_sel, ground) >= floor - 0.005 and contrast(ink, own_tag_sel) >= text_floor)
own_tag_sel
else
hued(ground, own_tag_sel, floor, chromaOf(own_tag_sel), ink, text_floor);
inks.* = groundInks(th, ground, ink, tag_sel, hold(ink, &.{tag_sel}, text_floor), severitiesOn(ground, ink, candidates, severity), hue);
}
c.sweeps = th.sweeps orelse .{
.{ .ground = sel, .text = sel_text },
sweepOf(page, severity[0], sel_floor, text),
sweepOf(page, th.added orelse ansi[2], sel_floor, text),
};
// R6, R5', H: the grips.
c.grip.focus = hold(th.accent, &.{focused}, grip_floor);
c.grip.ring = th.grip_ring orelse towardOf(hold(th.accent, &.{tag}, ring_floor), tag, ring_floor);
c.grip.mode = if (th.mode) |own| hold(own, &grounds, mode_floor) else modeOf(&grounds, .{ c.grip.focus, severity[1], severity[0] });
c.grip.mode_glyph = hold(c.grip.mode, &.{c.grip.focus}, mode_floor);
c.grip.dirty = hold(th.dirty orelse severity[1], &grounds, grip_floor);
// A column's grip on the page (H: the column row has no band; a
// port's own, made for its tag, held there too), grabbed 3:1, at
// rest a step quieter, 2:1.
const column = th.column_grip orelse th.number;
c.grip.column = hold(column, &.{page}, grip_floor);
c.grip.column_rest = towardOf(hold(column, &.{page}, ring_floor), page, ring_floor);
const fills = [5][3]u8{ c.grip.focus, c.grip.dirty, c.grip.column, c.grip.column_rest, c.grip.mode };
c.grip.ink = hold(if (leastContrast(page, &fills) >= leastContrast(tag_text, &fills)) page else tag_text, &fills, text_floor);
for (&c.grip.marks, [4][3]u8{ c.grip.focus, c.grip.dirty, c.grip.ring, c.grip.mode }, 0..) |*marks, fill, i| {
const both = [2][3]u8{ fill, tag };
const grounds_of = if (i < @intFromEnum(Fill.ring)) both[0..1] else both[0..];
for (&marks.severity, c.tag[0].severity) |*ink, own| ink.* = hold(own, grounds_of, text_floor);
marks.dim = hold(c.tag[0].dim, grounds_of, dim_floor);
}
// R10: added and deleted.
c.add = diffOf(page, text, th.added orelse ansi[2], dark);
c.del = diffOf(page, text, th.deleted orelse ansi[1], dark);
// R11: the frame.
c.tag_rule = th.tag_rule orelse mixOklab(tag, page, 0.5);
c.rail = th.rail orelse tag;
c.rail_thumb = th.rail_thumb orelse c.tag[0].rule;
c.empty_column = th.empty_column orelse c.rule;
c.rule_px = th.rule_px orelse 2;
c.rail_px = th.rail_px orelse 12;
// The original's own, never moved (B1.5); R12, R13.
c.syntax = .{ text, th.keyword, th.string, th.number, th.comment };
c.line_number = th.line_number orelse towardOf(text, page, 3);
c.line_number_current = th.line_number_current orelse towardOf(text, page, text_floor);
// A name keeps its hue focused: the plain tag's tint at the focused
// ink's lightness, else the search on that ground.
c.name[0] = th.tag_name orelse derivedNameTint(th, tag_text, tag) orelse tag_text;
const named = labOf(c.name[0]);
c.name[1] = nameTintFrom(named, focus_text, focused, -1, 0.15) orelse nameTintFrom(named, focus_text, focused, 0.15, 1) orelse
derivedNameTint(th, focus_text, focused) orelse focus_text;
// R10: the lanes (the accents but green and red, hue-sorted) and
// churn's steps from the line numbers' ink to the deleted hue.
c.lanes_len = lanesOf(.{ ansi[3], ansi[4], ansi[5], ansi[6], th.number, th.keyword }, .{ th.deleted orelse ansi[1], th.added orelse ansi[2] }, &c.lanes);
// A theme with no accent (a grey one) draws its lanes in one grey.
if (c.lanes_len == 0) {
c.lanes[0] = c.line_number;
c.lanes_len = 1;
}
for (&c.heat, 1..) |*h, k| h.* = mixOklab(c.line_number, th.deleted orelse ansi[1], @as(f32, @floatFromInt(k)) / 8);
return c;
}
};
fn chromaOf(rgb: [3]u8) f32 {
return lch(rgb)[1];
}
/// Which way in lightness is away from the page: up from a page under
/// `c`, down from one over it; up on a dark page where they are level.
fn awayFrom(c: [3]u8, page: [3]u8) f32 {
const l = labOf(c)[0];
const p = labOf(page)[0];
if (@abs(l - p) < 0.005) return if (isDark(page)) 1 else -1;
return if (l > p) 1 else -1;
}
/// `c` moved by its lightness alone (`clip`, its hue kept), `sign` up or
/// down, by the least that reads `floor`:1 off `off` and, where `past` is
/// given, ends beyond that lightness; by halves, up to 0.75 in lightness;
/// null where none does.
fn stepOff(c: [3]u8, sign: f32, off: [3]u8, floor: f32, past: ?f32) ?[3]u8 {
const lab = labOf(c);
const reach: f32 = 0.75;
var best = clip(lab[0] + sign * reach, lab[1], lab[2]);
if (!steppedOff(best, sign, off, floor, past)) return null;
var lo: f32 = 0;
var hi = reach;
for (0..8) |_| {
const mid = (lo + hi) / 2;
const m = clip(lab[0] + sign * mid, lab[1], lab[2]);
if (steppedOff(m, sign, off, floor, past)) {
hi = mid;
best = m;
} else lo = mid;
}
return best;
}
fn steppedOff(c: [3]u8, sign: f32, off: [3]u8, floor: f32, past: ?f32) bool {
if (contrast(c, off) < floor) return false;
const p = past orelse return true;
return sign * (labOf(c)[0] - p) > 0;
}
/// H: a plain tag too near the page lifted to a band off it, further from
/// it where the gamut has room, else across it (a white tag on cream).
fn liftedOff(tag: [3]u8, page: [3]u8) [3]u8 {
const away = awayFrom(tag, page);
const p = labOf(page)[0];
return stepOff(tag, away, page, Chrome.band_floor, p) orelse stepOff(tag, -away, page, Chrome.band_floor, p) orelse tag;
}
/// R4 under H: the focused tag a focus step off the plain one and further
/// off the page than it: the theme's own where it is that, on the tag's
/// side of light; else the tag moved the step lighter (darker on a light
/// tag), else the other way: away from the page or past it, whichever
/// stands louder (a tag sunk under its page rises above it, catppuccin's;
/// a soft theme's never sinks to black); null where neither does.
fn focusOf(own: ?[3]u8, tag: [3]u8, page: [3]u8, floor: f32) ?[3]u8 {
if (own) |o| if (louder(o, tag, page, floor) and isDark(o) == isDark(tag)) return o;
const lighter: f32 = if (isDark(tag)) 1 else -1;
for ([2]f32{ lighter, -lighter }) |sign| {
const f = stepOff(tag, sign, tag, floor, null) orelse continue;
if (louder(f, tag, page, floor)) return f;
}
return null;
}
fn louder(focus: [3]u8, tag: [3]u8, page: [3]u8, floor: f32) bool {
return contrast(focus, tag) >= floor - 0.005 and contrast(focus, page) > contrast(tag, page);
}
/// The mode's hues (R5', G1'): sky, mint, violet, paper, rose.
const mode_hues = [5]f32{ 230, 165, 300, 95, 350 };
/// R5': a reading pane's mark, quiet but findable: the first mode hue 40
/// degrees or more from the hues a grip already says (focus, unsaved, an
/// error), else the one furthest from them, at chroma 0.11 as the gamut
/// allows, at the least lightness off the two tags' mean (lighter on a
/// dark tag) that reads 3:1 on both. By halves.
fn modeOf(grounds: *const [2][3]u8, said: [3][3]u8) [3]u8 {
var hues: [3]f32 = undefined;
var n: usize = 0;
for (said) |c| {
const v = lch(c);
if (v[1] < 0.04) continue;
hues[n] = v[2];
n += 1;
}
var hue = mode_hues[0];
var furthest: f32 = -1;
for (mode_hues) |h| {
var apart: f32 = 180;
for (hues[0..n]) |taken| apart = @min(apart, hueDistance(h, taken));
if (apart >= 40) {
hue = h;
break;
}
if (apart > furthest) {
hue = h;
furthest = apart;
}
}
const a = 0.11 * @cos(std.math.degreesToRadians(hue));
const b = 0.11 * @sin(std.math.degreesToRadians(hue));
const mean = (labOf(grounds[0])[0] + labOf(grounds[1])[0]) / 2;
const sign: f32 = if (isDark(grounds[0])) 1 else -1;
var lo: f32 = 0;
var hi: f32 = 0.8;
var best = clip(mean + sign * hi, a, b);
if (leastContrast(best, grounds) < Chrome.mode_floor) return best;
for (0..8) |_| {
const mid = (lo + hi) / 2;
const c = clip(mean + sign * mid, a, b);
if (leastContrast(c, grounds) >= Chrome.mode_floor) {
hi = mid;
best = c;
} else lo = mid;
}
return best;
}
/// R9: the four severities on one ground: each the first candidate that,
/// held 4.5:1 there, stands 0.06 off the ground's text and the ones before
/// it, else the one that stands furthest; on a ground other than the page,
/// the page's own tried first.
fn severitiesOn(ground: [3]u8, text: [3]u8, candidates: [4][6]?[3]u8, page: ?[4][3]u8) [4][3]u8 {
var out: [4][3]u8 = undefined;
var taken: [5][3]f32 = undefined;
taken[0] = labOf(text);
// A colour two lists name (cyan, a canonical hue) is held once: up to
// the 28 the lists hold, each with its held ink and that ink's OKLab.
var seen: [28]struct { from: [3]u8, held: [3]u8, lab: [3]f32 } = undefined;
var n_seen: usize = 0;
for (&out, candidates, 0..) |*severity, own, k| {
var best = own[1].?;
var best_d: f32 = -1;
const first: ?[3]u8 = if (page) |p| p[k] else null;
for ([1]?[3]u8{first} ++ own) |candidate| {
const from = candidate orelse continue;
const at = for (seen[0..n_seen], 0..) |was, i| {
if (std.mem.eql(u8, &was.from, &from)) break i;
} else at: {
const held = hold(from, &.{ground}, Chrome.text_floor);
seen[n_seen] = .{ .from = from, .held = held, .lab = labOf(held) };
n_seen += 1;
break :at n_seen - 1;
};
const held = seen[at].held;
const lab = seen[at].lab;
var d: f32 = 2;
for (taken[0 .. k + 1]) |t| d = @min(d, oklabDistance(lab, t));
if (d >= Chrome.severity_apart) {
best = held;
break;
}
if (d > best_d) {
best = held;
best_d = d;
}
}
severity.* = best;
taken[k + 1] = labOf(best);
}
return out;
}
/// The inks one ground carries (`Chrome.Inks`).
fn groundInks(th: *const Theme, ground: [3]u8, text: [3]u8, sel: [3]u8, sel_text: [3]u8, severity: [4][3]u8, hue: [3]u8) Chrome.Inks {
var line: Line = .init(text, ground);
return .{
.ground = ground,
.text = text,
.word = if (contrast(text, ground) <= Chrome.text_floor) text else line.toward(Chrome.text_floor),
.dim = line.toward(Chrome.dim_floor),
.rule = line.toward(Chrome.rule_ink),
.key = hold(th.accent, &.{ground}, Chrome.text_floor),
.match = hold(hue, &.{ground}, Chrome.text_floor),
.kind = hold(th.keyword, &.{ ground, sel }, Chrome.text_floor),
.severity = severity,
.selection = .{
.ground = sel,
.text = sel_text,
.dim = towardOf(sel_text, sel, Chrome.dim_floor),
.secondary = mixOklab(ground, sel, 0.5),
.key = hold(th.accent, &.{sel}, Chrome.text_floor),
.match = hold(hue, &.{sel}, Chrome.text_floor),
},
};
}
/// R7: an exec or look sweep: the selection's step off the page in its
/// meaning's hue (acme's #aa0000 exec, #006600 look), its ink 4.5:1 on it.
fn sweepOf(page: [3]u8, hue: [3]u8, floor: f32, text: [3]u8) Theme.Sweep {
const ground = hued(page, hue, floor, if (isDark(page)) 0.07 else 0.10, text, Chrome.text_floor);
return .{ .ground = ground, .text = hold(text, &.{ground}, Chrome.text_floor) };
}
/// R10: a diff's rows in `hue`: a row 1.15:1 off the page, its changed
/// words 1.45:1, a faint line 1.06:1, never so far the text drops under
/// its floor; the marker the hue held 4.5:1 on the row and the words.
fn diffOf(page: [3]u8, text: [3]u8, hue: [3]u8, dark: bool) Chrome.Diff {
const floor = @min(Chrome.text_floor, contrast(text, page) * 0.9);
const row = hued(page, hue, Chrome.row_step, if (dark) 0.05 else 0.06, text, floor);
const emph = hued(page, hue, Chrome.emph_step, if (dark) 0.08 else 0.10, text, floor);
return .{ .row = row, .emph = emph, .line = hued(page, hue, Chrome.line_step, 0.025, null, 0), .ink = hold(hue, &.{ row, emph }, Chrome.text_floor) };
}
/// The Changes layer's lanes (jj.zig's rule, once a theme): the accents but
/// the two that mean written and taken away, in hue order from the top,
/// each 15 degrees or more from the one kept before it.
fn lanesOf(accents: [6][3]u8, taken: [2][3]u8, out: *[8][3]u8) u8 {
var sorted: [6][3]u8 = undefined;
var n: usize = 0;
for (accents) |c| {
// A grey is no accent; one near written or taken away means that.
if (hsvChroma(c) < 48 or hsvApart(c, taken[0]) < 15 or hsvApart(c, taken[1]) < 15) continue;
sorted[n] = c;
n += 1;
}
std.sort.insertion([3]u8, sorted[0..n], {}, struct {
fn above(_: void, a: [3]u8, b: [3]u8) bool {
return hsvHue(a) > hsvHue(b);
}
}.above);
out.* = @splat(@splat(0));
var kept: u8 = 0;
for (sorted[0..n]) |c| {
if (kept > 0 and hsvApart(c, out[kept - 1]) < 15) continue;
out[kept] = c;
kept += 1;
}
return kept;
}
fn hsvChroma(c: [3]u8) u8 {
return @max(c[0], c[1], c[2]) - @min(c[0], c[1], c[2]);
}
fn hsvHue(c: [3]u8) f32 {
const r: f32 = @floatFromInt(c[0]);
const g: f32 = @floatFromInt(c[1]);
const b: f32 = @floatFromInt(c[2]);
const hi = @max(r, g, b);
const d = hi - @min(r, g, b);
if (d == 0) return 0;
const h = if (hi == r) @mod((g - b) / d, 6) else if (hi == g) (b - r) / d + 2 else (r - g) / d + 4;
return 60 * h;
}
fn hsvApart(a: [3]u8, b: [3]u8) f32 {
return hueDistance(hsvHue(a), hsvHue(b));
}
/// The ink a syntax class is drawn in; a byte of none keeps its text's own.
pub fn synInk(th: *const Theme, sy: @import("syntax.zig").Syn) ?[3]u8 {
return switch (sy) {
.none => null,
.keyword => th.keyword,
.string => th.string,
.number => th.number,
.comment => th.comment,
};
}
/// One family, its eight backgrounds a theme each (`curated`).
const seoul256 = @import("themes/seoul256.zig");
const curated = struct {
// DESIGN.md E's groups, the picker's sections (`theme_groups`): pardes's
// own, dark first (the host's page, the favourite), orchard the default
// (`default_theme`, by name).
pub const dark = @import("themes/dark.zig");
pub const light = @import("themes/light.zig");
pub const orchard = @import("themes/orchard.zig");
pub const orchard_black = @import("themes/orchard_black.zig");
pub const ink = @import("themes/ink.zig");
pub const mono = @import("themes/mono.zig");
pub const okabe = @import("themes/okabe.zig");
pub const sepia = @import("themes/sepia.zig");
pub const paper = @import("themes/paper.zig");
pub const daybreak = @import("themes/daybreak.zig");
pub const dusk = @import("themes/dusk.zig");
pub const lapis = @import("themes/lapis.zig");
// Pardes's, after a classic.
pub const forge = @import("themes/forge.zig");
pub const forge_black = @import("themes/forge_black.zig");
pub const forge_soft = @import("themes/forge_soft.zig");
pub const lagoon = @import("themes/lagoon.zig");
pub const solarium = @import("themes/solarium.zig");
pub const spectrum = @import("themes/spectrum.zig");
pub const harvest = @import("themes/harvest.zig");
pub const clay = @import("themes/clay.zig");
// acme's.
pub const acme = @import("themes/acme.zig");
pub const atelier = @import("themes/atelier.zig");
// Faithful ports of well-known themes, a family at a time (core/themes/
// <name>.zig says where each value came from): `theme_groups`.
pub const dark_plus = @import("themes/dark_plus.zig");
pub const solarized_dark = @import("themes/solarized_dark.zig");
pub const solarized_light = @import("themes/solarized_light.zig");
pub const dracula = @import("themes/dracula.zig");
pub const dracula_soft = @import("themes/dracula_soft.zig");
pub const alucard = @import("themes/alucard.zig");
pub const monokai = @import("themes/monokai.zig");
pub const monokai_pro = @import("themes/monokai_pro.zig");
pub const monokai_pro_classic = @import("themes/monokai_pro_classic.zig");
pub const monokai_pro_machine = @import("themes/monokai_pro_machine.zig");
pub const monokai_pro_octagon = @import("themes/monokai_pro_octagon.zig");
pub const monokai_pro_ristretto = @import("themes/monokai_pro_ristretto.zig");
pub const monokai_pro_spectrum = @import("themes/monokai_pro_spectrum.zig");
pub const monokai_pro_light = @import("themes/monokai_pro_light.zig");
pub const monokai_pro_light_sun = @import("themes/monokai_pro_light_sun.zig");
pub const tokyonight_night = @import("themes/tokyonight_night.zig");
pub const tokyonight_storm = @import("themes/tokyonight_storm.zig");
pub const tokyonight_moon = @import("themes/tokyonight_moon.zig");
pub const tokyonight_day = @import("themes/tokyonight_day.zig");
pub const rose_pine = @import("themes/rose_pine.zig");
pub const rose_pine_moon = @import("themes/rose_pine_moon.zig");
pub const rose_pine_dawn = @import("themes/rose_pine_dawn.zig");
pub const catppuccin_latte = @import("themes/catppuccin_latte.zig");
pub const catppuccin_frappe = @import("themes/catppuccin_frappe.zig");
pub const catppuccin_macchiato = @import("themes/catppuccin_macchiato.zig");
pub const catppuccin_mocha = @import("themes/catppuccin_mocha.zig");
pub const seoul256_dark_233 = seoul256.dark(233);
pub const seoul256_dark_234 = seoul256.dark(234);
pub const seoul256_dark_235 = seoul256.dark(235);
pub const seoul256_dark_236 = seoul256.dark(236);
pub const seoul256_dark_237 = seoul256.dark(237);
pub const seoul256_light_254 = seoul256.light(254);
pub const seoul256_light_255 = seoul256.light(255);
pub const seoul256_light_256 = seoul256.light(256);
pub const zenbones_light = @import("themes/zenbones_light.zig");
pub const zenbones_dark = @import("themes/zenbones_dark.zig");
pub const neobones_light = @import("themes/neobones_light.zig");
pub const neobones_dark = @import("themes/neobones_dark.zig");
pub const vimbones = @import("themes/vimbones.zig");
pub const forestbones_light = @import("themes/forestbones_light.zig");
pub const forestbones_dark = @import("themes/forestbones_dark.zig");
pub const nordbones = @import("themes/nordbones.zig");
pub const rosebones_light = @import("themes/rosebones_light.zig");
pub const rosebones_dark = @import("themes/rosebones_dark.zig");
pub const tokyobones_light = @import("themes/tokyobones_light.zig");
pub const tokyobones_dark = @import("themes/tokyobones_dark.zig");
pub const seoulbones_light = @import("themes/seoulbones_light.zig");
pub const seoulbones_dark = @import("themes/seoulbones_dark.zig");
pub const duckbones = @import("themes/duckbones.zig");
pub const zenburned = @import("themes/zenburned.zig");
pub const zenwritten_light = @import("themes/zenwritten_light.zig");
pub const zenwritten_dark = @import("themes/zenwritten_dark.zig");
pub const kanagawabones = @import("themes/kanagawabones.zig");
pub const nord = @import("themes/nord.zig");
pub const ayu_dark = @import("themes/ayu_dark.zig");
pub const ayu_mirage = @import("themes/ayu_mirage.zig");
pub const ayu_light = @import("themes/ayu_light.zig");
pub const doom_one = @import("themes/doom_one.zig");
pub const doom_one_light = @import("themes/doom_one_light.zig");
// Captured: an old helix setup, kept (it works).
pub const helix = @import("themes/helix.zig");
};
/// A struct of theme files as themes: each file's `theme`, a field it
/// leaves out its default.
fn fold(comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme {
comptime {
@setEvalBranchQuota(400000);
var out: [@typeInfo(C).@"struct".decl_names.len]Theme = undefined;
const theme_info = @typeInfo(Theme).@"struct";
for (@typeInfo(C).@"struct".decl_names, 0..) |d, i| {
var t: Theme = undefined;
const source = @field(C, d).theme;
for (@typeInfo(@TypeOf(source)).@"struct".field_names) |name| if (!@hasField(Theme, name))
@compileError("theme " ++ d ++ " has no field " ++ name ++ " (core/theme_schema.zig)");
for (theme_info.field_names, theme_info.field_types, theme_info.field_attrs) |name, T, attrs| {
@field(t, name) = if (@hasField(@TypeOf(source), name))
as(T, @field(source, name))
else if (attrs.defaultValue(T)) |value|
value
else
@compileError("theme " ++ d ++ " is missing " ++ name);
}
out[i] = t;
}
return out;
}
}
/// A theme file's literal as the field's type: a struct field by field
/// (acme's sweeps), which a literal's own struct type does not coerce to.
fn as(comptime T: type, comptime value: anytype) T {
return switch (@typeInfo(T)) {
.optional => |o| if (@TypeOf(value) == @TypeOf(null)) null else as(o.child, value),
.array => |a| blk: {
var out: T = undefined;
for (&out, 0..) |*e, i| e.* = as(a.child, value[i]);
break :blk out;
},
.@"struct" => blk: {
var out: T = undefined;
for (@typeInfo(T).@"struct".field_names) |name| @field(out, name) = as(@FieldType(T, name), @field(value, name));
break :blk out;
},
else => value,
};
}
/// The ring: pardes's own (`native_count` of them), then the imported.
pub const themes = fold(curated) ++ fold(@import("generated_themes"));
/// The first `native_count` of `themes` are pardes's own; the rest imported.
pub const native_count = @typeInfo(curated).@"struct".decl_names.len;
/// The picker's sections (`Themes`), in ring order, each running from
/// the theme it names to the next section's; `NextColor` and `Theme` still
/// see one flat ring (DESIGN.md E): pardes's own, those after a classic,
/// acme's, the faithful ports a family at a time, the captured helix setup;
/// then the imported, a family at a time (`import_heads`).
pub const ThemeGroup = struct { title: []const u8, first: []const u8 };
const theme_groups = [_]ThemeGroup{
.{ .title = "Pardes", .first = "dark" },
.{ .title = "Pardes, after a classic", .first = "forge" },
.{ .title = "acme", .first = "acme" },
.{ .title = "Visual Studio Code", .first = "dark_plus" },
.{ .title = "Solarized", .first = "solarized_dark" },
.{ .title = "Dracula", .first = "dracula" },
.{ .title = "Monokai", .first = "monokai" },
.{ .title = "Monokai Pro", .first = "monokai_pro" },
.{ .title = "Tokyo Night", .first = "tokyonight_night" },
.{ .title = "Rosé Pine", .first = "rose_pine" },
.{ .title = "Catppuccin", .first = "catppuccin_latte" },
.{ .title = "Seoul256", .first = "seoul256_dark_233" },
.{ .title = "Zenbones", .first = "zenbones_light" },
.{ .title = "Nord", .first = "nord" },
.{ .title = "Ayu", .first = "ayu_dark" },
.{ .title = "Doom One", .first = "doom_one" },
.{ .title = "Captured", .first = "helix" },
};
/// The theme a session starts in, by name: never a place in the ring.
pub const default_theme = indexOfTheme("orchard");
/// The themes retired (DESIGN.md E, under the user's ruling of 2026-11-25)
/// and the kept one each stands for where its name is still read: an init
/// file's `Theme`, a /ctl write, a dump; null, the default.
const retired = [_]struct { []const u8, ?[]const u8 }{
.{ "seoul256_dark_238", "seoul256_dark_237" },
.{ "seoul256_dark_239", "seoul256_dark_237" },
.{ "seoul256_light_252", "seoul256_light_254" },
.{ "seoul256_light_253", "seoul256_light_254" },
.{ "ayu_dark_helix", "ayu_dark" },
.{ "ayu_dark_zed", "ayu_dark" },
.{ "ayu_light_zed", "ayu_light" },
.{ "ayu_mirage_zed", "ayu_mirage" },
.{ "base16_default_light", "base16_default_dark" },
.{ "base16_terminal", "dark" },
.{ "base16_transparent", "base16_default_dark" },
.{ "bogster_light", "bogster" },
.{ "cyan_light", "jetbrains_cyan_light" },
.{ "eldritch_transparent", "eldritch" },
.{ "gruvbox_dark_hard_zed", "gruvbox_dark_hard" },
.{ "gruvbox_dark_soft_zed", "gruvbox_dark_soft" },
.{ "gruvbox_dark_zed", "gruvbox" },
.{ "gruvbox_light_hard_zed", "gruvbox_light_hard" },
.{ "gruvbox_light_soft_zed", "gruvbox_light_soft" },
.{ "gruvbox_light_zed", "gruvbox_light" },
.{ "gruvbox_material", "gruvbox_material_dark_medium" },
.{ "hex_lavender", "hex_toxic" },
.{ "hex_poison", "hex_toxic" },
.{ "hex_steel", "hex_toxic" },
.{ "ingrid", null },
.{ "iroaseta", "ao" },
.{ "nord_helix", "nord" },
.{ "nord_light", "nord" },
.{ "nyxvamp_transparent", "nyxvamp_veil" },
.{ "peachpuff", "dark" },
.{ "seoul256_dark", "seoul256_dark_235" },
.{ "seoul256_dark_hard", "seoul256_dark_233" },
.{ "seoul256_dark_soft", "seoul256_dark_237" },
.{ "seoul256_light", "seoul256_light_254" },
.{ "seoul256_light_hard", "seoul256_light_256" },
.{ "seoul256_light_soft", "seoul256_light_254" },
.{ "term16_dark", "dark" },
.{ "term16_light", "light" },
.{ "tokyonight", "tokyonight_night" },
.{ "ttox", "dark" },
.{ "ttox_soft", "dark" },
.{ "vesper_transparent", "vesper" },
.{ "zed_onedark", "one_dark_zed" },
.{ "zed_onelight", "one_light_zed" },
};
/// The ring's place for the kept theme a retired `name` stands for,
/// whatever its case.
pub fn successorOf(name: []const u8) ?usize {
for (retired) |r| if (std.ascii.eqlIgnoreCase(r[0], name)) return if (r[1]) |kept| themeIndex(kept).? else default_theme;
return null;
}
/// The theme a dump naming `name` restores: that one, a retired one's
/// successor, else the one in effect (`was`) where this build has it, else
/// the default.
pub fn restoredIndex(name: []const u8, was: usize) usize {
for (themes, 0..) |t, i| if (std.mem.eql(u8, t.name, name)) return i;
return successorOf(name) orelse if (was < themes.len) was else default_theme;
}
fn indexOfTheme(comptime name: []const u8) usize {
return comptime blk: {
@setEvalBranchQuota(100000);
for (themes[0..native_count], 0..) |t, i| if (std.mem.eql(u8, t.name, name)) break :blk i;
@compileError("theme_groups names " ++ name ++ ", which is not one of ours");
};
}
/// The heading of the picker section that starts at ring index `index`.
pub fn groupAt(index: usize) ?[]const u8 {
inline for (theme_groups) |g| if (index == comptime indexOfTheme(g.first)) return g.title;
return if (index >= native_count) import_heads[index - native_count] else null;
}
/// A theme's family: its name's first word (gruvbox_dark_hard's gruvbox).
fn familyOf(name: []const u8) []const u8 {
return name[0 .. std.mem.indexOfScalar(u8, name, '_') orelse name.len];
}
/// The imported themes' headings, a family's at its first (DESIGN.md E: a
/// heading per family, not one flat run), and one over the lone ones the
/// generator rings after every family (tools/gen_themes.zig `byFamily`).
const import_heads: [themes.len - native_count]?[]const u8 = blk: {
@setEvalBranchQuota(2_000_000);
const imported = themes[native_count..];
var out: [imported.len]?[]const u8 = @splat(null);
var lone_seen = false;
for (imported, 0..) |t, i| {
const family = familyOf(t.name);
var members: usize = 0;
for (imported) |u| {
if (std.mem.eql(u8, familyOf(u.name), family)) members += 1;
}
if (members < 2) {
if (!lone_seen) out[i] = "Imported, one of a kind";
lone_seen = true;
} else if (i == 0 or !std.mem.eql(u8, familyOf(imported[i - 1].name), family)) {
if (lone_seen) @compileError("imported family " ++ family ++ " rings after a lone theme (tools/gen_themes.zig byFamily)");
out[i] = "Imported: " ++ family;
}
}
break :blk out;
};
comptime {
if (themes.len > std.math.maxInt(u16) + 1)
@compileError("runtime config theme index no longer fits u16");
}
comptime {
@setEvalBranchQuota(20000);
const ours = fold(curated).len;
for (themes[0..ours]) |c| for (themes[ours..]) |g| if (std.mem.eql(u8, c.name, g.name))
@compileError("theme name \"" ++ c.name ++ "\" is both ours and generated; rename the vendored source");
}
fn nextThemeFileGeneration(p: *Pardes) u32 {
p.theme_file_generation +%= 1;
if (p.theme_file_generation == 0) p.theme_file_generation = 1;
return p.theme_file_generation;
}
pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void {
const input = std.mem.trim(u8, argument, " \t\r\n");
if (input.len == 0 or !std.mem.endsWith(u8, input, ".zon")) {
p.reportError(.at(id), "theme file", error.InvalidThemePath);
return;
}
const absolute = std.Io.Dir.path.isAbsolute(input);
const config_dir = if (absolute) null else p.configDir();
if (!absolute and config_dir == null) {
p.reportError(.at(id), "theme file", error.NoConfigDirectory);
return;
}
var joined: [4095]u8 = undefined;
const resolved = if (absolute) input else path: {
const dir = config_dir.?;
const separator = if (dir.len > 0 and dir[dir.len - 1] != std.Io.Dir.path.sep) std.Io.Dir.path.sep_str else "";
break :path std.fmt.bufPrint(&joined, "{s}{s}{s}", .{ dir, separator, input }) catch {
p.reportError(.at(id), "theme file", error.PathTooLong);
return;
};
};
if (!p.theme_file_path.set(resolved)) {
p.reportError(.at(id), "theme file", error.PathTooLong);
return;
}
p.theme_file_pane = .at(id);
const generation = nextThemeFileGeneration(p);
p.emit(.{ .theme_file = .{ .generation = generation, .on = true } });
}
/// The .zon a ThemeFile loaded, while it is the theme in effect: what
/// /ctl and DumpConfig say in place of `Theme <name>`, since the name
/// inside the file is no theme `Theme` knows.
pub fn loadedThemeFile(p: *const Pardes) ?[]const u8 {
const path = p.theme_file_loaded.get();
return if (p.custom_theme != null and path.len > 0) path else null;
}
pub const ThemeFileRequest = struct {
path: []const u8,
pane: pardes.Pane.Id,
};
/// Borrow the current request while a native host performs its synchronous
/// read. A later command invalidates an already-queued generation.
pub fn themeFileRequest(p: *const Pardes, generation: u32) ?ThemeFileRequest {
if (generation == 0 or generation != p.theme_file_generation) return null;
const path = p.theme_file_path.get();
if (path.len == 0) return null;
return .{ .path = path, .pane = p.theme_file_pane };
}
pub fn failThemeFile(p: *Pardes, generation: u32, err: anyerror) void {
const request = themeFileRequest(p, generation) orelse return;
themeFileError(p, request, err);
}
/// A theme file's failure, said with its path: `theme file x.zon: file
/// not found`, not which file left to guess.
fn themeFileError(p: *Pardes, request: ThemeFileRequest, err: anyerror) void {
var words: [128]u8 = undefined;
themeFileFailure(p, request, pardes.Messages.errorWords(err, &words));
}
fn themeFileFailure(p: *Pardes, request: ThemeFileRequest, why: []const u8) void {
var said: pardes.Kind.Buf(520) = .{};
var cut: [200]u8 = undefined;
const path = @import("ninep/tree.zig").fitErr(request.path, &cut);
p.reportFailure(request.pane.index(), said.print("theme file {s}: {s}", .{ path, why }));
revertThemeFile(p);
}
/// A ThemeFile that did not load changes nothing: the request goes back to
/// the file last loaded (watched again), or to none, so /ctl and DumpConfig
/// still read what replays. A bad save of the loaded file itself keeps it.
fn revertThemeFile(p: *Pardes) void {
const loaded = p.theme_file_loaded.get();
if (std.mem.eql(u8, loaded, p.theme_file_path.get())) return;
if (loaded.len == 0) p.theme_file_path.clear() else _ = p.theme_file_path.set(loaded);
const generation = nextThemeFileGeneration(p);
p.emit(.{ .theme_file = .{ .generation = generation, .on = loaded.len > 0 } });
}
/// The deepest a theme file's brackets nest: its schema is three levels
/// deep, and std's ZON parser recurses a level a bracket with no bound of
/// its own (a file 5 000 deep overflowed a 16 MiB stack in a Debug build:
/// the session's end, at every start that loaded it).
const max_theme_nesting = 64;
/// How deep `source`'s brackets nest, as std's tokenizer reads it (strings
/// and comments are tokens of their own).
fn nesting(source: [:0]const u8) usize {
var tokens: std.zig.Tokenizer = .init(source);
var depth: usize = 0;
var most: usize = 0;
while (true) switch (tokens.next().tag) {
.eof => return most,
.l_brace, .l_bracket, .l_paren => {
depth += 1;
most = @max(most, depth);
},
.r_brace, .r_bracket, .r_paren => depth -|= 1,
else => {},
};
}
pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8) bool {
// ZON's generated field dispatch grows with the complete theme schema.
@setEvalBranchQuota(10000);
const request = themeFileRequest(p, generation) orelse return false;
if (bytes.len > 1024 * 1024) {
themeFileError(p, request, error.ThemeFileTooLarge);
return false;
}
const source = p.gpa.dupeSentinel(u8, bytes, 0) catch |err| {
themeFileError(p, request, err);
return false;
};
defer p.gpa.free(source);
if (nesting(source) > max_theme_nesting) {
themeFileFailure(p, request, std.fmt.comptimePrint("nested past {d} levels", .{max_theme_nesting}));
return false;
}
// The parse's results live in `arena`; the theme kept owns only its name.
var arena: std.heap.ArenaAllocator = .init(p.gpa);
defer arena.deinit();
var diagnostics: std.zon.parse.Diagnostics = undefined;
const options: std.zon.parse.Options = .{ .gpa = p.gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics };
// A file in the old names (every one written before 2026-11-25: a
// user's own, an older DumpThemes') is read in them and renamed.
var theme: Theme = if (inOldNames(source))
.fromLegacy(std.zon.parse.fromSlice(LegacyTheme, options) catch |err| return zonFailed(p, request, err, &diagnostics))
else
std.zon.parse.fromSlice(Theme, options) catch |err| return zonFailed(p, request, err, &diagnostics);
if (theme.name.len == 0 or theme.name.len > 255) {
themeFileError(p, request, error.InvalidThemeName);
return false;
}
theme.name = p.gpa.dupe(u8, theme.name) catch |err| {
themeFileError(p, request, err);
return false;
};
p.theme_chrome = .of(&theme);
const old = p.custom_theme;
p.custom_theme = theme;
if (old) |theme_value| p.gpa.free(theme_value.name);
_ = p.theme_file_loaded.set(request.path);
_ = p.scratch.reset(.{ .retain_with_limit = pardes.memory.limits.scratch_kept });
p.sync();
return true;
}
/// A theme file the parser refused: said with its line and what the parser
/// wanted there, never a bare `parse zon`.
fn zonFailed(p: *Pardes, request: ThemeFileRequest, err: anyerror, diagnostics: *const std.zon.parse.Diagnostics) bool {
if (err != error.ParseZon) themeFileError(p, request, err) else {
var why: [200]u8 = undefined;
themeFileFailure(p, request, pardes.Messages.zonWhy(diagnostics, &why));
}
return false;
}
/// Whether a theme file is in the old names (`LegacyTheme`): every one
/// names `tag_bg`, which the new names have not.
fn inOldNames(source: [:0]const u8) bool {
var tokens: std.zig.Tokenizer = .init(source);
var after_period = false;
while (true) {
const t = tokens.next();
switch (t.tag) {
.eof => return false,
.identifier => if (after_period and std.mem.eql(u8, source[t.loc.start..t.loc.end], "tag_bg")) return true,
else => {},
}
after_period = t.tag == .period;
}
}
/// The session's theme's chrome, at its start (Pardes.init, a Restore):
/// never one the window previews (`previewTheme`).
pub fn finishThemeInitialization(p: *Pardes) void {
p.theme_chrome = .of(if (p.custom_theme) |*custom| custom else &themes[p.settings.theme]);
}
/// Themes near `name`, a line of them, for a Theme given a name there is
/// none of (all of them, Themes, are too many for a refused write): every
/// one sharing its first letter when they fit in `buf`, else the 8 nearest.
pub fn themesNear(buf: []u8, name: []const u8) []const u8 {
var w = std.Io.Writer.fixed(buf);
for (themes) |t| {
if (name.len > 0 and std.ascii.toLower(t.name[0]) != std.ascii.toLower(name[0])) continue;
if (!putName(&w, buf.len, t.name)) break;
} else if (w.buffered().len > 0) return w.buffered();
// The nearest, most alike first: ponytail, a plain score (shared
// prefix, the name inside, its letters in order), no edit distance.
var best: [8]usize = undefined;
var scores: [8]usize = undefined;
var n: usize = 0;
for (themes, 0..) |t, i| {
const s = likeness(t.name, name);
var at = n;
while (at > 0 and scores[at - 1] < s) at -= 1;
if (at == best.len) continue;
const last = @min(n, best.len - 1);
var k = last;
while (k > at) : (k -= 1) {
best[k] = best[k - 1];
scores[k] = scores[k - 1];
}
best[at] = i;
scores[at] = s;
n = @min(n + 1, best.len);
}
w = std.Io.Writer.fixed(buf);
for (best[0..n]) |i| if (!putName(&w, buf.len, themes[i].name)) break;
return w.buffered();
}
/// One more name on the line, whole, or none: false when it would not fit.
fn putName(w: *std.Io.Writer, cap: usize, name: []const u8) bool {
const sep: []const u8 = if (w.buffered().len > 0) " " else "";
if (w.buffered().len + sep.len + name.len > cap) return false;
w.print("{s}{s}", .{ sep, name }) catch return false;
return true;
}
fn likeness(theme_name: []const u8, name: []const u8) usize {
var prefix: usize = 0;
while (prefix < @min(theme_name.len, name.len) and std.ascii.toLower(theme_name[prefix]) == std.ascii.toLower(name[prefix])) prefix += 1;
// Its letters found in order, one not there passed over.
var in_order: usize = 0;
var pos: usize = 0;
for (name) |c| {
const at = for (theme_name[pos..], pos..) |t, i| {
if (std.ascii.toLower(t) == std.ascii.toLower(c)) break i;
} else continue;
in_order += 1;
pos = at + 1;
}
const inside: usize = if (name.len > 0 and std.ascii.findIgnoreCase(theme_name, name) != null) name.len * 4 else 0;
return prefix * 3 + in_order + inside;
}
/// The theme named `name`, whatever its case.
pub fn themeIndex(name: []const u8) ?usize {
for (themes, 0..) |t, i| if (std.ascii.eqlIgnoreCase(t.name, name)) return i;
return null;
}
/// The window wearing theme `index` (SPEC §5.1, a theme's preview), or
/// its own again (null): nothing loaded, the session's theme and a theme
/// file as they were; its chrome worked out once a theme, never a frame.
/// The themes picker's (Pick.zig), and `:theme `'s argument rows'.
pub fn previewTheme(p: *Pardes, index: ?usize) void {
const i = index orelse {
p.theme_preview = null;
return;
};
if (i >= themes.len) return;
if (p.theme_preview) |had| if (had == i) return;
p.theme_preview = @intCast(i);
p.preview_chrome = .of(&themes[i]);
}
pub fn setThemeIndex(p: *Pardes, index: usize) void {
if (index >= themes.len or
(p.custom_theme == null and p.theme_file_path.get().len == 0 and
index == @as(usize, p.settings.theme))) return;
p.theme_chrome = .of(&themes[index]);
if (p.custom_theme) |theme_value| {
p.custom_theme = null;
p.gpa.free(theme_value.name);
}
p.theme_file_loaded.clear();
if (p.theme_file_path.get().len > 0) {
p.theme_file_path.clear();
const generation = nextThemeFileGeneration(p);
p.emit(.{ .theme_file = .{ .generation = generation, .on = false } });
}
p.settings.theme = @intCast(index);
}
test "a theme's own rule is kept where it already stands off its page" {
const forge = &themes[comptime indexOfTheme("forge")];
try std.testing.expectEqual(forge.rule.?, Chrome.of(forge).rule);
}
test "an OKLab fade holds its ends exactly and keeps a mid-way bright" {
for ([_][3]u8{ .{ 0, 0, 0 }, .{ 255, 255, 255 }, .{ 0x0c, 0x0c, 0x0e }, .{ 0xe8, 0xc4, 0x6a }, .{ 0x1c, 0x51, 0x72 } }) |rgb| {
try std.testing.expectEqual(rgb, fromOklab(toOklab(rgb)));
try std.testing.expectEqual(rgb, mixOklab(rgb, .{ 10, 200, 30 }, 0));
}
// Red to green through sRGB bytes dips dark at the middle; through
// OKLab it keeps its lightness.
const red: [3]u8 = .{ 255, 0, 0 };
const green: [3]u8 = .{ 0, 200, 0 };
const srgb_mid: [3]u8 = .{ 128, 100, 0 };
const lab_mid = mixOklab(red, green, 0.5);
try std.testing.expect(relativeLuminance(lab_mid) > relativeLuminance(srgb_mid) * 1.3);
}
test "the picker's sections run in ring order and cover it" {
var last: usize = 0;
inline for (theme_groups, 0..) |g, n| {
const at = comptime indexOfTheme(g.first);
if (n == 0) try std.testing.expectEqual(@as(usize, 0), at) else try std.testing.expect(at > last);
last = at;
}
try std.testing.expectEqualStrings("Pardes", groupAt(0).?);
try std.testing.expectEqualStrings("dark", themes[0].name);
try std.testing.expectEqualStrings("orchard", themes[default_theme].name);
// acme is a current theme, not a legacy one.
try std.testing.expect(indexOfTheme("acme") < indexOfTheme("helix"));
// The imported a family at a time, each under its heading, the lone
// ones last under one.
try std.testing.expect(std.mem.startsWith(u8, groupAt(native_count).?, "Imported: "));
const gruvbox = for (themes, 0..) |t, i| {
if (std.mem.eql(u8, t.name, "gruvbox")) break i;
} else unreachable;
try std.testing.expectEqualStrings("Imported: gruvbox", groupAt(gruvbox).?);
try std.testing.expectEqual(null, groupAt(gruvbox + 1));
const lone = for (themes[native_count..], native_count..) |_, i| {
if (groupAt(i)) |title| if (std.mem.eql(u8, title, "Imported, one of a kind")) break i;
} else unreachable;
for (themes[lone + 1 ..], lone + 1..) |_, i| try std.testing.expectEqual(null, groupAt(i));
}
test "seoul256's eight backgrounds ring in their order, after Catppuccin and before Zenbones" {
const names = [_][]const u8{
"seoul256_dark_233", "seoul256_dark_234", "seoul256_dark_235", "seoul256_dark_236",
"seoul256_dark_237", "seoul256_light_254", "seoul256_light_255", "seoul256_light_256",
};
const first = indexOfTheme("seoul256_dark_233");
for (names, themes[first..][0..names.len]) |name, t| try std.testing.expectEqualStrings(name, t.name);
try std.testing.expectEqualStrings("catppuccin_mocha", themes[first - 1].name);
try std.testing.expectEqualStrings("zenbones_light", themes[first + names.len].name);
}
test "a theme hint drops whole names to fit, never cutting one" {
var buf: [23]u8 = undefined;
const said = themesNear(&buf, "9dracula");
var words = std.mem.tokenizeScalar(u8, said, ' ');
while (words.next()) |word| {
var whole = false;
for (themes) |t| whole = whole or std.mem.eql(u8, t.name, word);
try std.testing.expect(whole);
}
}
test "a theme file that cannot be read is named in the failure" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
requestThemeFile(p, 0, "/nowhere/mine.zon");
failThemeFile(p, p.theme_file_generation, error.FileNotFound);
const pane = p.panes[0].?;
try std.testing.expect(std.mem.indexOf(u8, p.messages.saidBy(pane), "theme file /nowhere/mine.zon: ") != null);
}
test "a theme file nested 10, 1 000 and 100 000 deep is refused in words, never a stack overflow" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .config_dir = "/tmp/pardes-config" });
defer p.deinit();
for ([_]usize{ 10, 1000, 100_000 }) |depth| {
requestThemeFile(p, 0, "themes/deep.zon");
var source: std.ArrayList(u8) = .empty;
defer source.deinit(gpa);
try source.appendSlice(gpa, ".{ .name = \"deep\", .bg = ");
for (0..depth) |_| try source.appendSlice(gpa, ".{");
try source.appendSlice(gpa, "1");
for (0..depth) |_| try source.append(gpa, '}');
try source.appendSlice(gpa, " }\n");
p.messages.live_len = 0;
// Up to 2026-11-23 std's parser took it: 5 000 deep overflowed the
// stack (a Debug build's 16 MiB).
try std.testing.expect(!loadThemeFile(p, p.theme_file_generation, source.items));
const said = p.messages.saidBy(p.panes[0].?);
std.testing.expect(std.mem.indexOf(u8, said, "theme file /tmp/pardes-config/themes/deep.zon: ") != null) catch |err| {
std.debug.print("{d} deep: said {s}\n", .{ depth, said });
return err;
};
}
}
test "ThemeFile parses ZON atomically and Theme returns to the compiled ring" {
const p = try Pardes.init(std.testing.allocator, .{
.tty_only = true,
.config_dir = "/tmp/pardes-config",
});
defer p.deinit();
while (p.nextEffect()) |_| {}
requestThemeFile(p, 0, "themes/mine.zon");
const request_effect = while (p.nextEffect()) |effect| switch (effect) {
.theme_file => |request| break request,
else => {},
} else return error.MissingThemeFileEffect;
try std.testing.expect(request_effect.on);
const request = themeFileRequest(p, request_effect.generation) orelse
return error.MissingThemeFileRequest;
try std.testing.expectEqualStrings("/tmp/pardes-config/themes/mine.zon", request.path);
var custom = themes[default_theme];
custom.name = "mine";
custom.page = .{ 1, 2, 3 };
custom.tag = .{ 4, 5, 6 };
var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer encoded.deinit();
try std.zon.stringify.serialize(custom, .{ .whitespace = true }, &encoded.writer);
try std.testing.expect(loadThemeFile(p, request_effect.generation, encoded.written()));
try std.testing.expectEqualStrings("mine", p.theme().name);
try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().page);
try std.testing.expectEqual(Chrome.of(p.theme()), p.chrome().*);
// A half-written save is rejected without disturbing the last good value.
try std.testing.expect(!loadThemeFile(p, request_effect.generation, ".{ .name = "));
// Said with its line, in words: never a bare `parse zon`.
const said = p.messages.saidBy(p.panes[0].?);
try std.testing.expect(std.mem.indexOf(u8, said, ": line 1: ") != null and std.mem.indexOf(u8, said, "parse zon") == null);
try std.testing.expectEqualStrings("mine", p.theme().name);
try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().page);
setThemeIndex(p, default_theme);
try std.testing.expectEqualStrings(themes[default_theme].name, p.theme().name);
try std.testing.expect(themeFileRequest(p, request_effect.generation) == null);
const stop = while (p.nextEffect()) |effect| switch (effect) {
.theme_file => |theme_file| break theme_file,
else => {},
} else return error.MissingThemeFileStop;
try std.testing.expect(!stop.on);
}
test "native themes keep text and UI roles readable on their own surfaces" {
for (designed) |name| {
const th = &themes[themeIndex(name).?];
const c = Chrome.of(th);
const page = th.page.?;
const minimum: f32 = if (std.mem.eql(u8, name, "ink") or std.mem.eql(u8, name, "daybreak")) 7 else 4.5;
const text_colors = [_][3]u8{ th.text.?, th.keyword, th.string, th.number, th.comment } ++ c.page.severity;
for (text_colors) |fg| try std.testing.expect(contrast(fg, page) >= minimum);
// Gutters are orientation aids, not source text: stay visible without
// competing with comments or pulling attention away from the body.
try std.testing.expect(contrast(c.line_number, page) >= 2.5);
try std.testing.expect(contrast(c.line_number, page) <= 4);
try std.testing.expect(contrast(c.line_number_current, page) >= contrast(c.line_number, page));
try std.testing.expect(contrast(c.line_number_current, page) <= 4.5);
try std.testing.expect(contrast(th.comment, page) >= 5);
try std.testing.expect(contrast(th.comment, page) >= contrast(c.line_number, page) + 2);
try std.testing.expect(th.tag_name != null);
for (c.tag, c.name) |inks, tint| {
try std.testing.expect(contrast(inks.text, inks.ground) >= minimum);
try std.testing.expect(contrast(tint, inks.ground) >= minimum);
}
// Focus stays on the same tonal surface, rather than inverting a
// whole command strip. Text remains readable in both states.
try std.testing.expect(contrast(c.tag[1].ground, c.tag[0].ground) <= 1.6);
try std.testing.expect(contrast(c.tag[1].text, c.tag[0].text) <= 1.6);
try std.testing.expect(contrast(c.page.selection.text, c.page.selection.ground) >= minimum);
try std.testing.expect(contrast(c.hit_current_text, c.hit_current) >= Chrome.text_floor);
// ANSI black can intentionally match the page (for backgrounds). All
// other ANSI foregrounds, including bright black, remain legible.
for (c.ansi[1..]) |fg| try std.testing.expect(contrast(fg, page) >= minimum);
}
}
/// The natives written before the colour system (DESIGN.md B), each with a
/// name tint and a column grip of its own: what the tests of their own
/// values below hold (the ring test holds every theme to B4's floors).
const designed = [_][]const u8{ "orchard", "dusk", "ink", "paper", "daybreak", "atelier", "forge", "lagoon", "solarium", "spectrum", "harvest", "clay", "forge_black", "forge_soft", "orchard_black" };
test "native filename tints change hue without changing perceived lightness" {
for (designed) |native| {
const th = &themes[themeIndex(native).?];
// The theme's own tint at its tag ink's lightness (the focused one
// Chrome.of's, R13).
const pairs = [1][2][3]u8{
.{ th.tag_text, th.tag_name.? },
};
for (pairs) |pair| {
const base = toOklab(pair[0]);
const name = toOklab(pair[1]);
// Half a lightness point allows 8-bit quantization without a
// basename becoming visibly brighter or darker than its tag.
try std.testing.expectApproxEqAbs(base[0], name[0], 0.005);
const base_chroma = @sqrt(base[1] * base[1] + base[2] * base[2]);
const name_chroma = @sqrt(name[1] * name[1] + name[2] * name[2]);
try std.testing.expect(base_chroma > 0.005 and name_chroma > 0.02);
// A normalized dot product <= cos(60 degrees) means a clear
// hue difference, independent of saturation or lightness.
const hue_cosine = (base[1] * name[1] + base[2] * name[2]) / (base_chroma * name_chroma);
try std.testing.expect(hue_cosine <= 0.5);
}
}
}
test "native dark palettes choose near-black or deliberately soft contrast" {
for (designed) |name| {
const th = &themes[themeIndex(name).?];
if (contrast(th.page.?, .{ 0, 0, 0 }) > 10) continue; // light paper
const soft = std.mem.eql(u8, th.name, "dusk") or std.mem.eql(u8, th.name, "lagoon") or
std.mem.eql(u8, th.name, "solarium") or std.mem.eql(u8, th.name, "forge_soft");
if (soft) {
try std.testing.expect(contrast(th.text.?, th.page.?) >= 4.5);
try std.testing.expect(contrast(th.text.?, th.page.?) <= 7);
} else {
for (th.page.?) |channel| try std.testing.expect(channel <= 0x14);
try std.testing.expect(contrast(th.text.?, th.page.?) >= 14);
}
}
const forge = curated.forge.theme;
try std.testing.expectEqual(forge.page[0], forge.page[1]);
// Forge chrome is cool-neutral, never the old green-over-blue mint cast.
for ([_][3]u8{ forge.tag, forge.tag_focus, forge.accent, forge.rule }) |rgb|
try std.testing.expect(rgb[2] >= rgb[1]);
try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.forge_black.theme.page));
try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.orchard_black.theme.page));
}
test "line numbers stay quiet without a current-line tag background" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const pane = try p.setTestFile("first\nsecond\n");
pane.body.cur_pinned = true;
pane.body.cur_row = 0;
var custom = themes[default_theme];
custom.name = try gpa.dupe(u8, "quiet-gutter");
custom.line_number = .{ 70, 70, 70 };
custom.line_number_current = .{ 95, 95, 95 };
p.custom_theme = custom;
finishThemeInitialization(p);
p.sync();
const x = p.view().rects[0].x + config.GUTTER;
const y = p.view().rects[0].y + BOX_H;
const surface = try p.render(p.scratch.allocator());
try std.testing.expectEqual(Color{ .rgb = .{ 95, 95, 95 } }, surface.at(x, y).style.fg);
try std.testing.expectEqual(Color{ .rgb = .{ 70, 70, 70 } }, surface.at(x, y + 1).style.fg);
try std.testing.expectEqual(Color{ .rgb = custom.page.? }, surface.at(x, y).style.bg);
try std.testing.expect(surface.at(x, y).style.bold);
try std.testing.expect(!surface.at(x, y + 1).style.bold);
// Old ThemeFile palettes need no new field: the current number is the
// text toward the page to 4.5:1 (R12), and the block not regained.
p.custom_theme.?.line_number_current = null;
finishThemeInitialization(p);
const fallback = try p.render(p.scratch.allocator());
try std.testing.expectEqual(Color{ .rgb = p.chrome().line_number_current }, fallback.at(x, y).style.fg);
try std.testing.expect(contrast(p.chrome().line_number_current, custom.page.?) >= Chrome.text_floor - 0.05);
try std.testing.expectEqual(Color{ .rgb = custom.page.? }, fallback.at(x, y).style.bg);
try std.testing.expect(fallback.at(x, y).style.bold);
// Moving the caret clears the previous cue; editing the tag parks it.
pane.body.cur_row = 1;
const moved = try p.render(p.scratch.allocator());
try std.testing.expect(!moved.at(x, y).style.bold);
try std.testing.expect(moved.at(x, y + 1).style.bold);
tagline.enterTag(p, pane);
const tag_edit = try p.render(p.scratch.allocator());
try std.testing.expect(!tag_edit.at(x, y + 1).style.bold);
}
test "column grip colors remain distinct from pane grips across native themes" {
for (designed) |name| {
const th = &themes[themeIndex(name).?];
// The theme's own (their rest and grabbed inks Chrome.of's, R6, H).
for ([_][2][3]u8{
.{ th.accent, th.column_grip.? },
}) |pair| {
var distance: u32 = 0;
for (pair[0], pair[1]) |a, b| {
const delta = @as(i32, a) - b;
distance += @intCast(delta * delta);
}
try std.testing.expect(distance >= 30 * 30);
}
}
}
test "every theme tints its names off the tag's ink, and they read on both grounds" {
for (&themes) |*th| {
const c = Chrome.of(th);
const pairs = [2][3][3]u8{
.{ c.tag[0].text, c.name[0], c.tag[0].ground },
.{ c.tag[1].text, c.name[1], c.tag[1].ground },
};
for (pairs) |pair| {
const ink, const name, const ground = pair;
// An ink held to the end of the gamut (white or black, H's 7:1
// on a mid-grey tag: ao's, modus_vivendi's) has no hue at its
// lightness: the name is the ink.
if (std.mem.eql(u8, &name, &ink) and (std.mem.eql(u8, &ink, &@as([3]u8, @splat(255))) or std.mem.eql(u8, &ink, &@as([3]u8, @splat(0))))) continue;
const apart = oklabDistance(toOklab(ink), toOklab(name));
const floor = nameTintFloor(ink, ground);
if (apart < name_tint_distance or contrast(name, ground) < floor - 0.01)
std.debug.print("{s}: name {x} on {x} is {d:.3} off the ink {x}, {d:.2}:1\n", .{ th.name, name, ground, apart, ink, contrast(name, ground) });
try std.testing.expect(apart >= name_tint_distance);
try std.testing.expect(contrast(name, ground) >= floor - 0.01);
}
}
}
test "neonotte84's and acme's inks on the plain tag, their reading mark and their hits are B4's (DESIGN.md B4, D4's goldens re-pinned where B4 moves them)" {
const Want = struct { name: []const u8, text: [3]u8, dim: [3]u8, rule: [3]u8, key: [3]u8, match: [3]u8, mode: [3]u8, hit: [3]u8, hit_current: [3]u8 };
const wants = [_]Want{
// Text, dim, rule and key as D4 derived them; the match the hits'
// amber held on this ground alone (D4's pushed neonotte84's number
// over all seven grounds at once: #f1a271; L1's #e29e47 the warning
// pardes derived, its own palette's since B7, #e59d3c, the current
// hit's too); the reading mark sky
// on the grip, 3:1 on both tags (D4 tinted the whole tag #29271e);
// the hit an amber ground 1.5:1 off the page (D4's mixed the
// number in: #47322e) and the current one that amber itself, solid
// (D4's a 1.9:1 ground, #5f3f33).
.{ .name = "neonotte84", .text = .{ 0xb5, 0xbf, 0xe3 }, .dim = .{ 0x70, 0x76, 0x8f }, .rule = .{ 0x4c, 0x50, 0x63 }, .key = .{ 0xf8, 0xde, 0xd9 }, .match = .{ 0xe5, 0x9d, 0x3c }, .mode = .{ 0x2b, 0x92, 0xbc }, .hit = .{ 0x4c, 0x30, 0x1a }, .hit_current = .{ 0xe5, 0x9d, 0x3c } },
// acme's key and match on its plain tag alone, never held to its
// #9eeeee selection and its reading ground at once (D4's #555583,
// #8f4800): its #8888cc darkened to 4.5:1, its number as it is; the
// hits in its number's hue (its selection sits on the warning's):
// a ground 1.5:1 off the page (D4's #e6cdae), the current one the
// number itself (D4's #d9b490); the reading mark sky on the grip
// (its #f3f0cc reading tag goes with the mode ground, G1').
.{ .name = "acme", .text = .{ 0, 0, 0 }, .dim = .{ 0x7a, 0x86, 0x86 }, .rule = .{ 0xa8, 0xb7, 0xb7 }, .key = .{ 0x6e, 0x6d, 0xaf }, .match = .{ 0xa0, 0x52, 0x00 }, .mode = .{ 0x1e, 0x8a, 0xb3 }, .hit = .{ 0xff, 0xc7, 0x90 }, .hit_current = .{ 0xa0, 0x52, 0x00 } },
};
for (wants) |want| {
const c = Chrome.of(&themes[themeIndex(want.name).?]);
const plain = c.on(.plain);
const got = [_][3]u8{ plain.text, plain.dim, plain.rule, plain.key, plain.match, c.grip.mode, c.hit, c.hit_current };
const expected = [_][3]u8{ want.text, want.dim, want.rule, want.key, want.match, want.mode, want.hit, want.hit_current };
for (got, expected, 0..) |g, e, i| for (g, e) |x, y| if (@abs(@as(i16, x) - y) > 2) {
std.debug.print("{s} ink {d}: {x} for {x}\n", .{ want.name, i, g, e });
return error.TestUnexpectedResult;
};
}
}
test "the error ink is a theme's own, else its red (UX E3): neonotte84's (its diagnostic.error an underline only) its red, acme's its palette's, on the page and every tag ground" {
const neonotte = &themes[themeIndex("neonotte84").?];
// neonotte.toml: "error" = { fg = "red" }, its palette's red #ff7ea2.
try std.testing.expectEqual([3]u8{ 0xff, 0x7e, 0xa2 }, neonotte.@"error".?);
for ([_][]const u8{ "neonotte84", "acme" }) |name| {
const c = Chrome.of(&themes[themeIndex(name).?]);
for ([1]Chrome.Inks{c.page} ++ c.tag) |inks| {
const err = inks.severity[@backingInt(Chrome.Severity.@"error")];
try std.testing.expect(err[0] > err[1] + 40 and err[0] > err[2] + 40);
}
}
try std.testing.expectEqual([3]u8{ 0xaa, 0x22, 0x22 }, Chrome.of(&themes[themeIndex("acme").?]).page.severity[0]);
}
/// What the ring is held to (DESIGN.md A8, B4's floors): a state pardes
/// draws that must read (each check not `pro`), or the professional floor
/// (`pro`: natives and `dark` are held to it too). The `original` checks
/// are a theme's own colours: a port's or an import's are reported, never
/// held against it, except the sixteen where pardes derives them.
const RingCheck = enum {
text,
text7,
syntax,
syntax45,
comment,
comment45,
line_number,
selection,
selection_pro,
hit,
hit_current,
selection_hit,
tag_text,
focus,
focus_text,
tone,
grip_mode,
grip,
grip_pro,
grip_ring,
rule,
status_text,
words,
loudest,
band,
column_grip,
tag_text7,
severities,
severities4,
error_red,
diff,
ansi,
ansi_pro,
inks,
fn pro(c: RingCheck) bool {
return switch (c) {
.text7, .syntax45, .comment45, .line_number, .selection_pro, .selection_hit, .tone, .grip_pro, .grip_ring, .severities4, .error_red, .ansi_pro, .tag_text7 => true,
else => false,
};
}
fn original(c: RingCheck) bool {
return switch (c) {
.text, .text7, .syntax, .syntax45, .comment, .comment45, .line_number, .ansi, .ansi_pro => true,
else => false,
};
}
};
/// The checks `th`'s chrome fails.
fn ringFailures(th: *const Theme, c: *const Chrome, designed_here: bool) std.EnumSet(RingCheck) {
var f: std.EnumSet(RingCheck) = .empty;
const de = struct {
fn of(a: [3]u8, b: [3]u8) f32 {
return oklabDistance(toOklab(a), toOklab(b));
}
}.of;
const page = c.page.ground;
const ink = c.page.text;
const dark = isDark(page);
const text = contrast(ink, page);
f.setPresent(.text, text < 4.5);
f.setPresent(.text7, text < 7);
const syntax = @min(contrast(th.keyword, page), contrast(th.string, page), contrast(th.number, page));
f.setPresent(.syntax, syntax < 3);
f.setPresent(.syntax45, syntax < 4.5);
f.setPresent(.comment, contrast(th.comment, page) < 3);
f.setPresent(.comment45, contrast(th.comment, page) < 4.5);
const line = contrast(c.line_number, page);
f.setPresent(.line_number, line < 2 or line > 4.5);
const sel = c.page.selection;
f.setPresent(.selection, contrast(sel.ground, page) < 1.2 or contrast(sel.text, sel.ground) < 4.5);
f.setPresent(.selection_pro, contrast(sel.ground, page) < (if (dark) Chrome.selection_dark else Chrome.selection_light) - 0.005);
const hit_off = contrast(c.hit, page);
f.setPresent(.hit, !((hit_off >= 1.49 or (hit_off >= 1.1 and de(c.hit, page) >= 0.08)) and contrast(ink, c.hit) >= @min(4.5, text * 0.9) - 0.05));
f.setPresent(.hit_current, !((contrast(c.hit_current, c.hit) >= 1.12 or de(c.hit_current, c.hit) >= 0.05) and contrast(c.hit_current_text, c.hit_current) >= 4.49));
f.setPresent(.selection_hit, de(sel.ground, c.hit) < 0.05);
const tag = c.on(.plain);
const focus = c.on(.focus);
const focus_floor = if (isDark(tag.ground)) Chrome.focus_dark else Chrome.focus_light;
f.setPresent(.tag_text, contrast(tag.text, tag.ground) < 4.49);
f.setPresent(.focus, contrast(focus.ground, tag.ground) < focus_floor - 0.01);
f.setPresent(.focus_text, contrast(focus.text, focus.ground) < 4.49);
f.setPresent(.tone, isDark(tag.ground) != dark or isDark(focus.ground) != dark);
// R5': the reading mark 3:1 on both tags, off the resting ring, and
// its hue told from the grip's others where a mode hue is.
var said: [3]f32 = undefined;
var n_said: usize = 0;
for ([3][3]u8{ c.grip.focus, c.page.severity[1], c.page.severity[0] }) |s| if (lch(s)[1] >= 0.04) {
said[n_said] = lch(s)[2];
n_said += 1;
};
const apart = struct {
fn of(h: f32, taken: []const f32) f32 {
var least: f32 = 180;
for (taken) |t| least = @min(least, hueDistance(h, t));
return least;
}
}.of;
const room = for (mode_hues) |h| {
if (apart(h, said[0..n_said]) >= 40) break true;
} else false;
f.setPresent(.grip_mode, @min(contrast(c.grip.mode, tag.ground), contrast(c.grip.mode, focus.ground)) < 2.99 or
de(c.grip.mode, c.grip.ring) < 0.10 or (room and apart(lch(c.grip.mode)[2], said[0..n_said]) < 40 - 1));
const grip = contrast(c.grip.focus, focus.ground);
f.setPresent(.grip, grip < 2 and de(c.grip.focus, focus.ground) < 0.2);
f.setPresent(.grip_pro, grip < 2.99);
f.setPresent(.grip_ring, contrast(c.grip.ring, tag.ground) < 1.5);
f.setPresent(.rule, contrast(c.rule, page) < 1.49);
f.setPresent(.status_text, contrast(c.status.text, c.status.ground) < 4.49);
// H: the words at 4.5:1 on both tags and the page (or the full ink,
// where it has no more); the full ink up to 7:1; the focused band the
// loudest; the plain tag a band off the page, or rules of 3:1; the
// column grip 2:1 at rest, 3:1 grabbed.
for ([3]*const Chrome.Inks{ tag, focus, &c.page }) |g| {
if (contrast(g.word, g.ground) < @min(4.49, contrast(g.text, g.ground) - 0.01)) f.insert(.words);
}
f.setPresent(.loudest, contrast(focus.ground, page) <= contrast(tag.ground, page));
f.setPresent(.band, contrast(tag.ground, page) < Chrome.band_floor - 0.005 and contrast(c.rule, page) < 3);
const rest = contrast(c.grip.column_rest, page);
const grabbed = contrast(c.grip.column, page);
f.setPresent(.column_grip, rest < 1.99 or grabbed < 2.99 or grabbed <= rest);
f.setPresent(.tag_text7, @min(contrast(tag.text, tag.ground), contrast(focus.text, focus.ground)) < 6.99);
var apart3: f32 = 2;
var apart4: f32 = 2;
for (c.page.severity, 0..) |a, i| {
for (c.page.severity[i + 1 ..], i + 1..) |b, j| {
if (j < 3) apart3 = @min(apart3, de(a, b));
apart4 = @min(apart4, de(a, b));
}
if (i < 3) apart3 = @min(apart3, de(a, ink));
apart4 = @min(apart4, de(a, ink));
}
f.setPresent(.severities, apart3 < Chrome.severity_apart);
f.setPresent(.severities4, apart4 < Chrome.severity_apart);
const err = lch(c.page.severity[0]);
f.setPresent(.error_red, !(err[1] >= 0.08 and (err[2] <= 50 or err[2] >= 330)));
// R10: each diff row 1.15:1 off the page, and the two 0.05 apart; a
// port's or an import's nearer where its own text holds it (never
// under its floor there: tokyonight_day's text, 4.9:1, leaves 1.11:1);
// pardes's own themes always (the coordinator's ruling).
const diff_floor = @min(4.5, text * 0.9);
for ([2][3]u8{ c.add.row, c.del.row }) |row| {
if (contrast(row, page) < Chrome.row_step - 0.005 and (designed_here or contrast(ink, row) > diff_floor + 0.05)) f.insert(.diff);
}
if (de(c.add.row, c.del.row) < 0.05) f.insert(.diff);
var ansi_least: f32 = 21;
for (c.ansi[1..], 1..) |a, i| {
ansi_least = @min(ansi_least, contrast(a, page));
if (contrast(a, page) < @as(f32, if (i == 8) 2 else 3)) f.insert(.ansi);
}
f.setPresent(.ansi_pro, ansi_least < 4.5);
// Every ink on every ground it is drawn on (B1.3): its floor, or the
// most any ink reaches there.
const reach = struct {
fn of(g: [3]u8) f32 {
return @max(contrast(@splat(255), g), contrast(@splat(0), g)) - 0.01;
}
}.of;
for ([1]Chrome.Inks{c.page} ++ c.tag ++ [1]Chrome.Inks{c.status}, 0..) |g, n| {
const t = contrast(g.text, g.ground);
var low = (n > 0 and t < @min(4.5, reach(g.ground))) or contrast(g.dim, g.ground) < @min(3, t) - 0.01;
for ([2][3]u8{ g.key, g.match } ++ g.severity) |i| low = low or contrast(i, g.ground) < @min(4.5, reach(g.ground));
// The kind mark on the ground and on its selection, a list's
// cursor row: one ink for both, 4.5:1 where the keyword's hue
// reaches it there (held to the end of light, a hue keeps a trace
// of itself: #000100 on solarized_dark's grey tag reads 4.49).
const both = [2][3]u8{ g.ground, g.selection.ground };
const most = leastContrast(hold(th.keyword, &both, 21), &both);
low = low or leastContrast(g.kind, &both) < @min(4.5, most) - 0.01;
low = low or contrast(g.selection.text, g.selection.ground) < @min(4.5, reach(g.selection.ground));
// The keys and the matched letters on its selection, a ground of
// its own (a list's cursor row, B1.3).
for ([2][3]u8{ g.selection.key, g.selection.match }) |i| low = low or contrast(i, g.selection.ground) < @min(4.5, reach(g.selection.ground));
if (low) f.insert(.inks);
}
// A message's mark on each fill a grid's grip has, at rest and reading
// on the plain tag too, where a window's grip is hollow (Grip.marks):
// 4.5:1 where its hue reaches it there.
for (c.grip.marks, [4][3]u8{ c.grip.focus, c.grip.dirty, c.grip.ring, c.grip.mode }, 0..) |m, fill, i| {
const both = [2][3]u8{ fill, c.tag[0].ground };
const grounds = if (i < @intFromEnum(Chrome.Fill.ring)) both[0..1] else both[0..];
for (m.severity[0..3], c.tag[0].severity[0..3]) |mark, own| {
if (leastContrast(mark, grounds) < @min(4.5, leastContrast(hold(own, grounds, 21), grounds)) - 0.01) f.insert(.inks);
}
}
return f;
}
/// The soft natives: their text 4.5-7:1 by design, held at AA, never the
/// professional 7:1, and never retuned (the coordinator's ruling; solarium
/// is the user's).
const soft_themes = [_][]const u8{ "dusk", "lagoon", "solarium", "forge_soft" };
test "every theme in the ring meets every floor pardes owns (DESIGN.md B4), natives and dark the professional ones too; the original's own colours never moved" {
// pardes's own: every theme before the first faithful port (dark and
// the new ones among them), and the captured helix's originals.
const ports = comptime indexOfTheme("dark_plus");
const helix = comptime indexOfTheme("helix");
var passing: usize = 0;
for (&themes, 0..) |*th, i| {
const c = Chrome.of(th);
// The original's own (B1.5): never moved.
for ([4][3]u8{ th.keyword, th.string, th.number, th.comment }, c.syntax[1..]) |own, got| try std.testing.expectEqual(own, got);
if (th.text) |own| try std.testing.expectEqual(own, c.page.text);
if (th.page) |own| try std.testing.expectEqual(own, c.page.ground);
if (th.ansi) |own| try std.testing.expectEqual(own, c.ansi);
if (th.line_number) |own| try std.testing.expectEqual(own, c.line_number);
const ours = i < ports or i == helix;
const soft = for (soft_themes) |name| {
if (std.mem.eql(u8, name, th.name)) break true;
} else false;
const failures = ringFailures(th, &c, i < ports);
var held: std.EnumSet(RingCheck) = .empty;
var it = failures.iterator();
while (it.next()) |check| {
if (check.pro() and i >= ports) continue;
// A soft theme's text is held at AA, 4.5:1, never the pro 7:1.
if (soft and (check == .text7 or check == .tag_text7)) continue;
if (check.original() and !ours and !(std.mem.startsWith(u8, @tagName(check), "ansi") and th.ansi == null)) continue;
held.insert(check);
}
if (held.count() == 0) {
passing += 1;
continue;
}
std.debug.print("{s} fails:", .{th.name});
var failed = held.iterator();
while (failed.next()) |check| std.debug.print(" {s}", .{@tagName(check)});
std.debug.print("\n", .{});
}
std.debug.print("ring floors: {d} of {d} themes pass\n", .{ passing, themes.len });
try std.testing.expectEqual(themes.len, passing);
}
/// A faithful port's own colours pardes moves where they miss a floor: its
/// indicators and grounds (B1.6, G4: only that colour, and its file says
/// so); its text, syntax, comments and sixteen never move (the ring test).
/// Each with the ground it is held on, for the words its file says.
fn portMoves(th: *const Theme, c: *const Chrome) [12]struct { role: []const u8, own: ?[3]u8, got: [3]u8, on: [3]u8 } {
const page = c.page.ground;
return .{
.{ .role = "tag ground", .own = th.tag, .got = c.tag[0].ground, .on = page },
.{ .role = "focused tag ground", .own = th.tag_focus, .got = c.tag[1].ground, .on = c.tag[0].ground },
.{ .role = "focused grip", .own = th.accent, .got = c.grip.focus, .on = c.tag[1].ground },
.{ .role = "grip ring", .own = th.grip_ring, .got = c.grip.ring, .on = c.tag[0].ground },
.{ .role = "unsaved grip", .own = th.dirty, .got = c.grip.dirty, .on = c.tag[0].ground },
.{ .role = "selection", .own = th.selection, .got = c.page.selection.ground, .on = page },
.{ .role = "selection text", .own = th.selection_text, .got = c.page.selection.text, .on = c.page.selection.ground },
.{ .role = "search hit", .own = th.hit, .got = c.hit, .on = page },
.{ .role = "error", .own = th.@"error", .got = c.page.severity[0], .on = page },
.{ .role = "warning", .own = th.warning, .got = c.page.severity[1], .on = page },
.{ .role = "info", .own = th.info, .got = c.page.severity[2], .on = page },
.{ .role = "hint", .own = th.hint, .got = c.page.severity[3], .on = page },
};
}
test "every faithful port's file says each of its own colours pardes moves to meet a floor (DESIGN.md G4)" {
const first = comptime indexOfTheme("dark_plus");
const last = comptime indexOfTheme("doom_one_light");
var unsaid: usize = 0;
inline for (@typeInfo(curated).@"struct".decl_names[first .. last + 1], first..) |d, i| {
const file = comptime if (std.mem.startsWith(u8, d, "seoul256_")) "seoul256" else d;
const source = @embedFile("themes/" ++ file ++ ".zig");
const c = Chrome.of(&themes[i]);
for (portMoves(&themes[i], &c)) |m| if (m.own) |own| if (!std.mem.eql(u8, &own, &m.got)) {
var buf: [64]u8 = undefined;
const said = try std.fmt.bufPrint(&buf, "{s} #{x:0>2}{x:0>2}{x:0>2} -> #{x:0>2}{x:0>2}{x:0>2}", .{ m.role, own[0], own[1], own[2], m.got[0], m.got[1], m.got[2] });
if (std.mem.indexOf(u8, source, said) == null) {
unsaid += 1;
std.debug.print("unsaid\t{s}\t{s}\t{s}\t{d:.2}\t{d:.2}\n", .{ themes[i].name, file, said, contrast(own, m.on), contrast(m.got, m.on) });
}
};
}
try std.testing.expectEqual(0, unsaid);
}
/// B9's budget, about 0.5 ms a theme and the ring in 150 ms on an idle
/// machine (Debug), in user-space instructions, which a loaded machine does
/// not move: Chrome.of retires about 7 a nanosecond here (the ring's 304 M
/// in 42 ms of an idle CPU, 2026-11-26).
const theme_instructions: u64 = 3_500_000;
const ring_instructions: u64 = 1_050_000_000;
test "the whole ring resolves within B9's budget, about 0.5 ms a theme and 150 ms in all on an idle machine, counted in instructions (Debug)" {
if (builtin.os.tag != .linux) return error.SkipZigTest;
const linux = std.os.linux;
var attr: linux.perf_event_attr = .{ .type = .HARDWARE, .config = @intFromEnum(linux.PERF.COUNT.HW.INSTRUCTIONS), .flags = .{ .exclude_kernel = true, .exclude_hv = true } };
const rc = linux.perf_event_open(&attr, 0, -1, -1, 0);
// No counter here (a container, perf_event_paranoid 3): nothing to count.
if (linux.errno(rc) != .SUCCESS) return error.SkipZigTest;
const fd: i32 = @intCast(rc);
defer _ = linux.close(fd);
var total: u64 = 0;
var worst: u64 = 0;
var worst_at: usize = 0;
for (&themes, 0..) |*th, i| {
var before: u64 = 0;
var after: u64 = 0;
_ = linux.read(fd, std.mem.asBytes(&before), 8);
var c = Chrome.of(th);
std.mem.doNotOptimizeAway(&c);
_ = linux.read(fd, std.mem.asBytes(&after), 8);
total += after - before;
if (after - before > worst) {
worst = after - before;
worst_at = i;
}
}
std.debug.print("ring resolved in {d} instructions, the most {s}'s {d}\n", .{ total, themes[worst_at].name, worst });
try std.testing.expect(total < ring_instructions);
try std.testing.expect(worst <= theme_instructions);
}
test "a theme file in the old names, a user's own or an older DumpThemes', and DumpThemes' now in the new names, load to the same Chrome" {
@setEvalBranchQuota(20000);
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .config_dir = "/tmp/pardes-config" });
defer p.deinit();
// ~/.config/pardes/themes/one_dark_zed_mod.zon's shape: the seventeen
// fields the old names required, no others.
const own =
\\.{
\\ .name = "one_dark_zed",
\\ .bg = .{ 0, 0, 0 },
\\ .fg = .{ 172, 178, 190 },
\\ .sel_bg = .{ 69, 74, 86 },
\\ .sel_fg = .{ 172, 178, 190 },
\\ .tag_bg = .{ 59, 65, 77 },
\\ .tag_fg = .{ 169, 175, 188 },
\\ .box = .{ 116, 173, 232 },
\\ .box_dim = .{ 70, 75, 87 },
\\ .kw = .{ 180, 119, 207 },
\\ .str = .{ 161, 193, 129 },
\\ .num = .{ 191, 149, 106 },
\\ .comment = .{ 93, 99, 111 },
\\ .lineno = .{ 78, 90, 95 },
\\ .scroll_track = .{ 54, 60, 70 },
\\ .scroll_thumb = .{ 200, 204, 212 },
\\ .palette = .{
\\ .{ 40, 44, 52 }, .{ 224, 108, 117 }, .{ 152, 195, 121 }, .{ 229, 192, 123 },
\\ .{ 97, 175, 239 }, .{ 198, 120, 221 }, .{ 86, 182, 194 }, .{ 171, 178, 191 },
\\ .{ 99, 109, 131 }, .{ 234, 133, 139 }, .{ 170, 213, 129 }, .{ 255, 216, 133 },
\\ .{ 133, 193, 255 }, .{ 211, 152, 235 }, .{ 110, 213, 222 }, .{ 250, 250, 250 },
\\ },
\\}
\\
;
requestThemeFile(p, 0, "themes/one_dark_zed_mod.zon");
try std.testing.expect(loadThemeFile(p, p.theme_file_generation, own));
const want = p.chrome().*;
// The file in its old names, unset fields their defaults.
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
var diagnostics: std.zon.parse.Diagnostics = undefined;
const old = try std.zon.parse.fromSlice(LegacyTheme, .{ .gpa = gpa, .arena = arena.allocator(), .source = own, .diagnostics = &diagnostics });
try std.testing.expectEqual([3]u8{ 70, 75, 87 }, old.box_dim);
try std.testing.expectEqual(@as(?[3]u8, null), old.tag_active_bg);
try std.testing.expectEqual(Chrome.of(&.fromLegacy(old)), want);
// An older DumpThemes' shape: every old field, the unset ones null.
var older: std.Io.Writer.Allocating = .init(gpa);
defer older.deinit();
try std.zon.stringify.serialize(old, .{ .whitespace = true }, &older.writer);
try std.testing.expect(std.mem.indexOf(u8, older.written(), ".tag_active_bg = null") != null);
// DumpThemes' now: the new names.
var now: std.Io.Writer.Allocating = .init(gpa);
defer now.deinit();
try std.zon.stringify.serialize(Theme.fromLegacy(old), .{ .whitespace = true }, &now.writer);
try std.testing.expect(std.mem.indexOf(u8, now.written(), ".tag_bg") == null and std.mem.indexOf(u8, now.written(), ".page = ") != null);
for ([2][]const u8{ older.written(), now.written() }) |file| {
requestThemeFile(p, 0, "themes/again.zon");
try std.testing.expect(loadThemeFile(p, p.theme_file_generation, file));
try std.testing.expectEqualStrings("one_dark_zed", p.theme().name);
try std.testing.expectEqual(want, p.chrome().*);
// The theme worn is the file's, in the new names.
for ([_][3]u8{ p.theme().tag, p.theme().accent, p.theme().selection, p.theme().keyword }, [_][3]u8{ old.tag_bg, old.box, old.sel_bg, old.kw }) |got, was|
try std.testing.expectEqual(was, got);
}
// A file in the new names with a typo is refused in the new names' words.
requestThemeFile(p, 0, "themes/bad.zon");
try std.testing.expect(!loadThemeFile(p, p.theme_file_generation, ".{ .name = \"x\", .page = null, .txet = null }"));
try std.testing.expectEqualStrings("one_dark_zed", p.theme().name);
}
test "a retired theme's name stands for its successor in an init file and a dump, said once; an unknown one leaves the default, in today's words (DESIGN.md E)" {
const gpa = std.testing.allocator;
const Said = struct {
fn count(p: *const Pardes, needle: []const u8) usize {
var n: usize = 0;
for (p.messages.log[0..p.messages.len]) |m| {
if (std.mem.indexOf(u8, m.text[0..m.len], needle) != null) n += 1;
}
return n;
}
};
for ([_][3][]const u8{
.{ "gruvbox_dark_zed", "gruvbox", "Theme gruvbox_dark_zed was retired: gruvbox instead" },
.{ "TTOX", "dark", "Theme TTOX was retired: dark instead" },
// a retired one with no kept twin: the default
.{ "ingrid", "orchard", "Theme ingrid was retired: orchard instead" },
.{ "no-such-theme", "orchard", "Theme: no theme \"no-such-theme\"; like it: " },
}) |case| {
const line = try std.fmt.allocPrint(gpa, "Theme {s}\n", .{case[0]});
defer gpa.free(line);
const p = try Pardes.init(gpa, .{ .tty_only = true, .startup_config = line });
defer p.deinit();
try std.testing.expectEqualStrings(case[1], p.theme().name);
try std.testing.expectEqual(1, Said.count(p, case[2]));
}
// A dump naming one (this build writes none: a dump of an older one,
// its theme's name put in): its successor.
const source = try Pardes.init(gpa, .{ .tty_only = true, .startup_config = "Theme acme\n" });
defer source.deinit();
try @import("dump.zig").dumpState(source);
const bytes = try gpa.dupe(u8, source.dump_out.?);
defer gpa.free(bytes);
const at = std.mem.indexOf(u8, bytes, "acme").?;
try std.testing.expect(std.mem.indexOfPos(u8, bytes, at + 4, "acme") == null);
@memcpy(bytes[at..][0..4], "ttox");
const restored = try @import("dump.zig").initFromDump(gpa, .{ .tty_only = true }, bytes);
defer restored.deinit();
try std.testing.expectEqualStrings("dark", restored.theme().name);
}
test "every retired theme's successor is in the ring, and no retired name is" {
for (retired) |r| {
try std.testing.expectEqual(null, themeIndex(r[0]));
if (r[1]) |kept| try std.testing.expect(themeIndex(kept) != null);
}
try std.testing.expectEqual(44, retired.len);
}
|