oxicode-snapcompact 0.73.0

Bitmap-frame context compression for vision-capable LLMs — Rust port of omp snapcompact
Documentation
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
//! Snapcompact frame rendering.
//!
//! Rasterizes pre-normalized conversation text onto a `size`-wide bitmap
//! (height hugs the rows the text actually needs) using one of the bundled
//! public-domain pixel fonts, then encodes it as PNG:
//!
//! - `5x8`  — X.org BDF font (legacy shape).
//! - `8x8`  — unscii-8 hex font (Latin-1 subset), the square cell that won the
//!   snapcompact `SQuAD` evals.
//! - `6x12` / `8x13` — X.org misc BDF fonts (higher-density eval winners).
//! - `silver` — bundled TrueType font for CJK and other non-Latin text.
//!
//! Shape controls, all eval-validated in `packages/snapcompact`:
//!
//! - **variant** — `sent` cycles glyph ink through six hues at sentence
//!   boundaries; `bw` prints plain black ink (best for Anthropic readers).
//! - **lineRepeat** — prints every text line N times; copies after the first
//!   sit on a pale highlight band. Redundancy coding: two looks per glyph at
//!   half the density ("8x8r" shapes).
//! - **cellWidth/cellHeight** — target cell size. When it differs from the
//!   font's natural cell, glyphs are rasterized at native size and the canvas
//!   is Lanczos3-resampled to the target (anisotropic stretch, e.g. the
//!   OpenAI-optimal "6x6u" shape), producing an anti-aliased RGB frame.
//! - **stretch** — `false` disables resampling: glyphs print at natural size on
//!   the requested cell box while staying indexed (e.g. 8x13 glyphs on an 8x16
//!   pitch, the "8on16" shapes). `true`/unset keeps the auto rule above.
//! - **columns** — `2` flows pre-wrapped `\n`-separated lines down two
//!   newspaper columns (the "doc" shapes); word wrap and pagination happen in
//!   the TypeScript caller.
//! - **dim spans** — `U+000E`/`U+000F` in the text toggle dim gray ink on/off
//!   without occupying a cell; the TypeScript serializer wraps tool output in
//!   them so archived conversation reads louder than archived tool noise.
//! - **line breaks** — `U+2588` (FULL BLOCK) fills its entire cell with pitch
//!   black ink regardless of variant or dim state; the TypeScript normalizer
//!   folds newline runs to it so line structure survives whitespace collapse at
//!   a one-cell cost.
//!
//! Text normalization, frame chunking, provider shape selection, and archive
//! management live in `packages/snapcompact/src/snapcompact.ts`; this module
//! is only the hot `text -> PNG bytes` path.

use std::{
    borrow::Cow,
    collections::{HashMap, HashSet},
    f32::consts::PI,
    sync::LazyLock,
};

use fontdue::{Font as TtfFace, FontSettings, Metrics};

/// Renderer error type.
#[derive(Debug, thiserror::Error)]
pub enum SnapcompactError {
    /// Invalid options or unsupported font/variant.
    #[error("{0}")]
    Render(String),
    /// PNG encoding failed.
    #[error("png encode: {0}")]
    PngEncode(String),
}

impl From<std::io::Error> for SnapcompactError {
    fn from(e: std::io::Error) -> Self {
        SnapcompactError::PngEncode(e.to_string())
    }
}

impl From<std::fmt::Error> for SnapcompactError {
    fn from(e: std::fmt::Error) -> Self {
        SnapcompactError::PngEncode(e.to_string())
    }
}

/// Upper bound on the frame edge: a hard stop against absurd allocations
/// (`size * size` pixel buffer), far above the 2576px production frame.
const MAX_FRAME_SIZE: u32 = 16384;

/// Indexed palette: 0 is the white background, 1-6 are the six dark sentence
/// hues from the eval renderer (HLS l=0.22 s=0.95, h ∈ {0, .08, .3, .5, .62,
/// .78}), 7 is plain black ink (`bw` variant), 8 is the pale highlight band
/// behind repeated line copies, 9 is the dim gray ink for tool-output spans.
const PALETTE: [[u8; 3]; 10] = [
    [255, 255, 255],
    [109, 2, 2],     // red
    [109, 53, 2],    // amber
    [24, 109, 2],    // green
    [2, 109, 109],   // teal
    [2, 32, 109],    // blue
    [75, 2, 109],    // violet
    [0, 0, 0],       // bw ink
    [255, 247, 194], // repeat highlight band
    [128, 128, 128], // dim ink (tool-output spans)
];
const INK_COLORS: usize = 6;
const INK_BLACK: u8 = 7;
const BG_REPEAT: u8 = 8;
const INK_DIM: u8 = 9;
/// Zero-width ink toggles embedded in the text stream (shift-out/shift-in).
const DIM_ON: u32 = 0x0e;
const DIM_OFF: u32 = 0x0f;
/// FULL BLOCK: fills its entire cell box with pitch-black ink (`INK_BLACK`,
/// ignoring sentence hue and dim state). The TypeScript normalizer folds
/// newline runs to it.
const FULL_BLOCK: u32 = 0x2588;

static FONT_5X8: LazyLock<Font> = LazyLock::new(|| parse_bdf(include_str!("fonts/5x8.bdf"), 5, 8));
static FONT_8X8: LazyLock<Font> = LazyLock::new(|| parse_hex(include_str!("fonts/unscii-8.hex")));
static FONT_6X12: LazyLock<Font> =
    LazyLock::new(|| parse_bdf(include_str!("fonts/6x12.bdf"), 6, 12));
static FONT_8X13: LazyLock<Font> =
    LazyLock::new(|| parse_bdf(include_str!("fonts/8x13.bdf"), 8, 13));
static FONT_SILVER: LazyLock<TtfFont> =
    LazyLock::new(|| parse_ttf(include_bytes!("fonts/Silver.ttf"), 16.0, 16, 16));

struct Glyph {
    /// Glyph width in pixels (≤ 8 for the bundled fonts).
    w: u8,
    /// Glyph height in pixels.
    h: i32,
    xoff: i32,
    yoff: i32,
    /// One bitmask per bitmap row, MSB-leftmost.
    rows: Vec<u8>,
}

struct Font {
    /// Glyphs keyed by Unicode code point (ASCII + Latin-1 coverage).
    glyphs: HashMap<u32, Glyph>,
    ascent: i32,
    /// Natural cell advance (x) in pixels.
    cell_w: usize,
    /// Natural cell pitch (y) in pixels.
    cell_h: usize,
}

struct TtfFont {
    face: TtfFace,
    supported: HashSet<char>,
    px: f32,
    ascent: f32,
    cell_w: usize,
    cell_h: usize,
}

struct RasterizedGlyph {
    metrics: Metrics,
    bitmap: Vec<u8>,
}

fn parse_bdf(text: &str, cell_w: usize, cell_h: usize) -> Font {
    let mut glyphs = HashMap::new();
    let mut ascent = 0i32;
    let mut enc = -1i64;
    let mut bbx = [0i32; 4];
    let mut lines = text.lines();
    while let Some(line) = lines.next() {
        if let Some(rest) = line.strip_prefix("FONT_ASCENT") {
            ascent = rest.trim().parse().unwrap_or(0);
        } else if let Some(rest) = line.strip_prefix("ENCODING") {
            enc = rest.trim().parse().unwrap_or(-1);
        } else if let Some(rest) = line.strip_prefix("BBX") {
            let mut parts = rest.split_ascii_whitespace();
            for slot in &mut bbx {
                *slot = parts.next().and_then(|part| part.parse().ok()).unwrap_or(0);
            }
        } else if line.starts_with("BITMAP") {
            let mut rows = Vec::new();
            for row in lines.by_ref() {
                if row.starts_with("ENDCHAR") {
                    break;
                }
                rows.push(u8::from_str_radix(row.trim(), 16).unwrap_or(0));
            }
            if enc >= 0 {
                glyphs.insert(
                    enc as u32,
                    Glyph {
                        w: bbx[0].clamp(0, 8) as u8,
                        h: bbx[1],
                        xoff: bbx[2],
                        yoff: bbx[3],
                        rows,
                    },
                );
            }
        }
    }
    Font {
        glyphs,
        ascent,
        cell_w,
        cell_h,
    }
}

/// Parse a unifont-style `.hex` font (`CODEPOINT:16-hex-digit bitmap`, one
/// byte per row of an 8x8 glyph). Baseline sits at row 7 (`ascent` 7 with a
/// one-pixel descender row), matching the eval renderer.
fn parse_hex(text: &str) -> Font {
    let mut glyphs = HashMap::new();
    for line in text.lines() {
        let Some((cp, bits)) = line.split_once(':') else {
            continue;
        };
        let Ok(enc) = u32::from_str_radix(cp.trim(), 16) else {
            continue;
        };
        let bits = bits.trim();
        if bits.len() != 16 {
            continue;
        }
        let rows: Vec<u8> = (0..8)
            .map(|i| u8::from_str_radix(&bits[i * 2..i * 2 + 2], 16).unwrap_or(0))
            .collect();
        glyphs.insert(
            enc,
            Glyph {
                w: 8,
                h: 8,
                xoff: 0,
                yoff: -1,
                rows,
            },
        );
    }
    Font {
        glyphs,
        ascent: 7,
        cell_w: 8,
        cell_h: 8,
    }
}

fn parse_ttf(data: &'static [u8], px: f32, cell_w: usize, cell_h: usize) -> TtfFont {
    let face =
        TtfFace::from_bytes(data, FontSettings::default()).expect("bundled Silver.ttf must parse");
    let supported = face.chars().keys().copied().collect();
    let ascent = face
        .horizontal_line_metrics(px)
        .map_or(px * 0.8, |metrics| metrics.ascent);
    TtfFont {
        face,
        supported,
        px,
        ascent,
        cell_w,
        cell_h,
    }
}

enum RenderFont<'a> {
    Bitmap(&'a Font),
    Ttf(&'a TtfFont),
}

impl RenderFont<'_> {
    const fn cell_w(&self) -> usize {
        match self {
            Self::Bitmap(font) => font.cell_w,
            Self::Ttf(font) => font.cell_w,
        }
    }

    const fn cell_h(&self) -> usize {
        match self {
            Self::Bitmap(font) => font.cell_h,
            Self::Ttf(font) => font.cell_h,
        }
    }

    fn supports(&self, code: u32) -> bool {
        if matches!(code, DIM_ON | DIM_OFF | FULL_BLOCK | 0x0a) {
            return true;
        }
        match self {
            Self::Bitmap(font) => font.glyphs.contains_key(&code),
            Self::Ttf(font) => char::from_u32(code).is_some_and(|ch| font.supported.contains(&ch)),
        }
    }
}

fn resolve_font(name: &str) -> Option<RenderFont<'static>> {
    match name {
        "5x8" => Some(RenderFont::Bitmap(&FONT_5X8)),
        "8x8" => Some(RenderFont::Bitmap(&FONT_8X8)),
        "6x12" => Some(RenderFont::Bitmap(&FONT_6X12)),
        "8x13" => Some(RenderFont::Bitmap(&FONT_8X13)),
        "silver" => Some(RenderFont::Ttf(&FONT_SILVER)),
        _ => None,
    }
}

/// Frame grid geometry shared with the TypeScript caller. The cell box
/// (`cell_w` x `cell_h`) is the advance/pitch glyphs are laid out on; it may
/// differ from the font's natural cell (e.g. 8x13 glyphs on an 8x16 pitch).
struct Grid {
    cols: usize,
    rows: usize,
    repeat: usize,
    /// Cell advance (x) in pixels.
    cell_w: usize,
    /// Cell pitch (y) in pixels.
    cell_h: usize,
}

/// East Asian Wide / Fullwidth code points that occupy two grid cells when
/// drawn through the Silver fallback in a narrow bitmap shape. The same ranges
/// are mirrored in `packages/snapcompact/src/snapcompact.ts` so the TypeScript
/// capacity/pagination math and this layout never disagree on cell counts.
const fn is_wide(cp: u32) -> bool {
    matches!(cp,
        0x1100..=0x115F
        | 0x2E80..=0x2EFF
        | 0x2F00..=0x2FDF
        | 0x3000..=0x303E
        | 0x3041..=0x33FF
        | 0x3400..=0x4DBF
        | 0x4E00..=0x9FFF
        | 0xA000..=0xA4CF
        | 0xAC00..=0xD7A3
        | 0xF900..=0xFAFF
        | 0xFE30..=0xFE4F
        | 0xFF00..=0xFF60
        | 0xFFE0..=0xFFE6
        | 0x20000..=0x2FFFD
        | 0x30000..=0x3FFFD
    )
}

/// Cells one code point consumes in a grid of `wide_cells`-capable shape: zero
/// for the zero-width dim toggles, two for wide code points when the shape uses
/// a narrow bitmap cell (so CJK draws full-width through Silver), one
/// otherwise.
const fn cell_units(code: u32, wide_cells: bool) -> usize {
    match code {
        DIM_ON | DIM_OFF => 0,
        _ if wide_cells && is_wide(code) => 2,
        _ => 1,
    }
}

/// Advance the running cell cursor for one code point, inserting a one-cell pad
/// when a wide glyph would straddle the right edge so it starts the next row.
/// Returns `(cell_at_which_to_draw, units, next_cursor)`, or `None` for a
/// zero-width toggle.
const fn place_cell(
    cursor: usize,
    cols: usize,
    code: u32,
    wide_cells: bool,
) -> Option<(usize, usize, usize)> {
    let units = cell_units(code, wide_cells);
    if units == 0 {
        return None;
    }
    let mut cell = cursor;
    if units == 2 && cols >= 2 && cell % cols == cols - 1 {
        cell += 1; // pad: never split a wide glyph across two rows
    }
    Some((cell, units, cell + units))
}

/// Grid rows the text actually occupies, so the canvas height hugs the
/// content instead of padding the frame to a full square. Mirrors the
/// renderers' cell accounting: dim toggles are zero-width, wide code points
/// take two cells in bitmap shapes (with a straddle pad), every other code
/// point one; doc layout fills one row per `\n`-separated line.
fn used_rows(text: &str, grid: &Grid, doc: bool, wide_cells: bool) -> usize {
    let rows = if doc {
        text.split('\n').count()
    } else {
        let mut cursor = 0usize;
        for ch in text.chars() {
            if let Some((_, _, next)) = place_cell(cursor, grid.cols, ch as u32, wide_cells) {
                cursor = next;
            }
        }
        cursor.div_ceil(grid.cols)
    };
    rows.clamp(1, grid.rows)
}

/// Paint the pale highlight bands behind line copies after the first.
fn fill_repeat_bands(pixels: &mut [u8], width: usize, height: usize, grid: &Grid) {
    if grid.repeat <= 1 {
        return;
    }
    for row in 0..grid.rows {
        for copy in 1..grid.repeat {
            let band_top = (row * grid.repeat + copy) * grid.cell_h;
            for y in band_top..(band_top + grid.cell_h).min(height) {
                pixels[y * width..y * width + width].fill(BG_REPEAT);
            }
        }
    }
}

/// Blit one glyph's bitmask rows at (`left`, `top`), clipped to the canvas.
fn blit_glyph(
    pixels: &mut [u8],
    width: usize,
    height: usize,
    glyph: &Glyph,
    left: i32,
    top: i32,
    ink: u8,
) {
    for (r, &bits) in glyph.rows.iter().enumerate() {
        if bits == 0 {
            continue;
        }
        let y = top + r as i32;
        if y < 0 || y >= height as i32 {
            continue;
        }
        let row_base = y as usize * width;
        for b in 0..glyph.w {
            if bits & (0x80u8 >> b) != 0 {
                let x = left + i32::from(b);
                if x >= 0 && (x as usize) < width {
                    pixels[row_base + x as usize] = ink;
                }
            }
        }
    }
}

/// Fill one cell box (every repeat copy) with solid ink, clipped to canvas.
fn fill_cell(
    pixels: &mut [u8],
    width: usize,
    height: usize,
    grid: &Grid,
    x_origin: usize,
    row: usize,
    ink: u8,
) {
    let x0 = x_origin.min(width);
    let x1 = (x_origin + grid.cell_w).min(width);
    if x0 >= x1 {
        return;
    }
    for copy in 0..grid.repeat {
        let top = (row * grid.repeat + copy) * grid.cell_h;
        for y in top..(top + grid.cell_h).min(height) {
            pixels[y * width + x0..y * width + x1].fill(ink);
        }
    }
}

fn fill_repeat_bands_rgb(pixels: &mut [u8], width: usize, height: usize, grid: &Grid) {
    if grid.repeat <= 1 {
        return;
    }
    let band = PALETTE[BG_REPEAT as usize];
    for row in 0..grid.rows {
        for copy in 1..grid.repeat {
            let band_top = (row * grid.repeat + copy) * grid.cell_h;
            for y in band_top..(band_top + grid.cell_h).min(height) {
                for px in pixels[y * width * 3..(y + 1) * width * 3].chunks_exact_mut(3) {
                    px.copy_from_slice(&band);
                }
            }
        }
    }
}

fn fill_cell_rgb(
    pixels: &mut [u8],
    width: usize,
    height: usize,
    grid: &Grid,
    x_origin: usize,
    row: usize,
    ink: u8,
) {
    let x0 = x_origin.min(width);
    let x1 = (x_origin + grid.cell_w).min(width);
    if x0 >= x1 {
        return;
    }
    let color = PALETTE[ink as usize];
    for copy in 0..grid.repeat {
        let top = (row * grid.repeat + copy) * grid.cell_h;
        for y in top..(top + grid.cell_h).min(height) {
            let row = &mut pixels[y * width * 3..(y + 1) * width * 3];
            for x in x0..x1 {
                row[x * 3..x * 3 + 3].copy_from_slice(&color);
            }
        }
    }
}

fn ttf_pixel_size(font: &TtfFont, grid: &Grid) -> f32 {
    let sx = grid.cell_w as f32 / font.cell_w as f32;
    let sy = grid.cell_h as f32 / font.cell_h as f32;
    font.px * sx.min(sy)
}

/// Pixel size for a full-width fallback glyph spanning two grid cells: scaled
/// to the two-cell box so CJK fills the doubled width instead of a single
/// narrow ASCII cell.
fn ttf_wide_pixel_size(font: &TtfFont, grid: &Grid) -> f32 {
    let sx = (2 * grid.cell_w) as f32 / font.cell_w as f32;
    let sy = grid.cell_h as f32 / font.cell_h as f32;
    font.px * sx.min(sy)
}

fn ttf_ascent(font: &TtfFont, px: f32) -> f32 {
    font.face
        .horizontal_line_metrics(px)
        .map_or(font.ascent * px / font.px, |metrics| metrics.ascent)
}

fn cached_ttf_glyph<'a>(
    cache: &'a mut HashMap<char, RasterizedGlyph>,
    font: &TtfFont,
    ch: char,
    px: f32,
) -> Option<&'a RasterizedGlyph> {
    if !font.supported.contains(&ch) {
        return None;
    }
    Some(cache.entry(ch).or_insert_with(|| {
        let (metrics, bitmap) = font.face.rasterize(ch, px);
        RasterizedGlyph { metrics, bitmap }
    }))
}

fn blit_ttf_glyph(
    pixels: &mut [u8],
    width: usize,
    height: usize,
    glyph: &RasterizedGlyph,
    left: i32,
    top: i32,
    ink: u8,
) {
    if glyph.metrics.width == 0 || glyph.metrics.height == 0 {
        return;
    }
    let color = PALETTE[ink as usize];
    for y in 0..glyph.metrics.height {
        let dst_y = top + y as i32;
        if dst_y < 0 || dst_y >= height as i32 {
            continue;
        }
        for x in 0..glyph.metrics.width {
            let alpha = u16::from(glyph.bitmap[y * glyph.metrics.width + x]);
            if alpha == 0 {
                continue;
            }
            let dst_x = left + x as i32;
            if dst_x < 0 || dst_x >= width as i32 {
                continue;
            }
            let offset = (dst_y as usize * width + dst_x as usize) * 3;
            let inv = 255 - alpha;
            for c in 0..3 {
                let bg = u16::from(pixels[offset + c]);
                let fg = u16::from(color[c]);
                pixels[offset + c] = ((bg * inv + fg * alpha + 127) / 255) as u8;
            }
        }
    }
}

fn blit_ttf_glyph_indexed(
    pixels: &mut [u8],
    width: usize,
    height: usize,
    glyph: &RasterizedGlyph,
    left: i32,
    top: i32,
    ink: u8,
) {
    if glyph.metrics.width == 0 || glyph.metrics.height == 0 {
        return;
    }
    for y in 0..glyph.metrics.height {
        let dst_y = top + y as i32;
        if dst_y < 0 || dst_y >= height as i32 {
            continue;
        }
        let row_base = dst_y as usize * width;
        for x in 0..glyph.metrics.width {
            // Two-level anti-alias for the on/off indexed palette: a solid core
            // only where coverage is high, and a single dim-gray fringe on the
            // partially covered edges, so scaled CJK reads lighter than a
            // flat-thresholded (and visibly bold) glyph. Dim spans stay dim.
            let coverage = glyph.bitmap[y * glyph.metrics.width + x];
            let cell = if coverage >= 170 {
                ink
            } else if ink == INK_BLACK && coverage >= 56 {
                INK_DIM // soft gray fringe only on black ink (one neutral palette slot)
            } else if coverage >= 110 {
                ink
            } else {
                continue;
            };
            let dst_x = left + x as i32;
            if dst_x >= 0 && dst_x < width as i32 {
                pixels[row_base + dst_x as usize] = cell;
            }
        }
    }
}

fn ttf_glyph_origin(x_origin: usize, cell_w: usize, metrics: &Metrics) -> i32 {
    let advance = metrics.advance_width.ceil() as i32;
    let pad = (cell_w as i32 - advance).max(0) / 2;
    x_origin as i32 + pad + metrics.xmin
}

fn ttf_glyph_top(cell_top: usize, ascent: f32, metrics: &Metrics) -> i32 {
    (cell_top as f32 + ascent - metrics.height as f32 - metrics.ymin as f32).round() as i32
}

/// Rasterize `text` onto a `width` x `height` palette-indexed bitmap on the
/// grid's cell box, row-major with no word wrap. Glyphs keep their natural
/// size with the baseline at the font's ascent from the cell top, so a cell
/// taller than the font pads below the baseline (the "8on16" shapes). Each
/// text line is printed `grid.repeat` times; copies after the first sit on
/// the highlight band. Ink cycles through six hues at sentence boundaries
/// (terminator in `.!?` followed by a space or full block) unless `black_ink`
/// pins it to black; `U+000E`/`U+000F` toggle dim gray ink without occupying a
/// cell, and dim wins over both variants. `U+2588` fills its whole cell with
/// pitch-black ink, ignoring hue and dim state. Characters beyond
/// `cols * rows` are ignored; code points missing from the bitmap font draw
/// through the embedded Silver TrueType fallback when it has a glyph.
fn render_bitmap(
    text: &str,
    width: usize,
    height: usize,
    font: &Font,
    grid: &Grid,
    black_ink: bool,
) -> Vec<u8> {
    let mut pixels = vec![0u8; width * height]; // 0 = white background
    let capacity = grid.cols * grid.rows;
    if capacity == 0 {
        return pixels;
    }
    fill_repeat_bands(&mut pixels, width, height, grid);
    let codes: Vec<u32> = text.chars().map(|ch| ch as u32).collect();
    let narrow_px = ttf_pixel_size(&FONT_SILVER, grid);
    let wide_px = ttf_wide_pixel_size(&FONT_SILVER, grid);
    let mut fallback_cache = HashMap::new();
    let mut sentence = 0usize;
    let mut dim = false;
    let mut cursor = 0usize;
    for i in 0..codes.len() {
        if cursor >= capacity {
            break;
        }
        let code = codes[i];
        match code {
            DIM_ON => {
                dim = true;
                continue;
            }
            DIM_OFF => {
                dim = false;
                continue;
            }
            _ => {}
        }
        let ink = if dim {
            INK_DIM
        } else if black_ink {
            INK_BLACK
        } else {
            (1 + sentence % INK_COLORS) as u8
        };
        if matches!(code, 0x2e | 0x21 | 0x3f)
            && matches!(codes.get(i + 1), Some(&(0x20 | FULL_BLOCK)))
        {
            sentence += 1;
        }
        let Some((at, units, next)) = place_cell(cursor, grid.cols, code, true) else {
            continue;
        };
        cursor = next;
        if at >= capacity {
            break;
        }
        let row = at / grid.cols;
        let col = at - row * grid.cols;
        if code == FULL_BLOCK {
            fill_cell(
                &mut pixels,
                width,
                height,
                grid,
                col * grid.cell_w,
                row,
                INK_BLACK,
            );
            continue;
        }
        if let Some(glyph) = font.glyphs.get(&code) {
            if glyph.rows.is_empty() {
                continue;
            }
            let left = (col * grid.cell_w) as i32 + glyph.xoff;
            for copy in 0..grid.repeat {
                let cell_top = ((row * grid.repeat + copy) * grid.cell_h) as i32;
                let top = cell_top + font.ascent - glyph.h - glyph.yoff;
                blit_glyph(&mut pixels, width, height, glyph, left, top, ink);
            }
        } else if let Some(ch) = char::from_u32(code) {
            let px = if units == 2 { wide_px } else { narrow_px };
            let Some(glyph) = cached_ttf_glyph(&mut fallback_cache, &FONT_SILVER, ch, px) else {
                continue;
            };
            let span = units * grid.cell_w;
            let left = ttf_glyph_origin(col * grid.cell_w, span, &glyph.metrics);
            for copy in 0..grid.repeat {
                let cell_top = (row * grid.repeat + copy) * grid.cell_h;
                let top = ttf_glyph_top(cell_top, font.ascent as f32, &glyph.metrics);
                blit_ttf_glyph_indexed(&mut pixels, width, height, glyph, left, top, ink);
            }
        }
    }
    pixels
}

fn render_ttf_rgb(
    text: &str,
    width: usize,
    height: usize,
    font: &TtfFont,
    grid: &Grid,
    black_ink: bool,
) -> Vec<u8> {
    let mut pixels = vec![255u8; width * height * 3];
    let capacity = grid.cols * grid.rows;
    if capacity == 0 {
        return pixels;
    }
    fill_repeat_bands_rgb(&mut pixels, width, height, grid);
    let px = ttf_pixel_size(font, grid);
    let ascent = ttf_ascent(font, px);
    let codes: Vec<char> = text.chars().collect();
    let mut cache = HashMap::new();
    let mut sentence = 0usize;
    let mut dim = false;
    let mut cell = 0usize;
    for i in 0..codes.len() {
        if cell >= capacity {
            break;
        }
        let ch = codes[i];
        let code = ch as u32;
        match code {
            DIM_ON => {
                dim = true;
                continue;
            }
            DIM_OFF => {
                dim = false;
                continue;
            }
            _ => {}
        }
        let ink = if dim {
            INK_DIM
        } else if black_ink {
            INK_BLACK
        } else {
            (1 + sentence % INK_COLORS) as u8
        };
        if matches!(code, 0x2e | 0x21 | 0x3f)
            && matches!(
                codes.get(i + 1).map(|next| *next as u32),
                Some(0x20 | FULL_BLOCK)
            )
        {
            sentence += 1;
        }
        let row = cell / grid.cols;
        let col = cell - row * grid.cols;
        cell += 1;
        if code == FULL_BLOCK {
            fill_cell_rgb(
                &mut pixels,
                width,
                height,
                grid,
                col * grid.cell_w,
                row,
                INK_BLACK,
            );
            continue;
        }
        let Some(glyph) = cached_ttf_glyph(&mut cache, font, ch, px) else {
            continue;
        };
        let left = ttf_glyph_origin(col * grid.cell_w, grid.cell_w, &glyph.metrics);
        for copy in 0..grid.repeat {
            let cell_top = (row * grid.repeat + copy) * grid.cell_h;
            let top = ttf_glyph_top(cell_top, ascent, &glyph.metrics);
            blit_ttf_glyph(&mut pixels, width, height, glyph, left, top, ink);
        }
    }
    pixels
}

/// Character cells between the two doc columns (eval `exp14` layout).
const GUTTER: usize = 3;

/// Rasterize pre-wrapped text as a two-column "doc" page onto a `width` x
/// `height` palette-indexed bitmap. Input splits on `'\n'` (zero-width): line
/// `li` lands at column `li / rows`, row `li % rows`; each column is
/// `(cols - GUTTER) / 2` cells wide, the second starts `col_w + GUTTER` cells
/// in, and no rule is drawn between them. Lines longer than the column width
/// are clipped (the TypeScript caller pre-wraps; clipping is the overflow
/// guard) and lines past the second column are ignored. Sentence hues advance
/// on a terminator in `.!?` followed by a space, newline, *or* full block;
/// dim toggles, repeat bands, and the `U+2588` black cell fill behave exactly
/// as in the grid renderer.
fn render_doc_bitmap(
    text: &str,
    width: usize,
    height: usize,
    font: &Font,
    grid: &Grid,
    black_ink: bool,
) -> Vec<u8> {
    let mut pixels = vec![0u8; width * height]; // 0 = white background
    let col_w = grid.cols.saturating_sub(GUTTER) / 2;
    if col_w == 0 || grid.rows == 0 {
        return pixels;
    }
    fill_repeat_bands(&mut pixels, width, height, grid);
    let codes: Vec<u32> = text.chars().map(|ch| ch as u32).collect();
    let narrow_px = ttf_pixel_size(&FONT_SILVER, grid);
    let wide_px = ttf_wide_pixel_size(&FONT_SILVER, grid);
    let mut fallback_cache = HashMap::new();
    let mut sentence = 0usize;
    let mut dim = false;
    let mut line = 0usize;
    let mut col = 0usize;
    for i in 0..codes.len() {
        let code = codes[i];
        match code {
            DIM_ON => {
                dim = true;
                continue;
            }
            DIM_OFF => {
                dim = false;
                continue;
            }
            0x0a => {
                line += 1;
                col = 0;
                if line >= grid.rows * 2 {
                    break; // past the second column; the caller paginates
                }
                continue;
            }
            _ => {}
        }
        let ink = if dim {
            INK_DIM
        } else if black_ink {
            INK_BLACK
        } else {
            (1 + sentence % INK_COLORS) as u8
        };
        if matches!(code, 0x2e | 0x21 | 0x3f)
            && matches!(codes.get(i + 1), Some(&(0x20 | 0x0a | FULL_BLOCK)))
        {
            sentence += 1;
        }
        let units = cell_units(code, true);
        let mut cell = col;
        if units == 2 && col_w >= 2 && cell == col_w - 1 {
            cell += 1; // pad: never split a wide glyph across the column edge
        }
        col = cell + units;
        if cell + units > col_w {
            continue; // clip past the column width
        }
        let column = line / grid.rows;
        let row = line - column * grid.rows;
        let x_origin = column * (col_w + GUTTER) * grid.cell_w;
        if code == FULL_BLOCK {
            fill_cell(
                &mut pixels,
                width,
                height,
                grid,
                x_origin + cell * grid.cell_w,
                row,
                INK_BLACK,
            );
            continue;
        }
        if let Some(glyph) = font.glyphs.get(&code) {
            if glyph.rows.is_empty() {
                continue;
            }
            let left = (x_origin + cell * grid.cell_w) as i32 + glyph.xoff;
            for copy in 0..grid.repeat {
                let cell_top = ((row * grid.repeat + copy) * grid.cell_h) as i32;
                let top = cell_top + font.ascent - glyph.h - glyph.yoff;
                blit_glyph(&mut pixels, width, height, glyph, left, top, ink);
            }
        } else if let Some(ch) = char::from_u32(code) {
            let px = if units == 2 { wide_px } else { narrow_px };
            let Some(glyph) = cached_ttf_glyph(&mut fallback_cache, &FONT_SILVER, ch, px) else {
                continue;
            };
            let span = units * grid.cell_w;
            let left = ttf_glyph_origin(x_origin + cell * grid.cell_w, span, &glyph.metrics);
            for copy in 0..grid.repeat {
                let cell_top = (row * grid.repeat + copy) * grid.cell_h;
                let top = ttf_glyph_top(cell_top, font.ascent as f32, &glyph.metrics);
                blit_ttf_glyph_indexed(&mut pixels, width, height, glyph, left, top, ink);
            }
        }
    }
    pixels
}

fn render_ttf_doc_rgb(
    text: &str,
    width: usize,
    height: usize,
    font: &TtfFont,
    grid: &Grid,
    black_ink: bool,
) -> Vec<u8> {
    let mut pixels = vec![255u8; width * height * 3];
    let col_w = grid.cols.saturating_sub(GUTTER) / 2;
    if col_w == 0 || grid.rows == 0 {
        return pixels;
    }
    fill_repeat_bands_rgb(&mut pixels, width, height, grid);
    let px = ttf_pixel_size(font, grid);
    let ascent = ttf_ascent(font, px);
    let codes: Vec<char> = text.chars().collect();
    let mut cache = HashMap::new();
    let mut sentence = 0usize;
    let mut dim = false;
    let mut line = 0usize;
    let mut col = 0usize;
    for i in 0..codes.len() {
        let ch = codes[i];
        let code = ch as u32;
        match code {
            DIM_ON => {
                dim = true;
                continue;
            }
            DIM_OFF => {
                dim = false;
                continue;
            }
            0x0a => {
                line += 1;
                col = 0;
                if line >= grid.rows * 2 {
                    break;
                }
                continue;
            }
            _ => {}
        }
        let ink = if dim {
            INK_DIM
        } else if black_ink {
            INK_BLACK
        } else {
            (1 + sentence % INK_COLORS) as u8
        };
        if matches!(code, 0x2e | 0x21 | 0x3f)
            && matches!(
                codes.get(i + 1).map(|next| *next as u32),
                Some(0x20 | 0x0a | FULL_BLOCK)
            )
        {
            sentence += 1;
        }
        let cell = col;
        col += 1;
        if cell >= col_w {
            continue;
        }
        let column = line / grid.rows;
        let row = line - column * grid.rows;
        let x_origin = (column * (col_w + GUTTER) + cell) * grid.cell_w;
        if code == FULL_BLOCK {
            fill_cell_rgb(&mut pixels, width, height, grid, x_origin, row, INK_BLACK);
            continue;
        }
        let Some(glyph) = cached_ttf_glyph(&mut cache, font, ch, px) else {
            continue;
        };
        let left = ttf_glyph_origin(x_origin, grid.cell_w, &glyph.metrics);
        for copy in 0..grid.repeat {
            let cell_top = (row * grid.repeat + copy) * grid.cell_h;
            let top = ttf_glyph_top(cell_top, ascent, &glyph.metrics);
            blit_ttf_glyph(&mut pixels, width, height, glyph, left, top, ink);
        }
    }
    pixels
}

// ============================================================================
// Lanczos3 resampling (stretch shapes)
// ============================================================================

fn lanczos3(x: f32) -> f32 {
    let x = x.abs();
    if x < 1e-6 {
        return 1.0;
    }
    if x >= 3.0 {
        return 0.0;
    }
    let pix = PI * x;
    (pix.sin() / pix) * ((pix / 3.0).sin() / (pix / 3.0))
}

/// Per-output-pixel kernel contributions for one axis, PIL-convention
/// (`center = (i + 0.5) * scale`, kernel stretched by `max(scale, 1)`,
/// weights normalized).
fn contributions(src_len: usize, dst_len: usize) -> Vec<(usize, Vec<f32>)> {
    let scale = src_len as f32 / dst_len as f32;
    let filt_scale = scale.max(1.0);
    let support = 3.0 * filt_scale;
    let mut out = Vec::with_capacity(dst_len);
    for i in 0..dst_len {
        let center = (i as f32 + 0.5) * scale;
        let begin = ((center - support) as isize).max(0) as usize;
        let end = ((center + support).ceil() as usize).min(src_len);
        let mut weights = Vec::with_capacity(end - begin);
        let mut total = 0.0f32;
        for x in begin..end {
            let w = lanczos3((x as f32 + 0.5 - center) / filt_scale);
            weights.push(w);
            total += w;
        }
        if total != 0.0 {
            for w in &mut weights {
                *w /= total;
            }
        }
        out.push((begin, weights));
    }
    out
}

/// Separable Lanczos3 resize of an interleaved RGB f32 buffer.
fn resize_rgb(src: &[f32], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<f32> {
    let horiz = contributions(sw, dw);
    let mut tmp = vec![0f32; dw * sh * 3];
    for y in 0..sh {
        let src_row = &src[y * sw * 3..(y + 1) * sw * 3];
        let dst_row = &mut tmp[y * dw * 3..(y + 1) * dw * 3];
        for (x, (begin, weights)) in horiz.iter().enumerate() {
            let mut acc = [0f32; 3];
            for (k, &w) in weights.iter().enumerate() {
                let s = (begin + k) * 3;
                acc[0] = src_row[s].mul_add(w, acc[0]);
                acc[1] = src_row[s + 1].mul_add(w, acc[1]);
                acc[2] = src_row[s + 2].mul_add(w, acc[2]);
            }
            dst_row[x * 3..x * 3 + 3].copy_from_slice(&acc);
        }
    }
    let vert = contributions(sh, dh);
    let mut out = vec![0f32; dw * dh * 3];
    for (y, (begin, weights)) in vert.iter().enumerate() {
        let dst_row = &mut out[y * dw * 3..(y + 1) * dw * 3];
        for (k, &w) in weights.iter().enumerate() {
            let src_row = &tmp[(begin + k) * dw * 3..(begin + k + 1) * dw * 3];
            for (d, &s) in dst_row.iter_mut().zip(src_row) {
                *d = s.mul_add(w, *d);
            }
        }
    }
    out
}

// ============================================================================
// PNG encoding
// ============================================================================

/// Pack one-byte-per-pixel palette indices into `bits`-per-pixel PNG
/// scanline data (big-endian within each byte), remapping each global
/// palette index through `remap` to its per-frame slot on the way.
fn pack_bits(
    pixels: &[u8],
    width: usize,
    height: usize,
    bits: usize,
    remap: &[u8; PALETTE.len()],
) -> Vec<u8> {
    let per = 8 / bits;
    let row_bytes = width.div_ceil(per);
    let mut packed = vec![0u8; row_bytes * height];
    for y in 0..height {
        let src = &pixels[y * width..(y + 1) * width];
        let dst = &mut packed[y * row_bytes..(y + 1) * row_bytes];
        for (x, &px) in src.iter().enumerate() {
            dst[x / per] |= remap[px as usize] << (bits * (per - 1 - x % per));
        }
    }
    packed
}

/// Encode a palette-indexed bitmap as an indexed PNG with `None` row
/// filtering (the glyph bitmap is already minimal-entropy; filtering costs
/// encode time without helping deflate).
///
/// The palette is narrowed to the colors the frame actually uses and the bit
/// depth follows: a plain `bw` frame (background + ink) packs 1-bit rows, a
/// dim/banded frame 2-bit, sentence-hue frames 4-bit — bw frames shed
/// another ~half of the pre-deflate stream vs the fixed 4-bit layout.
fn encode_indexed_png(
    pixels: &[u8],
    width: usize,
    height: usize,
    compression: png::Compression,
) -> Result<Vec<u8>, SnapcompactError> {
    let mut used = [false; PALETTE.len()];
    for &px in pixels {
        used[px as usize] = true;
    }
    let mut remap = [0u8; PALETTE.len()];
    let mut palette = Vec::with_capacity(PALETTE.len() * 3);
    let mut count = 0u8;
    for (global, &is_used) in used.iter().enumerate() {
        if is_used {
            remap[global] = count;
            count += 1;
            palette.extend_from_slice(&PALETTE[global]);
        }
    }
    let (depth, bits) = match count {
        0..=2 => (png::BitDepth::One, 1),
        3..=4 => (png::BitDepth::Two, 2),
        _ => (png::BitDepth::Four, 4),
    };
    let mut out = Vec::new();
    let mut encoder = png::Encoder::new(&mut out, width as u32, height as u32);
    encoder.set_color(png::ColorType::Indexed);
    encoder.set_depth(depth);
    encoder.set_palette(Cow::Owned(palette));
    encoder.set_compression(compression);
    // MUST come after `set_compression`, which resets the filter to the
    // compression level's default (`Adaptive` for `Balanced`/`High`).
    encoder.set_filter(png::FilterType::NoFilter);
    let mut writer = encoder
        .write_header()
        .map_err(|err| SnapcompactError::Render(format!("Failed to write PNG header: {err}")))?;
    writer
        .write_image_data(&pack_bits(pixels, width, height, bits, &remap))
        .map_err(|err| SnapcompactError::Render(format!("Failed to write PNG data: {err}")))?;
    writer
        .finish()
        .map_err(|err| SnapcompactError::Render(format!("Failed to finish PNG stream: {err}")))?;
    Ok(out)
}

/// Encode an interleaved RGB8 buffer as PNG. Stretched frames are
/// continuous-tone, so adaptive filtering (the `Balanced` default) helps.
fn encode_rgb_png(
    pixels: &[u8],
    width: usize,
    height: usize,
    compression: png::Compression,
) -> Result<Vec<u8>, SnapcompactError> {
    let mut out = Vec::new();
    let mut encoder = png::Encoder::new(&mut out, width as u32, height as u32);
    encoder.set_color(png::ColorType::Rgb);
    encoder.set_depth(png::BitDepth::Eight);
    encoder.set_compression(compression);
    let mut writer = encoder
        .write_header()
        .map_err(|err| SnapcompactError::Render(format!("Failed to write PNG header: {err}")))?;
    writer
        .write_image_data(pixels)
        .map_err(|err| SnapcompactError::Render(format!("Failed to write PNG data: {err}")))?;
    writer
        .finish()
        .map_err(|err| SnapcompactError::Render(format!("Failed to finish PNG stream: {err}")))?;
    Ok(out)
}

// ============================================================================
// Entry point
// ============================================================================

/// Shape options for one snapcompact frame.

#[derive(Default, Clone)]
pub struct SnapcompactRenderOptions {
    /// Frame width in pixels; also bounds the grid rows
    /// (`floor(size/cellHeight/lineRepeat)`). Output height hugs the rows the
    /// text actually uses instead of padding to a square.
    pub size: u32,
    /// Bundled font: `"5x8"`, `"6x12"`, `"8x13"` (X.org BDF), `"8x8"`
    /// (unscii-8), or `"silver"` (embedded TrueType). Default `"5x8"`.
    pub font: Option<String>,
    /// Target cell advance in pixels. Differing from the font's natural cell
    /// triggers the Lanczos stretch path. Default: font natural width.
    pub cell_width: Option<u32>,
    /// Target cell pitch in pixels. Default: font natural height.
    pub cell_height: Option<u32>,
    /// Ink variant: `"sent"` (six-hue sentence cycling) or `"bw"` (black).
    /// Default `"sent"`.
    pub variant: Option<String>,
    /// Print each text line this many times; copies after the first sit on a
    /// pale highlight band. Default 1.
    pub line_repeat: Option<u32>,
    /// Stretch behavior. Unset: auto — Lanczos-stretch whenever the target
    /// cell differs from the font's natural cell. `false`: never stretch —
    /// render indexed with glyphs at natural size on the requested cell box
    /// (e.g. 8x13 glyphs on an 8x16 pitch, the "8on16" shapes). `true`: force
    /// the stretch path (identical to auto; natural cells render indexed).
    pub stretch: Option<bool>,
    /// Layout columns: `1` (default) row-major grid; `2` two newspaper "doc"
    /// columns of pre-wrapped newline-separated lines.
    pub columns: Option<u32>,
}

/// Return the subset of `chars` that the named snapcompact font can render.
///
/// The TypeScript normalizer uses this to keep Unicode text intact only when
/// considered renderable because they are interpreted outside font lookup.
pub fn snapcompact_supported_chars(
    font: String,
    chars: String,
) -> Result<String, SnapcompactError> {
    let font = resolve_font(&font).ok_or_else(|| {
        SnapcompactError::Render(format!(
            "Unknown snapcompact font {font:?}: expected \"5x8\", \"8x8\", \"6x12\", \"8x13\", or \
			 \"silver\""
        ))
    })?;
    let mut supported = String::new();
    for ch in chars.chars() {
        if matches!(ch as u32, DIM_ON | DIM_OFF | FULL_BLOCK | 0x0a) || font.supports(ch as u32) {
            supported.push(ch);
        }
    }
    Ok(supported)
}

/// Render one snapcompact frame on a libuv worker: print pre-normalized text
/// onto a `size`-wide bitmap and encode it as PNG.
///
/// The bitmap height hugs the rows the text actually occupies
/// (`usedRows * lineRepeat * cellHeight`), so a partially filled frame never
/// pays for blank padding rows. The glyph grid holds `floor(size/cellWidth) *
/// floor(size/cellHeight/lineRepeat)` characters; input beyond that is ignored.
/// Native-cell bitmap-font shapes encode as indexed PNG; stretched bitmap-font
/// shapes (target cell != font cell) encode as RGB. TrueType shapes encode RGB
/// directly from grayscale coverage.
/// `stretch: false` pins bitmap fonts to the indexed path, printing
/// natural-size glyphs on the requested cell box; `columns: 2` flows
/// pre-wrapped newline-separated lines down two newspaper columns.
/// `U+000E`/`U+000F` in `text` toggle dim-gray ink spans without occupying a
/// cell.
/// Returns a promise for the PNG encoded as base64, created as a one-byte
/// (Latin-1) JS string straight from native code — no `Uint8Array` hop or
pub fn render_snapcompact_png(
    text: String,
    options: SnapcompactRenderOptions,
) -> Result<Vec<u8>, SnapcompactError> {
    render_snapcompact_png_sync(text, options)
}

fn render_snapcompact_png_sync(
    text: String,
    options: SnapcompactRenderOptions,
) -> Result<Vec<u8>, SnapcompactError> {
    let size = options.size;
    if size == 0 || size > MAX_FRAME_SIZE {
        return Err(SnapcompactError::Render(format!(
            "Invalid frame size {size}: expected 1..={MAX_FRAME_SIZE}"
        )));
    }
    let font_name = options.font.as_deref().unwrap_or("5x8");
    let font = resolve_font(font_name).ok_or_else(|| {
		SnapcompactError::Render(format!(
			"Unknown snapcompact font {font_name:?}: expected \"5x8\", \"8x8\", \"6x12\", \"8x13\", \
			 or \"silver\""
		))
	})?;
    let black_ink = match options.variant.as_deref().unwrap_or("sent") {
        "sent" => false,
        "bw" => true,
        other => {
            return Err(SnapcompactError::Render(format!(
                "Unknown snapcompact variant {other:?}: expected \"sent\" or \"bw\""
            )));
        }
    };
    let natural_w = font.cell_w();
    let natural_h = font.cell_h();
    let target_w = options.cell_width.unwrap_or(natural_w as u32).max(1) as usize;
    let target_h = options.cell_height.unwrap_or(natural_h as u32).max(1) as usize;
    let repeat = options.line_repeat.unwrap_or(1).max(1) as usize;
    let columns = options.columns.unwrap_or(1);
    if !matches!(columns, 1 | 2) {
        return Err(SnapcompactError::Render(format!(
            "Invalid snapcompact columns {columns}: expected 1 or 2"
        )));
    }
    let doc = columns == 2;
    let size = size as usize;
    let grid = Grid {
        cols: size / target_w,
        rows: size / target_h / repeat,
        repeat,
        cell_w: target_w,
        cell_h: target_h,
    };
    if grid.cols == 0 || grid.rows == 0 {
        return Err(SnapcompactError::Render(format!(
            "Frame size {size} cannot fit a {target_w}x{target_h} cell grid (repeat {repeat})"
        )));
    }
    // Tight canvas: width stays the frame edge (the reading geometry the
    // caller derives cols from), height hugs the rows the text needs. Bitmap
    // shapes draw wide code points through Silver across two cells, so they
    // count double here; the square-celled Silver shape keeps one cell each.
    let wide_cells = matches!(font, RenderFont::Bitmap(_));
    let used = used_rows(&text, &grid, doc, wide_cells);
    let height = used * grid.repeat * grid.cell_h;

    match font {
        RenderFont::Ttf(font) => {
            let pixels = if doc {
                render_ttf_doc_rgb(&text, size, height, font, &grid, black_ink)
            } else {
                render_ttf_rgb(&text, size, height, font, &grid, black_ink)
            };
            Ok(encode_rgb_png(
                &pixels,
                size,
                height,
                png::Compression::Best,
            )?)
        }
        RenderFont::Bitmap(font) => {
            let stretch =
                options.stretch != Some(false) && (target_w, target_h) != (natural_w, natural_h);
            if !stretch {
                // Indexed path: rasterize straight onto the frame at the requested
                // cell box (the natural cell, or natural glyphs on a padded pitch
                // when `stretch: false`).
                let pixels = if doc {
                    render_doc_bitmap(&text, size, height, font, &grid, black_ink)
                } else {
                    render_bitmap(&text, size, height, font, &grid, black_ink)
                };
                return encode_indexed_png(&pixels, size, height, png::Compression::Best);
            }

            // Stretch shape: rasterize at the font's natural cell on a tight canvas
            // (layout stays in character cells from the target grid), Lanczos3-
            // resample to the target cell, paste onto the white frame.
            let native = Grid {
                cell_w: natural_w,
                cell_h: natural_h,
                ..grid
            };
            let src_w = grid.cols * natural_w;
            let src_h = used * grid.repeat * natural_h;
            let dst_w = grid.cols * target_w;
            let dst_h = used * grid.repeat * target_h;
            let indexed = if doc {
                render_doc_bitmap(&text, src_w, src_h, font, &native, black_ink)
            } else {
                render_bitmap(&text, src_w, src_h, font, &native, black_ink)
            };
            let mut rgb = vec![0f32; src_w * src_h * 3];
            for (dst, &idx) in rgb.chunks_exact_mut(3).zip(&indexed) {
                let [r, g, b] = PALETTE[idx as usize];
                dst[0] = f32::from(r);
                dst[1] = f32::from(g);
                dst[2] = f32::from(b);
            }
            let resized = resize_rgb(&rgb, src_w, src_h, dst_w, dst_h);
            let mut frame = vec![255u8; size * dst_h * 3];
            for y in 0..dst_h {
                let src_row = &resized[y * dst_w * 3..(y + 1) * dst_w * 3];
                let dst_row = &mut frame[y * size * 3..];
                for (d, &s) in dst_row[..dst_w.min(size) * 3].iter_mut().zip(src_row) {
                    *d = s.round().clamp(0.0, 255.0) as u8;
                }
            }
            Ok(encode_rgb_png(&frame, size, dst_h, png::Compression::Best)?)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn opts(size: u32) -> SnapcompactRenderOptions {
        SnapcompactRenderOptions {
            size,
            ..Default::default()
        }
    }

    #[test]
    fn fonts_parse_ascii_coverage() {
        for (font, ascent) in [(&*FONT_5X8, 7), (&*FONT_8X8, 7)] {
            assert_eq!(font.ascent, ascent);
            // Every printable ASCII char must have a glyph.
            for cp in 0x20u32..0x7f {
                assert!(
                    font.glyphs.contains_key(&cp),
                    "missing glyph for U+{cp:04X}"
                );
            }
        }
    }

    #[test]
    fn silver_font_covers_cjk_scripts() {
        assert!(
            FONT_SILVER.supported.contains(&''),
            "Silver must cover Japanese kana"
        );
        assert!(
            FONT_SILVER.supported.contains(&''),
            "Silver must cover Han text"
        );
        assert!(
            FONT_SILVER.supported.contains(&''),
            "Silver must cover Hangul syllables"
        );
    }

    #[test]
    fn bitmap_inks_sentences_and_caps_capacity() {
        // 40px -> 8 cols x 5 rows = 40 cells (5x8 font).
        let grid = Grid {
            cols: 8,
            rows: 5,
            repeat: 1,
            cell_w: 5,
            cell_h: 8,
        };
        let pixels = render_bitmap("Hi. Ok.", 40, 40, &FONT_5X8, &grid, false);
        let inks: Vec<u8> = pixels.iter().copied().filter(|&p| p != 0).collect();
        assert!(inks.contains(&1), "first sentence should use ink 1");
        assert!(inks.contains(&2), "second sentence should use ink 2");
        assert!(!inks.contains(&3), "no third sentence ink expected");

        // Overflow input renders without panicking and stays in-bounds.
        let overflow = render_bitmap(&"x".repeat(100), 40, 40, &FONT_5X8, &grid, false);
        assert_eq!(overflow.len(), 40 * 40);
    }

    #[test]
    fn bw_variant_prints_black_only() {
        let grid = Grid {
            cols: 8,
            rows: 8,
            repeat: 1,
            cell_w: 8,
            cell_h: 8,
        };
        let pixels = render_bitmap("Hi. Ok.", 64, 64, &FONT_8X8, &grid, true);
        let inks: Vec<u8> = pixels.iter().copied().filter(|&p| p != 0).collect();
        assert!(!inks.is_empty());
        assert!(
            inks.iter().all(|&p| p == INK_BLACK),
            "bw must ink only black"
        );
    }

    #[test]
    fn dim_markers_toggle_gray_without_consuming_cells() {
        let grid = Grid {
            cols: 8,
            rows: 8,
            repeat: 1,
            cell_w: 8,
            cell_h: 8,
        };
        let pixels = render_bitmap("\u{e}AB\u{f}CD", 64, 64, &FONT_8X8, &grid, true);
        let inks: Vec<u8> = pixels.iter().copied().filter(|&p| p != 0).collect();
        assert!(inks.contains(&INK_DIM), "dim span must ink gray");
        assert!(
            inks.contains(&INK_BLACK),
            "post-span text must return to black"
        );
        // Markers are zero-width: glyphs land in the same cells as without them.
        let plain = render_bitmap("ABCD", 64, 64, &FONT_8X8, &grid, true);
        for (i, (a, b)) in pixels.iter().zip(&plain).enumerate() {
            assert_eq!(
                *a != 0,
                *b != 0,
                "cell layout must ignore markers (pixel {i})"
            );
        }
    }

    #[test]
    fn line_repeat_duplicates_rows_on_highlight_bands() {
        // 64px, 8x8 font, repeat 2 -> 8 cols x 4 unique rows.
        let grid = Grid {
            cols: 8,
            rows: 4,
            repeat: 2,
            cell_w: 8,
            cell_h: 8,
        };
        let pixels = render_bitmap("ABCDEFGH", 64, 64, &FONT_8X8, &grid, true);
        // Copy band (rows 8..16) carries the highlight background.
        assert!(
            pixels[9 * 64..10 * 64].contains(&BG_REPEAT),
            "duplicate band must be highlighted"
        );
        // Identical glyph ink in both copies: compare full 8-row bands modulo
        // background.
        for y in 0..8 {
            for x in 0..64 {
                let a = pixels[y * 64 + x];
                let b = pixels[(y + 8) * 64 + x];
                assert_eq!(
                    a == INK_BLACK,
                    b == INK_BLACK,
                    "copy ink mismatch at ({x},{y})"
                );
            }
        }
    }

    #[test]
    fn full_block_fills_cell_pitch_black() {
        let grid = Grid {
            cols: 8,
            rows: 4,
            repeat: 2,
            cell_w: 8,
            cell_h: 8,
        };
        // The block's black fill beats both the dim span and the sent hues.
        let pixels = render_bitmap("\u{e}a\u{2588}b\u{f}", 64, 64, &FONT_8X8, &grid, false);
        for copy in 0..2 {
            for y in copy * 8..(copy + 1) * 8 {
                for x in 8..16 {
                    assert_eq!(
                        pixels[y * 64 + x],
                        INK_BLACK,
                        "block pixel ({x},{y}) must be black"
                    );
                }
            }
        }
        assert!(pixels.contains(&INK_DIM), "neighbours keep their dim ink");
        let hued = render_bitmap("Hi.\u{2588}Ok.", 64, 64, &FONT_8X8, &grid, false);
        assert!(
            hued.contains(&2),
            "block must advance the sentence hue like a space"
        );
    }

    #[test]
    fn doc_full_block_fills_cell() {
        // col_w = (13 - GUTTER) / 2 = 5; block at line 0, cell 1 -> x 8..16.
        let grid = Grid {
            cols: 13,
            rows: 2,
            repeat: 1,
            cell_w: 8,
            cell_h: 8,
        };
        let pixels = render_doc_bitmap("a\u{2588}b\nc", 104, 16, &FONT_8X8, &grid, true);
        for y in 0..8 {
            for x in 8..16 {
                assert_eq!(
                    pixels[y * 104 + x],
                    INK_BLACK,
                    "block pixel ({x},{y}) must be black"
                );
            }
        }
    }

    /// Test helper: PNG bytes come back directly (no base64 hop).
    fn png_bytes(encoded: Vec<u8>) -> Vec<u8> {
        encoded
    }

    #[test]
    fn render_native_is_indexed_and_stretch_is_rgb() {
        let native = png_bytes(
            render_snapcompact_png_sync(
                "Hello world. Again.".into(),
                SnapcompactRenderOptions {
                    size: 128,
                    font: Some("8x8".into()),
                    variant: Some("bw".into()),
                    line_repeat: Some(2),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        // PNG color type lives at byte 25 of the IHDR: 3 = indexed.
        assert_eq!(native[25], 3);

        let stretched = png_bytes(
            render_snapcompact_png_sync(
                "Hello world. Again.".into(),
                SnapcompactRenderOptions {
                    size: 128,
                    font: Some("8x8".into()),
                    cell_width: Some(6),
                    cell_height: Some(6),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        // 2 = truecolor RGB.
        assert_eq!(stretched[25], 2);
        let legacy = png_bytes(render_snapcompact_png_sync("Hi. Ok.".into(), opts(40)).unwrap());
        assert_eq!(
            legacy[25], 3,
            "default shape stays the legacy 5x8 indexed path"
        );

        let silver = png_bytes(
            render_snapcompact_png_sync(
                "こんにちは 你好 안녕".into(),
                SnapcompactRenderOptions {
                    size: 128,
                    font: Some("silver".into()),
                    cell_width: Some(16),
                    cell_height: Some(16),
                    variant: Some("bw".into()),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        assert_eq!(silver[25], 2, "TrueType frames render as RGB");
    }

    #[test]
    fn indexed_png_narrows_palette_and_bit_depth() {
        // IHDR bit depth lives at byte 24; PLTE length is the chunk length
        // word 8 bytes after the "PLTE" tag position.
        fn depth_and_palette(png: &[u8]) -> (u8, usize) {
            let tag = png
                .windows(4)
                .position(|w| w == b"PLTE")
                .expect("PLTE chunk");
            let len = u32::from_be_bytes(png[tag - 4..tag].try_into().unwrap()) as usize;
            (png[24], len / 3)
        }

        // Plain bw, no dim/band/repeat: background + black ink = 1-bit.
        let bw = png_bytes(
            render_snapcompact_png_sync(
                "Hello world. Again.".into(),
                SnapcompactRenderOptions {
                    size: 128,
                    font: Some("8x8".into()),
                    variant: Some("bw".into()),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        assert_eq!(depth_and_palette(&bw), (1, 2));

        // bw with a dim span and repeat bands: 4 colors = 2-bit.
        let dim = png_bytes(
            render_snapcompact_png_sync(
                "Read \u{e}the dim part\u{f} now.".into(),
                SnapcompactRenderOptions {
                    size: 128,
                    font: Some("8x8".into()),
                    variant: Some("bw".into()),
                    line_repeat: Some(2),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        assert_eq!(depth_and_palette(&dim), (2, 4));

        // Sentence hues exceed 4 colors: stays 4-bit, palette still narrowed
        // to the inks actually printed (bg + 2 hues here).
        let sent = png_bytes(
            render_snapcompact_png_sync(
                "Hi. Ok.".into(),
                SnapcompactRenderOptions {
                    size: 128,
                    font: Some("8x8".into()),
                    variant: Some("sent".into()),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        let (sent_depth, sent_colors) = depth_and_palette(&sent);
        assert_eq!(sent_depth, 2, "two hues + bg fit 2-bit");
        assert_eq!(sent_colors, 3);
    }

    #[test]
    fn rejects_bad_shapes() {
        assert!(render_snapcompact_png_sync("x".into(), opts(0)).is_err());
        assert!(
            render_snapcompact_png_sync(
                "x".into(),
                SnapcompactRenderOptions {
                    size: 64,
                    font: Some("9x9".into()),
                    ..Default::default()
                }
            )
            .is_err()
        );
        assert!(
            render_snapcompact_png_sync(
                "x".into(),
                SnapcompactRenderOptions {
                    size: 64,
                    variant: Some("zebra".into()),
                    ..Default::default()
                }
            )
            .is_err()
        );
    }

    #[test]
    fn xorg_fonts_parse_and_render() {
        for (font, ascent, name) in [(&*FONT_6X12, 10, "6x12"), (&*FONT_8X13, 11, "8x13")] {
            assert_eq!(font.ascent, ascent, "{name} ascent");
            for cp in 0x20u32..0x7f {
                assert!(
                    font.glyphs.contains_key(&cp),
                    "{name} missing glyph U+{cp:04X}"
                );
            }
        }
        for (name, size) in [("6x12", 60u32), ("8x13", 104u32)] {
            let png = png_bytes(
                render_snapcompact_png_sync(
                    "Hello world. Again!".into(),
                    SnapcompactRenderOptions {
                        size,
                        font: Some(name.into()),
                        ..Default::default()
                    },
                )
                .unwrap(),
            );
            assert_eq!(png[25], 3, "{name} natural cell must encode indexed");
        }
        // Non-blank: the raster must carry glyph ink.
        let grid = Grid {
            cols: 10,
            rows: 5,
            repeat: 1,
            cell_w: 6,
            cell_h: 12,
        };
        let pixels = render_bitmap("Hello", 60, 60, &FONT_6X12, &grid, true);
        assert!(pixels.contains(&INK_BLACK), "6x12 must ink pixels");
        let grid = Grid {
            cols: 8,
            rows: 8,
            repeat: 1,
            cell_w: 8,
            cell_h: 13,
        };
        let pixels = render_bitmap("Hello", 64, 104, &FONT_8X13, &grid, true);
        assert!(pixels.contains(&INK_BLACK), "8x13 must ink pixels");
    }

    #[test]
    fn stretch_false_renders_natural_glyphs_on_padded_pitch() {
        let png = png_bytes(
            render_snapcompact_png_sync(
                "Hello there. General Kenobi!".into(),
                SnapcompactRenderOptions {
                    size: 128,
                    font: Some("8x13".into()),
                    cell_width: Some(8),
                    cell_height: Some(16),
                    stretch: Some(false),
                    variant: Some("bw".into()),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        assert_eq!(png[25], 3, "8on16 must stay indexed");
        // IHDR width/height live at bytes 16..24, big-endian.
        let dim = |off: usize| u32::from_be_bytes(png[off..off + 4].try_into().unwrap());
        // "Hello there. General Kenobi!" is 28 chars on a 16-col grid: 2 rows
        // of the 16px pitch — the height hugs them instead of padding to 128.
        assert_eq!(
            (dim(16), dim(20)),
            (128, 32),
            "declared geometry must match"
        );

        // Glyph ink must sit in the top 13px of every 16px pitch row.
        let grid = Grid {
            cols: 16,
            rows: 8,
            repeat: 1,
            cell_w: 8,
            cell_h: 16,
        };
        let pixels = render_bitmap(
            "Hgjpqy. Mixed descenders!",
            128,
            128,
            &FONT_8X13,
            &grid,
            true,
        );
        assert!(pixels.contains(&INK_BLACK));
        for (i, &p) in pixels.iter().enumerate() {
            if p == INK_BLACK {
                assert!(
                    (i / 128) % 16 < 13,
                    "ink leaked into pitch padding at y={}",
                    i / 128
                );
            }
        }
    }

    #[test]
    fn doc_layout_flows_lines_into_second_column() {
        // 64px, 8x16 cells -> cols 8, rows 4, col_w = (8 - 3) / 2 = 2.
        let grid = Grid {
            cols: 8,
            rows: 4,
            repeat: 1,
            cell_w: 8,
            cell_h: 16,
        };
        let pixels = render_doc_bitmap("A\nB\nC\nD\nE", 64, 64, &FONT_8X13, &grid, true);
        // Line 4 (the rows+1-th) lands at the second column's x origin:
        // 1 * (col_w + GUTTER) * cell_w = 40, row band 0.
        let col2 = (0..13).any(|y| (40..48).any(|x| pixels[y * 64 + x] == INK_BLACK));
        assert!(
            col2,
            "fifth line must start at the second column's x origin"
        );
        // '\n' consumes no cell: line 1 starts back at x 0 in row band 1.
        let row1 = (16..29).any(|y| (0..8).any(|x| pixels[y * 64 + x] == INK_BLACK));
        assert!(
            row1,
            "second line must start at column 0 of the next row band"
        );
        // One-char lines leave the rest of column 0 and the gutter blank.
        for y in 0..64 {
            for x in 8..40 {
                assert_eq!(pixels[y * 64 + x], 0, "gutter must stay blank at ({x},{y})");
            }
        }
    }

    #[test]
    fn doc_sentence_hue_advances_across_newline_boundary() {
        // 152px wide: cols 19, col_w = (19 - 3) / 2 = 8.
        let grid = Grid {
            cols: 19,
            rows: 4,
            repeat: 1,
            cell_w: 8,
            cell_h: 16,
        };
        let pixels = render_doc_bitmap("Hi.\nOk", 152, 64, &FONT_8X13, &grid, false);
        let inks: Vec<u8> = pixels.iter().copied().filter(|&p| p != 0).collect();
        assert!(inks.contains(&1), "first sentence must use ink 1");
        assert!(
            inks.contains(&2),
            "hue must advance across the newline boundary"
        );
        assert!(!inks.contains(&3), "no third sentence ink expected");

        // Grid mode keeps the space-only rule: no advance across '\n'.
        let gridmode = render_bitmap("Hi.\nOk", 152, 64, &FONT_8X13, &grid, false);
        let inks: Vec<u8> = gridmode.iter().copied().filter(|&p| p != 0).collect();
        assert!(inks.contains(&1));
        assert!(
            !inks.contains(&2),
            "grid mode must not advance hue across newline"
        );
    }

    #[test]
    fn frame_height_hugs_used_rows() {
        let dims = |png: &[u8]| {
            let dim = |off: usize| u32::from_be_bytes(png[off..off + 4].try_into().unwrap());
            (dim(16), dim(20))
        };
        let render = |text: &str, opts: SnapcompactRenderOptions| {
            png_bytes(render_snapcompact_png_sync(text.into(), opts).unwrap())
        };
        let opts_8x8 = || SnapcompactRenderOptions {
            size: 64,
            font: Some("8x8".into()),
            ..Default::default()
        };
        // 8 cols of 8x8 cells: 10 chars span 2 rows -> 16px tall.
        assert_eq!(dims(&render("0123456789", opts_8x8())), (64, 16));
        // Dim toggles are zero-width and must not add a row.
        assert_eq!(dims(&render("\u{e}01234567\u{f}", opts_8x8())), (64, 8));
        // Capacity-filling text keeps the full grid height.
        assert_eq!(dims(&render(&"x".repeat(64), opts_8x8())), (64, 64));
        // Repeat shapes hug `usedRows * repeat` copy bands.
        let repeated = render(
            "0123456789",
            SnapcompactRenderOptions {
                line_repeat: Some(2),
                ..opts_8x8()
            },
        );
        assert_eq!(dims(&repeated), (64, 32));
        // Doc layout counts `\n` lines down the first column.
        let doc = render(
            "Hello there.\nSecond line",
            SnapcompactRenderOptions {
                size: 256,
                font: Some("8x13".into()),
                cell_width: Some(8),
                cell_height: Some(16),
                stretch: Some(false),
                columns: Some(2),
                ..Default::default()
            },
        );
        assert_eq!(dims(&doc), (256, 32));
        // The stretch path hugs too (RGB output, 6x6 target cells).
        let stretched = render(
            "0123456789ab",
            SnapcompactRenderOptions {
                size: 60,
                font: Some("8x8".into()),
                cell_width: Some(6),
                cell_height: Some(6),
                ..Default::default()
            },
        );
        assert_eq!(dims(&stretched), (60, 12));
    }

    #[test]
    fn columns_validates_and_renders_doc_frames() {
        assert!(
            render_snapcompact_png_sync(
                "x".into(),
                SnapcompactRenderOptions {
                    size: 64,
                    columns: Some(3),
                    ..Default::default()
                }
            )
            .is_err()
        );
        // Indexed doc frame (stretch: false on a padded pitch).
        let doc = png_bytes(
            render_snapcompact_png_sync(
                "Hello there.\nSecond line".into(),
                SnapcompactRenderOptions {
                    size: 256,
                    font: Some("8x13".into()),
                    cell_width: Some(8),
                    cell_height: Some(16),
                    stretch: Some(false),
                    columns: Some(2),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        assert_eq!(doc[25], 3, "8on16 doc frame must encode indexed");
        // Doc layout also applies on the stretch path (RGB output).
        let stretched = png_bytes(
            render_snapcompact_png_sync(
                "Hello there.\nSecond line".into(),
                SnapcompactRenderOptions {
                    size: 256,
                    font: Some("8x13".into()),
                    cell_width: Some(6),
                    cell_height: Some(12),
                    columns: Some(2),
                    ..Default::default()
                },
            )
            .unwrap(),
        );
        assert_eq!(stretched[25], 2, "stretched doc frame must encode RGB");
    }
}