termshot 1.2.0

Terminal screenshot CLI and MCP server with ANSI rendering, redaction, themes, and composition
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
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
use crate::capture::{
    CapturedScreen, DEFAULT_MAX_SCROLLBACK_LINES, LineSelection, cell_has_content,
    effective_scrollback_lines,
};
use crate::config::{ChromeConfig, ThemeConfig};
use crate::redaction::{ManualRedactions, RedactionEngine, RedactionMap};
use crate::shaping::{FontSource, GlyphBitmap, RunCell, RunRequest, ShapingEngine, ShapingOptions};
use crate::unicode;
use anyhow::{Context, Result};
use chrono::Utc;
use fontdue::{Font, FontSettings};
use image::{ImageBuffer, Rgba, RgbaImage};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use unicode_script::UnicodeScript;

/// JetBrains Mono font compiled directly into the binary so that release
/// archives and `cargo install` builds always have a working font, even when
/// the `fonts/` directory is not shipped alongside the executable.
const EMBEDDED_FONT: &[u8] = include_bytes!("../fonts/JetBrainsMono-Regular.ttf");

/// Default background color drawn behind redacted cells (bright red, #d41919)
/// when a rule does not specify its own color. Kept in sync with
/// [`crate::redaction::DEFAULT_BLOCK_COLOR`]; used as a reference in tests.
#[cfg(test)]
const REDACT_BG: Rgba<u8> = Rgba([212, 25, 25, 255]);

/// Supersampling factor: the whole image (terminal + chrome) is rendered at
/// this multiple of the base cell/chrome metrics for crisp, retina-quality
/// output. Both `render_screen` and `compose_with_chrome` must use the same
/// factor so terminal content and chrome stay proportional.
const RENDER_SCALE: u32 = 2;

/// Narrowest image, in terminal cells, that width trimming will produce, so an
/// empty capture still renders as a small padded tile instead of a zero-width
/// PNG. Any real content is trimmed to its exact bound.
const MIN_CONTENT_COLS: u32 = 1;

/// Shortest image, in terminal cells, that height trimming will produce, so an
/// empty capture still renders as a small padded tile instead of a zero-height
/// PNG. Any real content is trimmed to its exact bound.
const MIN_CONTENT_ROWS: u32 = 1;

/// Fraction of the terminal font size the chrome timestamp watermark is drawn
/// at. Shared by the layout reserve and the draw call so the strip below the
/// terminal is measured with the size the text is actually rendered at.
const TIMESTAMP_FONT_SCALE: f32 = 0.65;

/// Breathing room, in unscaled pixels, above and below the timestamp watermark.
/// The reserve below the terminal is one line of timestamp text plus this gap
/// on each side - enough that the text is never clipped and never crowds the
/// last row of output, and nothing like the full blank terminal row that used
/// to sit there.
const TIMESTAMP_GAP: u32 = 4;

/// Largest image, in pixels, that will be rendered.
///
/// A capture of a command that printed tens of thousands of lines would
/// otherwise ask the allocator for gigabytes. 64 megapixels is one 256 MB RGBA
/// buffer, and at a standard 120-column terminal it is still several hundred
/// lines of output - far more than fits on any screen. Past it the error points
/// at `--head-lines` / `--tail-lines`.
const MAX_IMAGE_PIXELS: u64 = 64_000_000;

/// Peak bytes of image buffer a single render may hold at once.
///
/// The pixel ceiling alone does not bound memory: composing window chrome holds
/// the framed window and the shadowed canvas at the same time, so the peak is a
/// multiple of the final image. This budget is checked against *all* the
/// full-size buffers a render will hold simultaneously, so a shadowed window is
/// held to roughly half the bare ceiling instead of quietly costing twice as
/// much.
const MAX_RENDER_BYTES: u64 = 320 * 1024 * 1024;

/// Bytes per pixel in the RGBA buffers the renderer allocates.
const BYTES_PER_PIXEL: u64 = 4;

/// Metadata describing how a screenshot was rendered, so it can later be
/// re-rendered (e.g. by the `redact_screenshot` MCP tool) with identical
/// geometry and styling. The MCP server keeps this in memory (alongside the
/// raw terminal bytes) for the lifetime of the process; it is not written to
/// disk.
///
/// This is the shape published in 1.0.0 and it stays that way: it is a public
/// struct with public fields that external code builds with exhaustive
/// literals, so a new field here would be a source-breaking change. Anything
/// the renderer has learned to record since travels in [`RenderContext`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RenderMeta {
    pub cols: u16,
    pub rows: u16,
    pub theme: Option<String>,
    pub chrome: Option<ChromeOptions>,
    /// Whether the image width was auto-cropped to fit the content. Persisted
    /// so a later re-render (e.g. `redact_screenshot`) reproduces the same
    /// geometry. Defaults to true for metadata written before this field
    /// existed.
    #[serde(default = "default_auto_crop")]
    pub auto_crop: bool,
    /// Whether the returned text was taken from the parsed screen rather than
    /// the source bytes (see [`TextOptions::from_screen`]). Kept so a later
    /// re-render returns text of the same kind as the original capture.
    #[serde(default)]
    pub from_screen: bool,
}

impl Default for RenderMeta {
    fn default() -> Self {
        Self {
            cols: 80,
            rows: 24,
            theme: None,
            chrome: None,
            auto_crop: default_auto_crop(),
            from_screen: false,
        }
    }
}

/// A [`RenderMeta`] plus everything the renderer learned about a capture after
/// 1.0.0 froze that struct's shape.
///
/// Returned by the option-taking APIs ([`Renderer::render_bytes_with_options`])
/// and kept by the MCP server's render cache, so a re-render reproduces not
/// only the original geometry and styling but the same lines of the same
/// capture - and so its cell coordinates mean the same thing.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct RenderContext {
    /// The 1.0.0 metadata, unchanged.
    #[serde(flatten)]
    pub meta: RenderMeta,
    /// Which of the retained lines the screenshot showed.
    #[serde(default)]
    pub lines: LineSelection,
    /// Whether more output scrolled off than the scrollback could hold while
    /// capturing, so the oldest lines were dropped before rendering.
    #[serde(default)]
    pub truncated: bool,
}

impl RenderContext {
    /// A context around metadata with no line selection, which is what a 1.0.0
    /// [`RenderMeta`] describes: the whole capture, nothing dropped.
    pub fn from_meta(meta: RenderMeta) -> Self {
        Self {
            meta,
            lines: LineSelection::All,
            truncated: false,
        }
    }
}

impl std::ops::Deref for RenderContext {
    type Target = RenderMeta;

    fn deref(&self) -> &RenderMeta {
        &self.meta
    }
}

fn default_auto_crop() -> bool {
    true
}

/// Result of rendering: output PNG path, plain text, per-rule redaction
/// audit counts (empty when no redaction was applied), and the render metadata
/// needed to later re-render (e.g. for `redact_screenshot`).
pub type RenderOutput = (PathBuf, String, Vec<(String, usize)>, RenderMeta);

/// [`RenderOutput`] with the extended [`RenderContext`] in place of the 1.0.0
/// [`RenderMeta`], as the option-taking render APIs return it.
pub type RenderOutputWithContext = (PathBuf, String, Vec<(String, usize)>, RenderContext);

/// How [`compose_images`] arranges multiple source screenshots on the canvas.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposeLayout {
    /// Place images left-to-right; canvas height is the tallest image, and
    /// shorter panes are padded (not stretched) to reach it.
    Horizontal,
    /// Stack images top-to-bottom; canvas width is the widest image, and
    /// narrower panes are padded (not stretched) to reach it.
    Vertical,
}

impl ComposeLayout {
    /// Parse a user-supplied layout name. Accepts a few friendly aliases.
    pub fn parse(s: &str) -> Result<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "horizontal" | "h" | "row" | "side-by-side" => Ok(Self::Horizontal),
            "vertical" | "v" | "column" | "stacked" => Ok(Self::Vertical),
            other => anyhow::bail!(
                "unknown compose layout '{}': use 'horizontal' or 'vertical'",
                other
            ),
        }
    }
}

/// macOS traffic-light geometry, in unscaled (1x) pixels: the radius of each
/// button, the center of the leftmost one measured from the frame's left edge,
/// and the distance between adjacent centers. All three buttons share the
/// radius, so they are always identical circles.
const TRAFFIC_LIGHT_RADIUS: u32 = 5;
const TRAFFIC_LIGHT_FIRST_CENTER: u32 = 18;
const TRAFFIC_LIGHT_PITCH: u32 = 16;

/// Muted divider color drawn between panes on a dark background. Chosen to
/// read like a tmux pane border (tmux's default `colour8` grey) so the seam is
/// clearly visible without competing with the terminal content.
const DIVIDER_COLOR_DARK: Rgba<u8> = Rgba([0x6e, 0x76, 0x80, 255]);
/// Muted divider color drawn between panes on a light background.
const DIVIDER_COLOR_LIGHT: Rgba<u8> = Rgba([0x9a, 0x9a, 0x9a, 255]);

/// Pick a muted divider color that reads well against `background`, using a
/// perceptual luminance threshold to decide dark vs. light.
fn divider_color_for(background: Rgba<u8>) -> Rgba<u8> {
    let [r, g, b, _] = background.0;
    let luminance = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
    if luminance < 128.0 {
        DIVIDER_COLOR_DARK
    } else {
        DIVIDER_COLOR_LIGHT
    }
}

/// Sample the background color of a rendered screenshot so a composite can fill
/// any exposed canvas with a color that matches the panes (never a black or
/// mismatched margin). Prefers a point just inside the top edge - which skips
/// any rounded/transparent corner - and falls back to `fallback` if no fully
/// opaque pixel is found.
fn sample_background(img: &RgbaImage, fallback: Rgba<u8>) -> Rgba<u8> {
    let (w, h) = img.dimensions();
    if w == 0 || h == 0 {
        return fallback;
    }
    let candidates = [
        (w / 2, 2.min(h - 1)),
        (4.min(w - 1), 4.min(h - 1)),
        (2.min(w - 1), h / 2),
        (0, 0),
    ];
    for (x, y) in candidates {
        let p = *img.get_pixel(x, y);
        if p[3] == 255 {
            return Rgba([p[0], p[1], p[2], 255]);
        }
    }
    fallback
}

/// Convert bare LF (`\n` not already preceded by CR) to CRLF so raw ANSI that
/// was not captured through a TTY - piped command output or a redirected log
/// fed to `render` - lands on proper lines instead of staircasing to the right.
///
/// The check is idempotent: input that already uses CRLF (e.g. PTY output from
/// `exec`) contains no bare LF and is returned borrowed without allocating.
fn normalize_newlines(data: &[u8]) -> std::borrow::Cow<'_, [u8]> {
    let has_bare_lf = data
        .iter()
        .enumerate()
        .any(|(i, &b)| b == b'\n' && (i == 0 || data[i - 1] != b'\r'));
    if !has_bare_lf {
        return std::borrow::Cow::Borrowed(data);
    }
    let mut out = Vec::with_capacity(data.len() + 16);
    let mut prev = 0u8;
    for &b in data {
        if b == b'\n' && prev != b'\r' {
            out.push(b'\r');
        }
        out.push(b);
        prev = b;
    }
    std::borrow::Cow::Owned(out)
}

///
/// `divider` is the divider thickness in pixels. For a horizontal layout the
/// panes are padded to a common height (the tallest source) and separated by a
/// vertical divider; for a vertical layout they are padded to a common width
/// (the widest source) and separated by a horizontal divider, so the seams line
/// up like real terminal splits. A pane is padded with its own background
/// color - never rescaled - so its glyphs keep the crisp 2x rendering and their
/// aspect ratio, exactly like a tmux pane that is smaller than its neighbour.
pub fn compose_images(
    paths: &[PathBuf],
    layout: ComposeLayout,
    divider: u32,
    background: Rgba<u8>,
) -> Result<RgbaImage> {
    if paths.len() < 2 {
        anyhow::bail!("compose requires at least two images (got {})", paths.len());
    }

    let mut sources: Vec<RgbaImage> = Vec::with_capacity(paths.len());
    for p in paths {
        let img = image::open(p)
            .with_context(|| format!("Failed to open image {:?}", p))?
            .to_rgba8();
        sources.push(img);
    }

    // Fill any exposed canvas (and choose the divider color) from the first
    // pane's own background, so the composite never shows a black or otherwise
    // mismatched margin. Falls back to the caller-supplied background.
    let canvas_bg = sample_background(&sources[0], background);

    // Pad every pane to a common cross-axis size so the panes align. Resizing
    // would resample the text, so a smaller pane is extended with its own
    // background instead and stays pixel-for-pixel as rendered.
    let (target_w, target_h) = match layout {
        ComposeLayout::Horizontal => (0, sources.iter().map(|i| i.height()).max().unwrap_or(1)),
        ComposeLayout::Vertical => (sources.iter().map(|i| i.width()).max().unwrap_or(1), 0),
    };
    let panes: Vec<RgbaImage> = sources
        .into_iter()
        .map(|img| {
            let w = target_w.max(img.width()).max(1);
            let h = target_h.max(img.height()).max(1);
            if (w, h) == img.dimensions() {
                return img;
            }
            let pane_bg = sample_background(&img, canvas_bg);
            let mut padded: RgbaImage = ImageBuffer::from_pixel(w, h, pane_bg);
            image::imageops::overlay(&mut padded, &img, 0, 0);
            padded
        })
        .collect();

    let total_divider = divider * (panes.len() as u32 - 1);
    let (width, height) = match layout {
        ComposeLayout::Horizontal => (
            panes.iter().map(|i| i.width()).sum::<u32>() + total_divider,
            panes.iter().map(|i| i.height()).max().unwrap_or(0),
        ),
        ComposeLayout::Vertical => (
            panes.iter().map(|i| i.width()).max().unwrap_or(0),
            panes.iter().map(|i| i.height()).sum::<u32>() + total_divider,
        ),
    };

    let divider_color = divider_color_for(canvas_bg);
    let mut canvas: RgbaImage = ImageBuffer::from_pixel(width.max(1), height.max(1), canvas_bg);
    let mut offset = 0u32;
    for (idx, src) in panes.iter().enumerate() {
        match layout {
            ComposeLayout::Horizontal => {
                image::imageops::overlay(&mut canvas, src, offset as i64, 0);
                offset += src.width();
                if idx + 1 < panes.len() && divider > 0 {
                    fill_rect(&mut canvas, offset, 0, divider, height, divider_color);
                    offset += divider;
                }
            }
            ComposeLayout::Vertical => {
                image::imageops::overlay(&mut canvas, src, 0, offset as i64);
                offset += src.height();
                if idx + 1 < panes.len() && divider > 0 {
                    fill_rect(&mut canvas, 0, offset, width, divider, divider_color);
                    offset += divider;
                }
            }
        }
    }

    Ok(canvas)
}

/// Fill an axis-aligned rectangle on `canvas` with a solid `color`, clipping to
/// the canvas bounds.
fn fill_rect(canvas: &mut RgbaImage, x: u32, y: u32, w: u32, h: u32, color: Rgba<u8>) {
    let (cw, ch) = canvas.dimensions();
    let x_end = (x + w).min(cw);
    let y_end = (y + h).min(ch);
    for py in y..y_end {
        for px in x..x_end {
            canvas.put_pixel(px, py, color);
        }
    }
}

/// A request to redact a screenshot: the compiled rule engine plus an optional
/// filter limiting which rule names apply.
pub struct RedactionRequest<'a> {
    pub engine: &'a RedactionEngine,
    pub rules: Option<Vec<String>>,
}

/// Controls how the returned plain text is produced.
///
/// By default (`strip_ansi = false`, `redact_text = false`) the *original*
/// terminal output is returned with ANSI color codes intact, so an agent sees
/// exactly what was on screen and can decide what to redact. Redaction still
/// always applies to the rendered PNG regardless of these options.
#[derive(Debug, Clone, Copy, Default)]
pub struct TextOptions {
    /// Strip ANSI escape codes from the returned text (return plain text).
    pub strip_ansi: bool,
    /// Also apply redaction to the returned text (mask matches with blocks).
    pub redact_text: bool,
    /// Embed the terminal text in the PNG's `Description` metadata so the
    /// screenshot is readable by screen readers. When redaction ran, the
    /// *redacted* text is embedded so the image never carries the secrets its
    /// pixels hide.
    pub embed_description: bool,
    /// Take the colored text from the parsed *screen* rather than echoing the
    /// source bytes.
    ///
    /// Set for interactive captures, whose raw stream is a terminal session
    /// rather than a document: it carries readline's redraws, bracketed-paste
    /// and window-title sequences, cursor motion, and the trailing prompt the
    /// screenshot deliberately drops. Reading those bytes as text shows things
    /// that were never on screen, so the screen itself is the honest source.
    ///
    /// Left unset for `render`, where the bytes *are* the document, so the
    /// text returned is the file itself rather than a re-rendering of it.
    /// A head/tail line selection overrides this: text that does not match the
    /// picture would only mislead.
    pub from_screen: bool,
}

const MAX_TITLE_CHARS: usize = 60;

/// Parsed RGBA theme ready for rendering.
#[derive(Debug, Clone)]
pub struct Theme {
    pub foreground: Rgba<u8>,
    pub background: Rgba<u8>,
    pub palette: [Rgba<u8>; 16],
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ChromeOptions {
    pub enabled: bool,
    pub preset: String,
    pub title: Option<String>,
    pub timestamp: bool,
    pub shadow: bool,
    pub radius: u32,
    /// Draw soft rounded corners. Independent of `enabled`: with chrome the
    /// window frame is rounded; without chrome the terminal image itself is
    /// given rounded corners (transparent outside the curve). Defaults to
    /// `true`; the serde default keeps older [`RenderMeta`] records working.
    #[serde(default = "default_true")]
    pub rounded: bool,
    pub outer_padding: u32,
    pub title_bar_height: u32,
}

fn default_true() -> bool {
    true
}

impl ChromeOptions {
    pub fn from_config(config: &ChromeConfig) -> Self {
        Self {
            enabled: config.enabled && config.preset != "none",
            preset: config.preset.clone(),
            title: config.title.clone(),
            timestamp: config.timestamp,
            shadow: config.shadow,
            radius: config.radius,
            rounded: config.rounded,
            outer_padding: config.outer_padding,
            title_bar_height: config.title_bar_height,
        }
    }
}

impl Theme {
    /// Parse a ThemeConfig (hex strings) into an RGBA Theme.
    pub fn from_config(config: &ThemeConfig) -> Result<Self> {
        Ok(Self {
            foreground: parse_hex_color(&config.foreground)?,
            background: parse_hex_color(&config.background)?,
            palette: {
                let mut arr = [Rgba([0, 0, 0, 255]); 16];
                for (i, hex) in config.palette.iter().enumerate() {
                    arr[i] = parse_hex_color(hex)?;
                }
                arr
            },
        })
    }

    /// Fallback dark theme (no config needed).
    pub fn dark() -> Self {
        Self {
            foreground: Rgba([204, 204, 204, 255]),
            background: Rgba([30, 30, 30, 255]),
            palette: [
                Rgba([30, 30, 30, 255]),
                Rgba([204, 0, 0, 255]),
                Rgba([78, 154, 6, 255]),
                Rgba([196, 160, 0, 255]),
                Rgba([52, 101, 164, 255]),
                Rgba([117, 80, 123, 255]),
                Rgba([6, 152, 160, 255]),
                Rgba([211, 215, 207, 255]),
                Rgba([85, 87, 83, 255]),
                Rgba([239, 41, 41, 255]),
                Rgba([138, 226, 52, 255]),
                Rgba([252, 233, 79, 255]),
                Rgba([114, 159, 207, 255]),
                Rgba([173, 127, 168, 255]),
                Rgba([52, 226, 226, 255]),
                Rgba([238, 238, 236, 255]),
            ],
        }
    }
}

fn parse_hex_color(hex: &str) -> Result<Rgba<u8>> {
    let hex = hex.trim().trim_start_matches('#');
    // Guard on ASCII hex digits before slicing: a non-ASCII string (e.g.
    // "#abc\u{20ac}") is six *bytes* but slicing it would split a UTF-8
    // character and panic.
    anyhow::ensure!(
        hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()),
        "Invalid hex color: #{}",
        hex
    );
    let r = u8::from_str_radix(&hex[0..2], 16)?;
    let g = u8::from_str_radix(&hex[2..4], 16)?;
    let b = u8::from_str_radix(&hex[4..6], 16)?;
    Ok(Rgba([r, g, b, 255]))
}

/// Font ascent (baseline offset from the top of the line box) at `size`,
/// with a proportional fallback for fonts that carry no horizontal line
/// metrics, so an unusual but parseable font cannot panic the renderer.
fn font_ascent(font: &Font, size: f32) -> f32 {
    font.horizontal_line_metrics(size)
        .map(|m| m.ascent)
        .unwrap_or(size * 0.8)
}

/// Line height (baseline-to-baseline advance) at `size`, with a fallback for
/// fonts that carry no horizontal line metrics.
fn font_line_height(font: &Font, size: f32) -> f32 {
    font.horizontal_line_metrics(size)
        .map(|m| m.new_line_size)
        .unwrap_or(size * 1.2)
}

/// Whether `font` genuinely covers `ch`.
///
/// A font that lacks a character maps it to glyph 0 (`.notdef`), which most
/// faces draw as a tofu box. Rasterizing that box would "succeed" and hide the
/// gap, so glyph 0 never counts as coverage - a character mapped to it must
/// keep walking the fallback chain. Glyphs that exist but rasterize to nothing
/// at this size (an empty outline in a broken font) are rejected the same way,
/// while whitespace is accepted because an empty box is exactly right for it.
fn font_covers(font: &Font, ch: char, size: f32) -> bool {
    if !font.has_glyph(ch) {
        return false;
    }
    if ch.is_whitespace() {
        return true;
    }
    let metrics = font.metrics(ch, size);
    metrics.width > 0 && metrics.height > 0
}

/// A font picked for one character, plus whether it came from the fallback
/// chain. Fallback faces have their own metrics, so their glyphs are placed
/// differently (see [`GlyphPlacement`]) to keep the monospace grid intact.
struct ChosenFont<'a> {
    font: &'a Font,
    is_fallback: bool,
}

/// How a glyph is positioned inside its cell.
///
/// Primary-font glyphs use their own side bearing and their own font's ascent,
/// exactly as before fallback existed. Fallback glyphs instead get the primary
/// font's ascent (so every glyph on a line shares one baseline) and are
/// centered inside the cell they occupy (so a face with different metrics
/// cannot shift the monospace grid).
#[derive(Clone, Copy, Default)]
struct GlyphPlacement {
    /// Baseline offset from the top of the line box. `None` means "use the
    /// glyph's own font ascent".
    ascent: Option<f32>,
    /// When set, the glyph is centered horizontally in a box of this width
    /// instead of being placed at its left side bearing.
    center_width: Option<u32>,
}

impl GlyphPlacement {
    /// Placement for a glyph drawn from the primary (or bold) face.
    fn natural() -> Self {
        Self::default()
    }

    /// Placement for a fallback glyph: primary baseline, centered in a cell
    /// (or a wide character's two cells) of `width` pixels.
    fn fallback(ascent: f32, width: u32) -> Self {
        Self {
            ascent: Some(ascent),
            center_width: Some(width),
        }
    }
}

/// Rasterization size for a fallback glyph: `font_size` scaled so the glyph's
/// advance matches `target_advance` (the width of the cell, or of both cells of
/// a wide character, in device pixels).
///
/// Fonts disagree on how much of the em an advance takes - MonoLisa's is 0.64em
/// against JetBrains Mono's 0.6em - so a fallback glyph drawn at the nominal
/// size is narrower than the cell it lands in. That is invisible for a symbol
/// but breaks box drawing, where every `─` would leave a gap and a `bat` frame
/// would come out dashed. Matching the advance makes those runs tile.
///
/// The ratio is clamped so an unusual fallback face (a proportional font, or a
/// glyph with no advance at all) cannot blow the glyph up or shrink it away.
fn fallback_font_size(font: &Font, ch: char, font_size: f32, target_advance: u32) -> f32 {
    let advance = font.metrics(ch, font_size).advance_width;
    if advance <= 0.0 || target_advance == 0 {
        return font_size;
    }
    let ratio = (target_advance as f32 / advance).clamp(0.5, 1.5);
    font_size * ratio
}

/// Save an RGBA image as a PNG, optionally embedding `description` as an
/// `iTXt` chunk under the standard `Description` keyword so screen readers and
/// other assistive tooling can read the terminal text back out of the image.
///
/// `iTXt` (rather than `tEXt`) is used because it is the only PNG text chunk
/// that carries UTF-8: terminal output routinely contains box drawing (`bat`,
/// `tree`), Greek, CJK, and symbols, all of which `tEXt`'s Latin-1 encoding
/// would destroy. The text is only sanitized of control characters and capped
/// at [`MAX_DESCRIPTION_BYTES`] on a character boundary.
pub fn save_png(img: &RgbaImage, path: &Path, description: Option<&str>) -> Result<()> {
    let file = std::fs::File::create(path)
        .with_context(|| format!("Failed to create image file {:?}", path))?;
    let writer = std::io::BufWriter::new(file);
    let mut encoder = png::Encoder::new(writer, img.width(), img.height());
    encoder.set_color(png::ColorType::Rgba);
    encoder.set_depth(png::BitDepth::Eight);
    if let Some(text) = description {
        let text = description_text_chunk(text);
        if !text.is_empty() {
            encoder
                .add_itxt_chunk("Description".to_string(), text)
                .with_context(|| format!("Failed to embed description in {:?}", path))?;
        }
    }
    let mut writer = encoder
        .write_header()
        .with_context(|| format!("Failed to write PNG header for {:?}", path))?;
    writer
        .write_image_data(img.as_raw())
        .with_context(|| format!("Failed to write PNG data for {:?}", path))?;
    writer
        .finish()
        .with_context(|| format!("Failed to finalize PNG {:?}", path))?;
    Ok(())
}

/// Maximum size of an embedded `Description` text chunk. Sized so the text of
/// a full capture - which is every retained line, not just the last screenful -
/// fits: at ~60 bytes a line that covers several thousand lines, well past the
/// point where the image itself dominates the file. Longer captures are
/// truncated so a screenshot's metadata never dwarfs its pixels.
const MAX_DESCRIPTION_BYTES: usize = 256 * 1024;

/// Read the UTF-8 `Description` text embedded in a PNG by [`save_png`].
///
/// Only the `iTXt` chunk is consulted: that is the only PNG text chunk that
/// carries UTF-8, and it is the one termshot writes. A file without the chunk
/// (or one that cannot be read or decoded) yields `None` - missing metadata is
/// never an error, since composition must still work for foreign PNGs.
pub fn read_png_description(path: &Path) -> Option<String> {
    let file = std::fs::File::open(path)
        .map_err(|e| tracing::debug!("No description read from {:?}: {}", path, e))
        .ok()?;
    let decoder = png::Decoder::new(std::io::BufReader::new(file));
    let reader = decoder
        .read_info()
        .map_err(|e| tracing::debug!("No description read from {:?}: {}", path, e))
        .ok()?;
    let info = reader.info();
    let chunk = info
        .utf8_text
        .iter()
        .find(|c| c.keyword.eq_ignore_ascii_case("Description"))?;
    let text = chunk
        .get_text()
        .map_err(|e| tracing::debug!("Undecodable description in {:?}: {}", path, e))
        .ok()?;
    let text = text.trim_end_matches('\n').to_string();
    if text.is_empty() { None } else { Some(text) }
}

/// Build the `Description` metadata for a composed image from the descriptions
/// of the panes it was built from.
///
/// Each pane's text is separated by a clearly marked header so a reader can
/// tell where one terminal ends and the next begins. Panes that carry no
/// description are marked as such rather than silently dropped, so the pane
/// numbering always matches the image. Returns `None` when no pane has a
/// description at all - inventing one would only describe metadata that is not
/// there.
fn composed_description(paths: &[PathBuf]) -> Option<String> {
    let descriptions: Vec<Option<String>> = paths
        .iter()
        .map(|p| read_png_description(p))
        .collect::<Vec<_>>();
    if descriptions.iter().all(Option::is_none) {
        return None;
    }
    let mut out = String::new();
    for (idx, description) in descriptions.iter().enumerate() {
        if idx > 0 {
            out.push_str(&format!("\n\n--- Pane {} ---\n\n", idx + 1));
        }
        match description {
            Some(text) => out.push_str(text),
            None => out.push_str("(no description)"),
        }
    }
    Some(out)
}

/// Render a parsed screen back to colored text: one line per screen row, with
/// SGR sequences re-emitted wherever the style changes.
///
/// This is a *text* rendering, not a terminal stream to be re-parsed: rows are
/// separated by hard newlines, which is exactly what a reader wants and exactly
/// what a capture destined for the renderer must not do (it would erase the
/// terminal's soft-wrap information, and with it the ability to redact a value
/// that crossed the right margin).
fn screen_ansi_text(screen: &CapturedScreen, cols: u16) -> String {
    let (rows, _) = screen.size();
    let mut out = String::new();

    for row in 0..rows {
        if row > 0 {
            out.push('\n');
        }
        let mut style: Option<CellStyle> = None;
        // Trailing blanks carry no information; stop at the last filled cell.
        let last_col = (0..cols)
            .rev()
            .find(|&col| {
                screen
                    .cell(row, col)
                    .map(|c| c.has_contents())
                    .unwrap_or(false)
            })
            .map(|col| col + 1)
            .unwrap_or(0);

        for col in 0..last_col {
            let Some(cell) = screen.cell(row, col) else {
                continue;
            };
            if cell.is_wide_continuation() {
                continue;
            }
            let cell_style = CellStyle::of(cell);
            if style != Some(cell_style) {
                out.push_str(&cell_style.sgr());
                style = Some(cell_style);
            }
            let contents = cell.contents();
            if contents.is_empty() {
                out.push(' ');
            } else {
                out.push_str(contents);
            }
        }
        if style.is_some() {
            out.push_str("\x1b[0m");
        }
    }

    out.trim_end().to_string()
}

/// The drawing attributes of one cell, used to emit an SGR sequence only where
/// the style actually changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CellStyle {
    fg: vt100::Color,
    bg: vt100::Color,
    bold: bool,
    dim: bool,
    italic: bool,
    underline: bool,
    inverse: bool,
}

impl CellStyle {
    fn of(cell: &vt100::Cell) -> Self {
        Self {
            fg: cell.fgcolor(),
            bg: cell.bgcolor(),
            bold: cell.bold(),
            dim: cell.dim(),
            italic: cell.italic(),
            underline: cell.underline(),
            inverse: cell.inverse(),
        }
    }

    /// The SGR escape sequence that selects this style, starting from a reset
    /// so no attribute of a previous cell can linger.
    fn sgr(&self) -> String {
        let mut params: Vec<String> = vec!["0".to_string()];
        for (on, code) in [
            (self.bold, "1"),
            (self.dim, "2"),
            (self.italic, "3"),
            (self.underline, "4"),
            (self.inverse, "7"),
        ] {
            if on {
                params.push(code.to_string());
            }
        }
        match self.fg {
            vt100::Color::Default => {}
            vt100::Color::Idx(i) if i < 8 => params.push(format!("{}", 30 + i)),
            vt100::Color::Idx(i) if i < 16 => params.push(format!("{}", 90 + i - 8)),
            vt100::Color::Idx(i) => params.push(format!("38;5;{}", i)),
            vt100::Color::Rgb(r, g, b) => params.push(format!("38;2;{};{};{}", r, g, b)),
        }
        match self.bg {
            vt100::Color::Default => {}
            vt100::Color::Idx(i) if i < 8 => params.push(format!("{}", 40 + i)),
            vt100::Color::Idx(i) if i < 16 => params.push(format!("{}", 100 + i - 8)),
            vt100::Color::Idx(i) => params.push(format!("48;5;{}", i)),
            vt100::Color::Rgb(r, g, b) => params.push(format!("48;2;{};{};{}", r, g, b)),
        }
        format!("\x1b[{}m", params.join(";"))
    }
}

/// Prepare terminal text for a PNG `iTXt` `Description` chunk.
///
/// The text stays UTF-8 - box drawing, Greek, CJK and symbols all survive
/// verbatim - so a screen reader gets what the terminal actually showed.
/// Newlines are kept because they carry the line structure of the capture;
/// other control characters are dropped, since `iTXt` text is a plain string
/// and stray escapes would only confuse a reader. The result is capped at
/// [`MAX_DESCRIPTION_BYTES`], truncated on a character boundary so the chunk
/// is never invalid UTF-8.
fn description_text_chunk(text: &str) -> String {
    let mut out = String::with_capacity(text.len().min(MAX_DESCRIPTION_BYTES));
    for ch in text.chars() {
        if ch != '\n' && ((ch as u32) < 0x20 || (ch as u32) == 0x7f) {
            continue;
        }
        if out.len() + ch.len_utf8() > MAX_DESCRIPTION_BYTES {
            break;
        }
        out.push(ch);
    }
    while out.ends_with('\n') {
        out.pop();
    }
    out
}

/// The fonts used to draw one theme: its primary face, an optional real bold
/// face, and the fallback chain searched for characters the primary face does
/// not cover. Cell metrics are derived from the primary face, so a theme with a
/// wider font gets a proportionally wider grid.
///
/// One of these is built per distinct font chain when the [`Renderer`] is
/// constructed and shared (behind an `Arc`) by every theme that resolves to the
/// same files, so no font is ever parsed per screenshot - let alone per cell.
pub struct ThemeFonts {
    font: Font,
    font_bold: Option<Font>,
    /// Fonts searched, in order, for characters the primary face does not
    /// have. The embedded JetBrains Mono is always first, followed by the
    /// fonts a theme listed in `fallback_fonts`.
    fallback_fonts: Vec<Font>,
    cell_width: u32,
    cell_height: u32,
    /// The shaped path for this same chain: the cells `fontdue` cannot draw
    /// one scalar at a time. Built lazily on first use, so a chain that only
    /// ever renders ASCII never touches a font database.
    shaping: ShapingEngine,
}

/// The font files one theme resolves to. Doubles as the cache key that lets
/// themes sharing a chain share one parsed [`ThemeFonts`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct FontChainSpec {
    primary: Option<PathBuf>,
    bold: Option<PathBuf>,
    fallbacks: Vec<PathBuf>,
}

impl FontChainSpec {
    /// The same chain, in the same order, as the shaped path's font sources:
    /// primary face, bold face, the embedded JetBrains Mono, then every
    /// configured fallback. Automatic system font discovery comes after all of
    /// them, so an explicitly configured font is never overruled by whatever
    /// happens to be installed.
    fn shaping_sources(&self) -> Vec<FontSource> {
        let mut sources = Vec::with_capacity(self.fallbacks.len() + 3);
        let push = |source: FontSource, sources: &mut Vec<FontSource>| {
            if !sources.contains(&source) {
                sources.push(source);
            }
        };
        if let Some(primary) = &self.primary {
            push(FontSource::File(primary.clone()), &mut sources);
        }
        if let Some(bold) = &self.bold {
            push(FontSource::File(bold.clone()), &mut sources);
        }
        push(FontSource::Embedded(EMBEDDED_FONT), &mut sources);
        for fallback in &self.fallbacks {
            push(FontSource::File(fallback.clone()), &mut sources);
        }
        sources
    }
}

impl ThemeFonts {
    /// Load one font chain. The primary and bold faces are hard errors when
    /// they cannot be read or parsed (the user asked for that exact file);
    /// fallback entries are best-effort and only shrink the chain.
    ///
    /// `shaping` decides how the same chain is set up for the shaped path,
    /// which is built lazily and only consulted for cells `fontdue` cannot
    /// draw correctly on its own.
    fn load(spec: &FontChainSpec, font_size: f32, shaping: &ShapingOptions) -> Result<Self> {
        // Use an explicitly configured font file if provided, otherwise fall
        // back to the font embedded in the binary.
        let font_data = match spec.primary.as_deref() {
            Some(path) => {
                std::fs::read(path).with_context(|| format!("Failed to read font: {:?}", path))?
            }
            None => EMBEDDED_FONT.to_vec(),
        };
        let font = Font::from_bytes(font_data, FontSettings::default())
            .map_err(|e| anyhow::anyhow!("Failed to parse font: {}", e))?;

        // Load bold font if provided
        let font_bold = if let Some(path) = spec.bold.as_deref() {
            let data = std::fs::read(path)
                .with_context(|| format!("Failed to read bold font: {:?}", path))?;
            Some(
                Font::from_bytes(data, FontSettings::default())
                    .map_err(|e| anyhow::anyhow!("Failed to parse bold font: {}", e))?,
            )
        } else {
            None
        };

        // Fallback chain. The embedded JetBrains Mono always comes first so a
        // theme font without box drawing, arrows, or symbols (MonoLisa, for
        // example) still renders them instead of tofu; fonts the theme
        // configured are searched after it. A fallback that cannot be read or
        // parsed is skipped with a warning - one bad entry must never stop the
        // renderer from starting.
        let mut fallback_fonts = Vec::with_capacity(spec.fallbacks.len() + 1);
        match Font::from_bytes(EMBEDDED_FONT, FontSettings::default()) {
            Ok(embedded) => fallback_fonts.push(embedded),
            Err(e) => tracing::warn!("Failed to parse embedded fallback font: {}", e),
        }
        for path in &spec.fallbacks {
            match std::fs::read(path) {
                Ok(data) => match Font::from_bytes(data, FontSettings::default()) {
                    Ok(parsed) => fallback_fonts.push(parsed),
                    Err(e) => tracing::warn!("Ignoring unusable fallback font {:?}: {}", path, e),
                },
                Err(e) => tracing::warn!("Ignoring unreadable fallback font {:?}: {}", path, e),
            }
        }

        let metrics = font.metrics('M', font_size);
        let cell_width = metrics.advance_width.ceil() as u32;
        let cell_height = font_line_height(&font, font_size).ceil() as u32;

        Ok(Self {
            font,
            font_bold,
            fallback_fonts,
            cell_width,
            cell_height,
            shaping: ShapingEngine::new(spec.shaping_sources(), shaping.clone()),
        })
    }

    /// Whether any face in the `fontdue` chain genuinely covers `ch`.
    ///
    /// This is the same walk [`Renderer::font_for_char`] makes, asked as a
    /// yes/no question: a character nothing covers is one the shaped path has
    /// to try, because the alternative is the tofu box 1.1.5 drew.
    fn chain_covers(&self, ch: char, bold: bool, font_size: f32) -> bool {
        let primary = match (bold, self.font_bold.as_ref()) {
            (true, Some(bold_font)) => bold_font,
            _ => &self.font,
        };
        font_covers(primary, ch, font_size)
            || self
                .fallback_fonts
                .iter()
                .any(|font| font_covers(font, ch, font_size))
    }

    /// The shaped path built for this chain. Exposed so tests can inspect the
    /// font precedence the shaper resolved.
    #[cfg(test)]
    pub(crate) fn shaping(&self) -> &ShapingEngine {
        &self.shaping
    }
}

/// Font inputs that are not part of a theme: the user's explicit overrides and
/// the globally configured font.
///
/// A theme's own `font`/`font_bold`/`fallback_fonts` are read from its
/// [`ThemeConfig`], so every theme gets its own chain regardless of how it is
/// selected (CLI flag or MCP request parameter).
#[derive(Debug, Clone, Default)]
pub struct FontSelection {
    /// Explicit user override (CLI `--font`). Wins over a theme's own font.
    pub font_override: Option<PathBuf>,
    /// Explicit user override (CLI `--font-bold`). Wins over a theme's own
    /// bold font.
    pub font_bold_override: Option<PathBuf>,
    /// Globally configured font (`font_path` in the config file), used by
    /// themes that declare no font of their own.
    pub global_font: Option<PathBuf>,
    /// Fallback fonts applied to every theme, searched after the theme's own
    /// fallback fonts.
    pub global_fallback_fonts: Vec<PathBuf>,
}

impl FontSelection {
    /// Resolve the font chain for one theme: explicit overrides first, then
    /// the theme's own fonts, then the globally configured font, and finally
    /// the embedded font (represented by `None`).
    fn spec_for(&self, theme: Option<&ThemeConfig>) -> FontChainSpec {
        let (theme_font, theme_bold) = match theme {
            Some(t) => t.resolved_font_paths(),
            None => (None, None),
        };
        let mut fallbacks = match theme {
            Some(t) => t.resolved_fallback_font_paths(),
            None => Vec::new(),
        };
        fallbacks.extend(self.global_fallback_fonts.iter().cloned());
        FontChainSpec {
            primary: self
                .font_override
                .clone()
                .or(theme_font)
                .or_else(|| self.global_font.clone()),
            bold: self.font_bold_override.clone().or(theme_bold),
            fallbacks,
        }
    }
}

/// Capture settings for a [`Renderer`].
///
/// A struct rather than another constructor parameter so later settings can be
/// added without changing anyone's call: build one with
/// [`RendererOptions::default`] and override only what you need, either through
/// the builder method or with `..RendererOptions::default()`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RendererOptions {
    /// How many scrolled-off lines a capture retains. See [`crate::capture`]:
    /// the viewport height decides where lines wrap, this decides how much of
    /// the output survives to be rendered. Clamped per capture to what the
    /// retained-cell budget allows for the terminal's width.
    ///
    /// This is a *tail*-retention bound. A [`LineSelection::Head`] render
    /// ignores it and streams the beginning of the output as it scrolls past,
    /// so `Head(n)` is lines 1..n at any capacity.
    pub max_scrollback_lines: usize,
}

impl Default for RendererOptions {
    fn default() -> Self {
        Self {
            max_scrollback_lines: DEFAULT_MAX_SCROLLBACK_LINES,
        }
    }
}

impl RendererOptions {
    /// Set how many scrolled-off lines a capture retains.
    pub fn with_max_scrollback_lines(mut self, lines: usize) -> Self {
        self.max_scrollback_lines = lines;
        self
    }
}

/// Per-render settings for [`Renderer::render_bytes_with_options`].
///
/// Defaults to rendering every retained line, which is exactly what the
/// 1.0.0 [`Renderer::render_bytes`] does.
///
/// This is the struct published in 1.0.0 and it keeps exactly the one field it
/// was published with, so an exhaustive literal - `RenderOptions { lines }`,
/// written with no `..Default::default()` - still compiles. Settings added
/// since live in [`ExtendedRenderOptions`], which borrows rather than owns and
/// therefore could not have been added here without giving this type a
/// lifetime parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RenderOptions {
    /// Which of the retained lines to render.
    pub lines: LineSelection,
}

impl RenderOptions {
    /// Render only the lines `selection` names.
    pub fn with_lines(mut self, selection: LineSelection) -> Self {
        self.lines = selection;
        self
    }

    /// Add manual redactions, producing the extended options
    /// [`Renderer::render_bytes_with_extended_options`] takes.
    pub fn with_manual(self, manual: &ManualRedactions) -> ExtendedRenderOptions<'_> {
        ExtendedRenderOptions::from(self).with_manual(manual)
    }
}

/// Per-render settings for [`Renderer::render_bytes_with_extended_options`]:
/// the published [`RenderOptions`] plus everything termshot has gained since
/// 1.0.0.
///
/// Defaults to exactly what a 1.0.0 render does - every retained line, no
/// manual redactions - so `ExtendedRenderOptions::default()` and
/// `RenderOptions::default().into()` render identically.
#[derive(Debug, Clone, Copy, Default)]
pub struct ExtendedRenderOptions<'a> {
    /// The settings 1.0.0 published, unchanged.
    pub base: RenderOptions,
    /// Caller-supplied redactions (the CLI's `--redaction`, the MCP
    /// `redact_screenshot` specifications) to apply on top of any rule-based
    /// redaction, before the image is drawn. Their coordinates are validated
    /// against the bounds this very render paints, so an out-of-bounds range
    /// fails instead of quietly covering nothing.
    pub manual: Option<&'a ManualRedactions>,
}

/// A 1.0.0 option set is an extended one with nothing extra set.
impl From<RenderOptions> for ExtendedRenderOptions<'_> {
    fn from(base: RenderOptions) -> Self {
        Self { base, manual: None }
    }
}

/// Two option sets are equal when they select the same lines and carry the
/// same manual redactions. [`ManualRedactions`] holds compiled regexes, which
/// have no meaningful equality, so it is compared by identity.
impl PartialEq for ExtendedRenderOptions<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.base == other.base
            && match (self.manual, other.manual) {
                (None, None) => true,
                (Some(a), Some(b)) => std::ptr::eq(a, b),
                _ => false,
            }
    }
}

impl Eq for ExtendedRenderOptions<'_> {}

impl<'a> ExtendedRenderOptions<'a> {
    /// Render only the lines `selection` names.
    pub fn with_lines(mut self, selection: LineSelection) -> Self {
        self.base.lines = selection;
        self
    }

    /// Apply `manual` redactions to this render.
    pub fn with_manual(mut self, manual: &'a ManualRedactions) -> Self {
        self.manual = Some(manual);
        self
    }

    /// [`ExtendedRenderOptions::with_manual`] for a caller that may or may not
    /// have any: `None` renders exactly as a call with no manual redactions.
    ///
    /// Both entry points build their options this way - the CLI from
    /// `--redaction`, the MCP server from a tool's `redactions` array - so an
    /// absent list means the same thing on either side.
    pub fn with_optional_manual(mut self, manual: Option<&'a ManualRedactions>) -> Self {
        self.manual = manual;
        self
    }

    /// Which of the retained lines to render.
    pub fn lines(&self) -> LineSelection {
        self.base.lines
    }
}

/// Renders a vt100 screen buffer to a PNG image.
pub struct Renderer {
    /// Font chain per theme name, so a screenshot rendered with theme `x`
    /// always uses `x`'s primary, bold, and fallback fonts. Built once at
    /// construction; themes with identical font files share one entry.
    theme_fonts: HashMap<String, Arc<ThemeFonts>>,
    /// Chain used for the default theme and for any theme without its own
    /// entry.
    default_fonts: Arc<ThemeFonts>,
    font_size: f32,
    themes: HashMap<String, Theme>,
    default_theme: String,
    default_chrome: ChromeOptions,
    padding: u32,
    /// How many scrolled-off lines a capture retains. See
    /// [`crate::capture`]: the viewport height decides where lines wrap, this
    /// decides how much of the output survives to be rendered.
    max_scrollback_lines: usize,
}

impl Renderer {
    /// Build a renderer with the default capture settings.
    ///
    /// This is the constructor published in 1.0.0 and its behaviour is
    /// unchanged. Use [`Renderer::new_with_options`] to set how much
    /// scrolled-off output a capture retains.
    pub fn new(
        fonts: &FontSelection,
        font_size: f32,
        theme_configs: &HashMap<String, ThemeConfig>,
        default_theme: &str,
        chrome_config: &ChromeConfig,
    ) -> Result<Self> {
        Self::new_with_options(
            fonts,
            font_size,
            theme_configs,
            default_theme,
            chrome_config,
            RendererOptions::default(),
        )
    }

    /// [`Renderer::new`] with explicit capture options.
    ///
    /// Unicode shaping is configured from the environment; use
    /// [`Renderer::new_with_shaping`] to set it explicitly.
    pub fn new_with_options(
        fonts: &FontSelection,
        font_size: f32,
        theme_configs: &HashMap<String, ThemeConfig>,
        default_theme: &str,
        chrome_config: &ChromeConfig,
        options: RendererOptions,
    ) -> Result<Self> {
        Self::new_with_shaping(
            fonts,
            font_size,
            theme_configs,
            default_theme,
            chrome_config,
            options,
            ShapingOptions::from_env(),
        )
    }

    /// [`Renderer::new_with_options`] with the shaped text path configured
    /// explicitly.
    ///
    /// [`ShapingOptions::deterministic`] restricts every shaped run to the
    /// fonts the configuration names, which is what a reproducible screenshot
    /// pipeline - or a test - wants; [`ShapingOptions::disabled`] reproduces
    /// the 1.1.5 renderer exactly.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_shaping(
        fonts: &FontSelection,
        font_size: f32,
        theme_configs: &HashMap<String, ThemeConfig>,
        default_theme: &str,
        chrome_config: &ChromeConfig,
        options: RendererOptions,
        shaping: ShapingOptions,
    ) -> Result<Self> {
        // Parse all themes
        let mut themes = HashMap::new();
        for (name, config) in theme_configs {
            match Theme::from_config(config) {
                Ok(theme) => {
                    themes.insert(name.clone(), theme);
                }
                Err(e) => {
                    tracing::warn!("Failed to parse theme '{}': {}", name, e);
                }
            }
        }
        // Always have a fallback
        themes.entry("dark".to_string()).or_insert_with(Theme::dark);

        // The default chain is the one used when no theme is requested (and
        // when a theme's own fonts cannot be loaded), so a broken font here is
        // a hard error rather than a silent downgrade.
        let default_spec = fonts.spec_for(theme_configs.get(default_theme));
        let default_fonts = Arc::new(ThemeFonts::load(&default_spec, font_size, &shaping)?);

        // One font chain per theme, deduplicated by the files it resolves to:
        // the common case (every theme using the same font) parses one chain.
        let mut by_spec: HashMap<FontChainSpec, Arc<ThemeFonts>> = HashMap::new();
        by_spec.insert(default_spec, Arc::clone(&default_fonts));
        let mut theme_fonts: HashMap<String, Arc<ThemeFonts>> = HashMap::new();
        for name in themes.keys() {
            let spec = fonts.spec_for(theme_configs.get(name));
            if let Some(existing) = by_spec.get(&spec) {
                theme_fonts.insert(name.clone(), Arc::clone(existing));
                continue;
            }
            match ThemeFonts::load(&spec, font_size, &shaping) {
                Ok(loaded) => {
                    let loaded = Arc::new(loaded);
                    by_spec.insert(spec, Arc::clone(&loaded));
                    theme_fonts.insert(name.clone(), loaded);
                }
                Err(e) => {
                    // One theme's unusable font must not stop the renderer:
                    // that theme falls back to the default chain.
                    tracing::warn!(
                        "Failed to load fonts for theme '{}': {}; using the default fonts",
                        name,
                        e
                    );
                    theme_fonts.insert(name.clone(), Arc::clone(&default_fonts));
                }
            }
        }

        Ok(Self {
            theme_fonts,
            default_fonts,
            font_size,
            themes,
            default_theme: default_theme.to_string(),
            default_chrome: ChromeOptions::from_config(chrome_config),
            padding: 16,
            max_scrollback_lines: options.max_scrollback_lines,
        })
    }

    /// Resolve a requested theme name to one that exists, falling back to the
    /// default theme and then "dark". Theme colors and theme fonts are looked
    /// up with the same name, so they can never disagree.
    fn resolve_theme_name<'a>(&'a self, name: Option<&'a str>) -> &'a str {
        let name = name.unwrap_or(&self.default_theme);
        if self.themes.contains_key(name) {
            name
        } else if self.themes.contains_key(&self.default_theme) {
            &self.default_theme
        } else {
            "dark"
        }
    }

    /// Get a theme by name, falling back to default then "dark".
    pub fn get_theme(&self, name: Option<&str>) -> &Theme {
        let name = self.resolve_theme_name(name);
        self.themes
            .get(name)
            .or_else(|| self.themes.get(&self.default_theme))
            .or_else(|| self.themes.get("dark"))
            .expect("no themes available")
    }

    /// Get the font chain for a theme, falling back to the default chain.
    fn fonts_for(&self, name: Option<&str>) -> &ThemeFonts {
        let name = self.resolve_theme_name(name);
        self.theme_fonts
            .get(name)
            .map(Arc::as_ref)
            .unwrap_or(&self.default_fonts)
    }

    /// List available theme names.
    pub fn theme_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.themes.keys().cloned().collect();
        names.sort();
        names
    }

    /// Render raw ANSI bytes to a PNG image.
    /// Returns the path to the saved image, the plain text content, the
    /// per-rule redaction audit counts (empty when no redaction was applied),
    /// and the [`RenderMeta`] describing how it was rendered.
    ///
    /// `output_name` is an optional descriptive base name (typically the
    /// command line) used to derive the PNG filename; it is sanitized and made
    /// unique within `output_dir`. When `None`, a generic name is used.
    ///
    /// Redaction (when `redaction` is supplied) always masks the rendered PNG.
    /// The returned text is controlled by `text`: by default it is the original
    /// output with ANSI colors intact; set `redact_text` to also scrub it, or
    /// `strip_ansi` to return plain (color-free) text.
    ///
    /// `rows` is the PTY viewport height - it decides where lines wrap - not a
    /// limit on how much output is shown: the capture keeps everything that
    /// scrolled off (up to the renderer's scrollback capacity) and renders all
    /// of it. Use [`render_bytes_with_options`] to render only one end of it.
    ///
    /// No sidecar files are written; callers that need to re-render (e.g. the
    /// MCP server) should keep the raw bytes and returned [`RenderMeta`] in
    /// memory.
    ///
    /// [`render_bytes_with_options`]: Self::render_bytes_with_options
    #[allow(clippy::too_many_arguments)]
    pub fn render_bytes(
        &self,
        data: &[u8],
        cols: u16,
        rows: u16,
        output_dir: &Path,
        output_name: Option<&str>,
        theme_name: Option<&str>,
        chrome: Option<&ChromeOptions>,
        redaction: Option<&RedactionRequest>,
        text: TextOptions,
        auto_crop: bool,
    ) -> Result<RenderOutput> {
        let (path, text, audit, context) = self.render_bytes_with_options(
            data,
            cols,
            rows,
            output_dir,
            output_name,
            theme_name,
            chrome,
            redaction,
            text,
            auto_crop,
            RenderOptions::default(),
        )?;
        Ok((path, text, audit, context.meta))
    }

    /// [`Renderer::render_bytes`], rendering only the lines `options` selects.
    ///
    /// A head or tail selection also decides what the returned text and the
    /// PNG's `Description` metadata contain: text that does not match the
    /// picture would only mislead.
    ///
    /// This is the signature published in 1.0.0. Use
    /// [`Renderer::render_bytes_with_extended_options`] to also apply
    /// caller-supplied redactions.
    #[allow(clippy::too_many_arguments)]
    pub fn render_bytes_with_options(
        &self,
        data: &[u8],
        cols: u16,
        rows: u16,
        output_dir: &Path,
        output_name: Option<&str>,
        theme_name: Option<&str>,
        chrome: Option<&ChromeOptions>,
        redaction: Option<&RedactionRequest>,
        text: TextOptions,
        auto_crop: bool,
        options: RenderOptions,
    ) -> Result<RenderOutputWithContext> {
        self.render_bytes_with_extended_options(
            data,
            cols,
            rows,
            output_dir,
            output_name,
            theme_name,
            chrome,
            redaction,
            text,
            auto_crop,
            options.into(),
        )
    }

    /// [`Renderer::render_bytes_with_options`], also applying the manual
    /// redactions `options` carries.
    ///
    /// This is the render path the CLI (`--redaction`) and the MCP server use.
    /// Manual coordinate ranges are validated against the bounds this very
    /// render paints, so a range that would land outside the image is an error
    /// rather than a redaction that covers nothing.
    #[allow(clippy::too_many_arguments)]
    pub fn render_bytes_with_extended_options(
        &self,
        data: &[u8],
        cols: u16,
        rows: u16,
        output_dir: &Path,
        output_name: Option<&str>,
        theme_name: Option<&str>,
        chrome: Option<&ChromeOptions>,
        redaction: Option<&RedactionRequest>,
        text: TextOptions,
        auto_crop: bool,
        options: ExtendedRenderOptions<'_>,
    ) -> Result<RenderOutputWithContext> {
        let lines = options.base.lines;
        let capture = self.capture(data, rows, cols, lines);
        let screen = &capture;
        if capture.truncated() {
            tracing::warn!(
                "capture truncated: more output scrolled off than the {}-line scrollback \
                 could hold, so the oldest lines were dropped; raise `max_scrollback_lines` \
                 (a wide terminal caps it below the configured value) or render one end with \
                 a head/tail selection",
                self.effective_scrollback_lines(rows, cols)
            );
        }

        // A caller that asked for specific lines wants text that matches them,
        // so the text comes from the capture rather than from the source bytes.
        let text = TextOptions {
            from_screen: text.from_screen || !lines.is_all(),
            ..text
        };

        // Redaction pass: scan the parsed buffer before rendering.
        if let Some(req) = redaction {
            tracing::debug!("redaction: {} active rule(s)", req.engine.rule_count());
        }
        let mut redaction_map =
            redaction.map(|req| req.engine.redact_screen(screen, req.rules.as_deref()));

        // Caller-supplied redactions are applied to the same capture, on top of
        // whatever the rules matched. Their coordinates address the image this
        // call is about to draw, so they are checked against its rendered
        // bounds - which the line selection and `auto_crop` decide - rather
        // than against the retained grid.
        if let Some(manual) = options.manual.filter(|manual| !manual.is_empty()) {
            let (rendered_rows, rendered_cols) =
                self.rendered_bounds(screen, theme_name, auto_crop);
            manual.validate_bounds(rendered_rows, rendered_cols)?;
            manual.apply_to(
                screen,
                redaction_map.get_or_insert_with(RedactionMap::default),
            );
        }

        if let Some(map) = &redaction_map
            && !map.is_empty()
        {
            tracing::info!(
                "redaction: masked {} cell(s) ({})",
                map.cell_count(),
                map.audit_summary()
            );
        }

        let plain_text = self.output_text(data, screen, cols, redaction_map.as_ref(), text);

        let theme = self.get_theme(theme_name);
        // Fonts are selected by the same theme name as the colors, so a theme
        // requested per call (CLI flag or MCP parameter) renders with its own
        // primary, bold, and fallback fonts.
        let fonts = self.fonts_for(theme_name);
        let chrome = chrome.unwrap_or(&self.default_chrome);
        let image = self.render_to_image(
            screen,
            theme,
            fonts,
            chrome,
            redaction_map.as_ref(),
            auto_crop,
        )?;

        let base = sanitize_base_name(output_name.unwrap_or(""));
        let path = unique_png_path(output_dir, &base);
        let description = self.description_text(screen, cols, redaction_map.as_ref(), text);
        save_png(&image, &path, description.as_deref())?;

        let context = RenderContext {
            meta: RenderMeta {
                cols,
                rows,
                theme: theme_name.map(str::to_owned),
                chrome: Some(chrome.clone()),
                auto_crop,
                from_screen: text.from_screen,
            },
            lines,
            truncated: capture.truncated(),
        };

        let audit = redaction_map.map(|m| m.counts).unwrap_or_default();
        Ok((path, plain_text, audit, context))
    }

    /// Capture the terminal session in `data` exactly the way
    /// [`render_bytes_with_options`] does, so a redaction map built from the
    /// returned capture addresses the same cells the renderer will draw.
    ///
    /// [`render_bytes_with_options`]: Self::render_bytes_with_options
    pub fn capture(
        &self,
        data: &[u8],
        rows: u16,
        cols: u16,
        lines: LineSelection,
    ) -> CapturedScreen {
        // Normalize bare LF to CRLF before feeding the terminal parser so raw,
        // non-TTY captured ANSI (piped output or redirected logs passed to
        // `render`) lands on proper lines instead of staircasing. This is a
        // no-op for PTY-sourced bytes (from `exec`), which already use CRLF,
        // and the original `data` is still used for the returned text.
        let normalized = normalize_newlines(data);
        CapturedScreen::parse_selected(&normalized, rows, cols, self.max_scrollback_lines, lines)
    }

    /// How many scrolled-off lines a capture of a `rows` x `cols` terminal
    /// actually retains: the configured limit, capped by the retained-cell
    /// budget that keeps a wide terminal from turning a line count into
    /// gigabytes. See [`crate::capture::effective_scrollback_lines`].
    pub fn effective_scrollback_lines(&self, rows: u16, cols: u16) -> usize {
        effective_scrollback_lines(rows, cols, self.max_scrollback_lines)
    }

    /// Capture the session behind an already rendered screenshot, using the
    /// geometry and line selection it was rendered with.
    pub fn capture_for(&self, data: &[u8], context: &RenderContext) -> CapturedScreen {
        self.capture(data, context.meta.rows, context.meta.cols, context.lines)
    }

    /// The `(rows, cols)` of `screen` a render with these settings actually
    /// paints.
    ///
    /// Not the same as [`CapturedScreen::size`]: the renderer stops at the last
    /// row holding content, and with `auto_crop` it stops at the rightmost
    /// column holding content too, so a retained grid is routinely taller and
    /// wider than the image made from it. Callers that address cells in a
    /// finished screenshot - a coordinate redaction, say - have to be checked
    /// against *these* bounds, because a cell outside them is counted by the
    /// capture but never drawn.
    pub fn rendered_bounds(
        &self,
        screen: &CapturedScreen,
        theme_name: Option<&str>,
        auto_crop: bool,
    ) -> (u16, u16) {
        let layout = self.screen_layout(screen, self.fonts_for(theme_name), auto_crop);
        (
            u16::try_from(layout.content_rows).unwrap_or(u16::MAX),
            u16::try_from(layout.content_cols).unwrap_or(u16::MAX),
        )
    }

    /// [`Renderer::rendered_bounds`] for the theme and `auto_crop` setting a
    /// screenshot was rendered with, so a re-render draws exactly these cells.
    pub fn rendered_bounds_for(
        &self,
        screen: &CapturedScreen,
        context: &RenderContext,
    ) -> (u16, u16) {
        self.rendered_bounds(
            screen,
            context.meta.theme.as_deref(),
            context.meta.auto_crop,
        )
    }

    /// How many scrolled-off lines a capture retains before the terminal starts
    /// dropping the oldest ones.
    pub fn max_scrollback_lines(&self) -> usize {
        self.max_scrollback_lines
    }

    /// Re-render a screenshot from its original raw terminal bytes and
    /// [`RenderMeta`], applying a prebuilt redaction map, and overwrite the PNG
    /// in place. Returns the new plain text (controlled by `text`) and
    /// per-label audit counts.
    pub fn render_redaction_to(
        &self,
        data: &[u8],
        meta: &RenderMeta,
        map: &RedactionMap,
        out_path: &Path,
        text: TextOptions,
    ) -> Result<(String, Vec<(String, usize)>)> {
        self.render_redaction_to_with_context(
            data,
            &RenderContext::from_meta(meta.clone()),
            map,
            out_path,
            text,
        )
    }

    /// [`Renderer::render_redaction_to`], re-rendering the same line selection
    /// the screenshot was made with rather than the whole capture.
    ///
    /// This is what a caller holding a [`RenderContext`] - the MCP server's
    /// render cache, say - should use: a redaction map is addressed in the
    /// coordinates of the rows the image actually shows, so re-rendering a
    /// different set of rows would move every block.
    pub fn render_redaction_to_with_context(
        &self,
        data: &[u8],
        context: &RenderContext,
        map: &RedactionMap,
        out_path: &Path,
        text: TextOptions,
    ) -> Result<(String, Vec<(String, usize)>)> {
        let meta = &context.meta;
        let capture = self.capture_for(data, context);
        let screen = &capture;

        let plain_text = self.output_text(data, screen, meta.cols, Some(map), text);
        let theme = self.get_theme(meta.theme.as_deref());
        let chrome = meta
            .chrome
            .clone()
            .unwrap_or_else(|| self.default_chrome.clone());
        let fonts = self.fonts_for(meta.theme.as_deref());
        let image =
            self.render_to_image(screen, theme, fonts, &chrome, Some(map), meta.auto_crop)?;
        let description = self.description_text(screen, meta.cols, Some(map), text);
        save_png(&image, out_path, description.as_deref())?;
        Ok((plain_text, map.counts.clone()))
    }

    /// Compose several existing screenshots into a single image laid out
    /// horizontally or vertically, using the given theme's background color as
    /// the fill. When `output` is `None` a file name is auto-generated in
    /// `output_dir`. Returns the path of the saved composite PNG.
    ///
    /// The inputs should be RAW terminal screenshots (chrome `none`): they are
    /// combined into a single tmux-style split, and when `chrome` is supplied
    /// and enabled the *composed* result is wrapped in one outer window frame,
    /// rather than each pane carrying its own title bar.
    ///
    /// When `embed_description` is set (the global `embed_description` config),
    /// the panes' own `Description` metadata is read back and concatenated into
    /// the composite's `Description` chunk, so a composed image is as readable
    /// to assistive tooling as the screenshots it was built from.
    #[allow(clippy::too_many_arguments)]
    pub fn compose_screenshots(
        &self,
        paths: &[PathBuf],
        layout: ComposeLayout,
        divider: u32,
        theme_name: Option<&str>,
        chrome: Option<&ChromeOptions>,
        output_dir: &Path,
        output: Option<&Path>,
        embed_description: bool,
    ) -> Result<PathBuf> {
        let theme = self.get_theme(theme_name);
        let fonts = self.fonts_for(theme_name);
        // Read the panes' descriptions before composing, so the composite can
        // carry them even though the pixels are merged.
        let description = if embed_description {
            composed_description(paths)
        } else {
            None
        };
        let composed = compose_images(paths, layout, divider, theme.background)?;
        let composed = match chrome {
            Some(chrome) if chrome.enabled => {
                self.compose_with_chrome(composed, theme, fonts, chrome)
            }
            // Frameless composite: round the outer corners (transparent
            // outside the curve) so a bare gallery still gets soft corners
            // instead of a hard rectangle, matching single-screenshot output.
            _ => {
                let mut composed = composed;
                if self.default_chrome.rounded {
                    self.round_image_corners(
                        &mut composed,
                        self.default_chrome.radius * RENDER_SCALE,
                    );
                }
                composed
            }
        };

        let path = match output {
            Some(p) => p.to_path_buf(),
            None => {
                let id = &uuid::Uuid::new_v4().to_string()[..8];
                output_dir.join(format!("termshot_composed_{}.png", id))
            }
        };
        save_png(&composed, &path, description.as_deref())
            .with_context(|| format!("Failed to save composed image to {:?}", path))?;
        Ok(path)
    }

    /// Compute the plain text to return to the caller.
    ///
    /// Precedence:
    /// * `redact_text` (with matches) -> stripped text with redaction blocks;
    /// * else `strip_ansi` -> plain (color-free) text from the parsed screen;
    /// * else `from_screen` -> the screen's text with its colors re-applied;
    /// * else the original raw output with ANSI color codes preserved.
    fn output_text(
        &self,
        data: &[u8],
        screen: &CapturedScreen,
        cols: u16,
        redaction: Option<&RedactionMap>,
        opts: TextOptions,
    ) -> String {
        if opts.redact_text
            && let Some(map) = redaction
            && !map.is_empty()
        {
            return map.redacted_plain_text(screen);
        }
        if opts.strip_ansi {
            screen
                .rows(0, cols)
                .collect::<Vec<String>>()
                .join("\n")
                .trim_end()
                .to_string()
        } else if opts.from_screen {
            screen_ansi_text(screen, cols)
        } else {
            String::from_utf8_lossy(data).trim_end().to_string()
        }
    }

    /// Build the accessibility text embedded in the PNG's `Description`
    /// metadata, or `None` when embedding is disabled.
    ///
    /// This is always ANSI-free plain text, and always the *redacted* version
    /// when redaction masked anything, so the metadata can never leak a secret
    /// the pixels hide.
    fn description_text(
        &self,
        screen: &CapturedScreen,
        cols: u16,
        redaction: Option<&RedactionMap>,
        opts: TextOptions,
    ) -> Option<String> {
        if !opts.embed_description {
            return None;
        }
        if let Some(map) = redaction
            && !map.is_empty()
        {
            return Some(map.redacted_plain_text(screen));
        }
        Some(
            screen
                .rows(0, cols)
                .collect::<Vec<String>>()
                .join("\n")
                .trim_end()
                .to_string(),
        )
    }

    /// Render a screen (with optional redaction) to a composed RGBA image.
    #[allow(clippy::too_many_arguments)]
    fn render_to_image(
        &self,
        screen: &CapturedScreen,
        theme: &Theme,
        fonts: &ThemeFonts,
        chrome: &ChromeOptions,
        redaction: Option<&RedactionMap>,
        auto_crop: bool,
    ) -> Result<RgbaImage> {
        let layout = self.screen_layout(screen, fonts, auto_crop);
        if chrome.enabled {
            // The terminal is drawn straight into the window frame rather than
            // into a buffer of its own that is then copied in: one full-size
            // layer instead of two, for an image that is already the largest
            // allocation in the process.
            let metrics = ChromeMetrics::new(
                chrome,
                layout.width,
                layout.height,
                self.timestamp_reserve(fonts),
            );
            metrics.check_budget(screen)?;
            return Ok(self.compose_with_chrome_layer(
                theme,
                fonts,
                chrome,
                &metrics,
                |renderer, frame, x, y| {
                    renderer.draw_screen_into(frame, x, y, &layout, screen, theme, fonts, redaction)
                },
            ));
        }
        // No chrome: optionally round the terminal content itself so a bare
        // screenshot still has soft corners on a transparent background,
        // like macOS window captures or code-screenshot tools.
        let mut img = self.render_screen(screen, theme, fonts, redaction, auto_crop)?;
        if chrome.rounded {
            self.round_image_corners(&mut img, chrome.radius * RENDER_SCALE);
        }
        Ok(img)
    }

    /// Geometry of the terminal portion of a screenshot: how many rows and
    /// columns actually hold content, and the pixel size they render to.
    /// Computed before anything is allocated so the memory budget can be
    /// checked against a number rather than against a failed allocation.
    fn screen_layout(
        &self,
        screen: &CapturedScreen,
        fonts: &ThemeFonts,
        auto_crop: bool,
    ) -> ScreenLayout {
        let rows = screen.size().0 as u32;
        let cols = screen.size().1 as u32;

        let content_rows = self.find_content_rows(screen, rows, cols);
        // Optionally trim the image width to the rightmost column that
        // actually holds content, so narrow output doesn't sit in a wide,
        // mostly-empty frame. The trim keeps the image's normal padding on the
        // right and nothing more, so both margins match.
        let content_cols = if auto_crop {
            self.find_content_cols(screen, content_rows, cols)
        } else {
            cols
        };

        let scale = RENDER_SCALE;
        let cell_w = fonts.cell_width * scale;
        let cell_h = fonts.cell_height * scale;
        let padding = self.padding * scale;

        ScreenLayout {
            content_rows,
            content_cols,
            cell_w,
            cell_h,
            padding,
            width: content_cols * cell_w + padding * 2,
            height: content_rows * cell_h + padding * 2,
        }
    }

    /// Render a capture to a standalone RGBA image.
    /// Renders at 2x resolution for sharper text.
    fn render_screen(
        &self,
        screen: &CapturedScreen,
        theme: &Theme,
        fonts: &ThemeFonts,
        redaction: Option<&RedactionMap>,
        auto_crop: bool,
    ) -> Result<RgbaImage> {
        let layout = self.screen_layout(screen, fonts, auto_crop);
        // One buffer, allocated below and returned to the caller.
        check_render_budget(layout.width, layout.height, 1, screen)?;
        let mut img: RgbaImage =
            ImageBuffer::from_pixel(layout.width, layout.height, theme.background);
        self.draw_screen_into(&mut img, 0, 0, &layout, screen, theme, fonts, redaction);
        Ok(img)
    }

    /// Draw a capture into `img` with its top-left corner at `(ox, oy)`.
    ///
    /// The background is painted here too, so a caller can hand over a buffer
    /// it allocated for other reasons - the window frame, say - instead of
    /// making one just for the terminal.
    #[allow(clippy::too_many_arguments)]
    fn draw_screen_into(
        &self,
        img: &mut RgbaImage,
        ox: u32,
        oy: u32,
        layout: &ScreenLayout,
        screen: &CapturedScreen,
        theme: &Theme,
        fonts: &ThemeFonts,
        redaction: Option<&RedactionMap>,
    ) {
        let ScreenLayout {
            content_rows,
            content_cols,
            cell_w,
            cell_h,
            padding,
            width,
            height,
        } = *layout;
        let hi_font_size = self.font_size * RENDER_SCALE as f32;

        self.draw_rect(img, ox, oy, width, height, theme.background);

        let shaping = fonts.shaping.enabled();

        for row in 0..content_rows {
            // First column past a run the shaper could not draw, so a failed
            // attempt is not repeated cell by cell across the same run.
            let mut unshapable_until = 0u32;
            let mut col = 0u32;
            while col < content_cols {
                let Some(cell) = screen.cell(row as u16, col as u16) else {
                    col += 1;
                    continue;
                };
                let x = ox + col * cell_w + padding;
                let y = oy + row * cell_h + padding;

                // Redaction: draw a block (with an optional short label)
                // in place of sensitive cell contents, using the color the
                // matching rule requested.
                if let Some(rc) = redaction.and_then(|m| m.get(row as u16, col as u16)) {
                    let block =
                        Rgba([rc.block_color[0], rc.block_color[1], rc.block_color[2], 255]);
                    self.draw_rect(img, x, y, cell_w, cell_h, block);
                    if let Some(label_ch) = rc.label_char {
                        let label =
                            Rgba([rc.label_color[0], rc.label_color[1], rc.label_color[2], 255]);
                        self.draw_char_with_font(
                            img,
                            fonts,
                            x,
                            y,
                            label_ch,
                            label,
                            false,
                            hi_font_size,
                            &self.font_for_char(fonts, label_ch, false, hi_font_size),
                            cell_w,
                        );
                    }
                    col += 1;
                    continue;
                }

                // Cells the per-scalar path cannot draw correctly - combining
                // marks, joining and reordering scripts, emoji, anything no
                // configured font covers - are gathered into a run of cells
                // with one style and shaped together. Everything else takes
                // the path it always took, so ordinary output is untouched.
                if shaping && col >= unshapable_until && self.cell_needs_shaping(fonts, cell) {
                    let run =
                        self.collect_shaped_run(screen, fonts, row, col, content_cols, redaction);
                    if self
                        .draw_shaped_run(img, fonts, theme, screen, row, col, &run, layout, ox, oy)
                    {
                        col += run.cols;
                        continue;
                    }
                    unshapable_until = col + run.cols;
                }

                self.draw_cell(img, fonts, theme, cell, x, y, cell_w, cell_h, hi_font_size);
                col += 1;
            }
        }
    }

    /// Draw one cell the way the renderer always has: its background, its
    /// characters through the `fontdue` chain, then its underline.
    #[allow(clippy::too_many_arguments)]
    fn draw_cell(
        &self,
        img: &mut RgbaImage,
        fonts: &ThemeFonts,
        theme: &Theme,
        cell: &vt100::Cell,
        x: u32,
        y: u32,
        cell_w: u32,
        cell_h: u32,
        hi_font_size: f32,
    ) {
        let (fg_color, bg_color) = self.resolve_cell_colors(cell, theme);

        // Draw background
        if bg_color != theme.background {
            self.draw_rect(img, x, y, cell_w, cell_h, bg_color);
        }

        // Draw character(s) at 2x font size
        let ch = cell.contents();
        if !ch.is_empty() && ch != " " {
            // A double-width character owns this cell and the
            // vt100 continuation cell after it, so a fallback
            // glyph is centered across both.
            let cell_span = if cell.is_wide() { cell_w * 2 } else { cell_w };
            let bold = cell.bold();
            let has_bold_font = fonts.font_bold.is_some();
            for c in ch.chars() {
                let chosen = self.font_for_char(fonts, c, bold, hi_font_size);
                self.draw_char_with_font(
                    img,
                    fonts,
                    x,
                    y,
                    c,
                    fg_color,
                    cell.italic(),
                    hi_font_size,
                    &chosen,
                    cell_span,
                );
                // Faux bold only when no bold font is available
                if bold && !has_bold_font {
                    self.draw_char_with_font(
                        img,
                        fonts,
                        x + 1,
                        y,
                        c,
                        fg_color,
                        cell.italic(),
                        hi_font_size,
                        &chosen,
                        cell_span,
                    );
                }
            }
        }

        // Underline
        if cell.underline() {
            let uy = y + cell_h.saturating_sub(2 * RENDER_SCALE);
            self.draw_rect(img, x, uy, cell_w, RENDER_SCALE, fg_color);
        }
    }

    /// Whether a cell has to go through the shaper.
    ///
    /// Four cases, and only four:
    ///
    /// * the cell holds more than one scalar, which is how vt100 stores a base
    ///   character plus its combining marks, a variation sequence, or a keycap;
    /// * the cell asks for emoji presentation, which wants a color font;
    /// * the cell belongs to a script whose glyphs depend on their neighbours
    ///   (Arabic joining, Brahmic reordering, Hebrew points); or
    /// * no font in the configured chain covers it, so the alternative is the
    ///   tofu box the renderer used to draw.
    ///
    /// Everything else - ASCII, box drawing, Latin, Greek, Cyrillic, CJK the
    /// chain covers - answers `false` and is drawn exactly as before.
    fn cell_needs_shaping(&self, fonts: &ThemeFonts, cell: &vt100::Cell) -> bool {
        let contents = cell.contents();
        if contents.is_empty() || contents == " " {
            return false;
        }
        let mut chars = contents.chars();
        let Some(first) = chars.next() else {
            return false;
        };
        if chars.next().is_some() {
            return true;
        }
        if unicode::cluster_is_emoji(contents) {
            return true;
        }
        if unicode::script_needs_shaping(first.script()) {
            return true;
        }
        let hi_font_size = self.font_size * RENDER_SCALE as f32;
        !fonts.chain_covers(first, cell.bold(), hi_font_size)
    }

    /// Gather the run of cells starting at `col` that will be shaped together.
    ///
    /// A run stops at the first cell that is redacted, styled differently,
    /// does not need shaping at all, or belongs to a different shaping class
    /// (emoji against text, a joining or reordering script against everything
    /// else). Spaces inside a contiguous script phrase are retained when the
    /// same shaping class resumes afterward; splitting Arabic at each space
    /// would reverse its word order by laying out each word independently.
    /// These boundaries keep a ligature or an overhanging mark from crossing a
    /// redaction block or a color change: the shaper never sees the two sides
    /// as one piece of text, and the run's glyphs are clipped to its columns.
    fn collect_shaped_run(
        &self,
        screen: &CapturedScreen,
        fonts: &ThemeFonts,
        row: u32,
        col: u32,
        content_cols: u32,
        redaction: Option<&RedactionMap>,
    ) -> ShapedRunSpan {
        let mut cells = Vec::new();
        let mut cols = 0u32;
        let mut style = None;
        let mut class = None;
        let mut at = col;
        while at < content_cols {
            let Some(cell) = screen.cell(row as u16, at as u16) else {
                break;
            };
            let wide = cell.is_wide() && at + 1 < content_cols;
            let span = if wide { 2 } else { 1 };
            if (0..span).any(|offset| {
                redaction
                    .and_then(|map| map.get(row as u16, (at + offset) as u16))
                    .is_some()
            }) {
                break;
            }
            let cell_style = CellStyle::of(cell);
            match style {
                None => style = Some(cell_style),
                Some(first) if first == cell_style => {}
                Some(_) => break,
            }
            if !self.cell_needs_shaping(fonts, cell) {
                let bridges_contiguous_phrase = class == Some((false, true))
                    && cell.contents() == " "
                    && self.contiguous_shaping_resumes(
                        screen,
                        fonts,
                        row,
                        at + span,
                        content_cols,
                        redaction,
                        cell_style,
                    );
                if bridges_contiguous_phrase {
                    cells.push(RunCell {
                        text: cell.contents().to_string(),
                        cols: span,
                    });
                    cols += span;
                    at += span;
                    continue;
                }
                break;
            }
            let contents = cell.contents();
            let cell_class = (
                unicode::cluster_is_emoji(contents),
                unicode::cluster_forces_contiguous_run(contents),
            );
            match class {
                None => class = Some(cell_class),
                Some(first) if first == cell_class => {}
                Some(_) => break,
            }
            cells.push(RunCell {
                text: contents.to_string(),
                cols: span,
            });
            cols += span;
            at += span;
        }
        ShapedRunSpan { cells, cols }
    }

    /// Whether a sequence of same-style spaces is followed by another cell in
    /// the current contiguous shaping class without crossing a redaction.
    #[allow(clippy::too_many_arguments)]
    fn contiguous_shaping_resumes(
        &self,
        screen: &CapturedScreen,
        fonts: &ThemeFonts,
        row: u32,
        mut at: u32,
        content_cols: u32,
        redaction: Option<&RedactionMap>,
        style: CellStyle,
    ) -> bool {
        while at < content_cols {
            let Some(cell) = screen.cell(row as u16, at as u16) else {
                return false;
            };
            let span = if cell.is_wide() && at + 1 < content_cols {
                2
            } else {
                1
            };
            if (0..span).any(|offset| {
                redaction
                    .and_then(|map| map.get(row as u16, (at + offset) as u16))
                    .is_some()
            }) || CellStyle::of(cell) != style
            {
                return false;
            }
            if cell.contents() == " " {
                at += span;
                continue;
            }
            return self.cell_needs_shaping(fonts, cell)
                && !unicode::cluster_is_emoji(cell.contents())
                && unicode::cluster_forces_contiguous_run(cell.contents());
        }
        false
    }

    /// Draw a run of cells through the shaper.
    ///
    /// Returns `false` when the shaper produced nothing, in which case the
    /// caller falls back to the per-cell path it always used.
    #[allow(clippy::too_many_arguments)]
    fn draw_shaped_run(
        &self,
        img: &mut RgbaImage,
        fonts: &ThemeFonts,
        theme: &Theme,
        screen: &CapturedScreen,
        row: u32,
        col: u32,
        run: &ShapedRunSpan,
        layout: &ScreenLayout,
        ox: u32,
        oy: u32,
    ) -> bool {
        if run.cells.is_empty() {
            return false;
        }
        let ScreenLayout {
            cell_w,
            cell_h,
            padding,
            ..
        } = *layout;
        let Some(first) = screen.cell(row as u16, col as u16) else {
            return false;
        };
        let hi_font_size = self.font_size * RENDER_SCALE as f32;
        let bold = first.bold();
        let has_bold_font = fonts.font_bold.is_some();
        let request = RunRequest {
            cells: &run.cells,
            cell_w,
            font_size: hi_font_size,
            ascent: font_ascent(&fonts.font, hi_font_size),
            bold: bold && has_bold_font,
            italic: first.italic(),
        };
        let placed = fonts.shaping.place_run(&request);
        if placed.is_empty() {
            return false;
        }

        let run_x = ox + col * cell_w + padding;
        let run_y = oy + row * cell_h + padding;
        let (fg_color, _) = self.resolve_cell_colors(first, theme);

        // Backgrounds first, for every column the run owns, so a shaped glyph
        // is never painted over by the cell after it.
        for offset in 0..run.cols {
            let Some(cell) = screen.cell(row as u16, (col + offset) as u16) else {
                continue;
            };
            let (_, bg_color) = self.resolve_cell_colors(cell, theme);
            if bg_color != theme.background {
                self.draw_rect(
                    img,
                    run_x + offset * cell_w,
                    run_y,
                    cell_w,
                    cell_h,
                    bg_color,
                );
            }
        }

        // The run's own rectangle is the clip: nothing shaped may reach the
        // cell after it, redacted or not.
        let clip = ClipRect {
            x0: run_x as i32,
            x1: (run_x + run.cols * cell_w) as i32,
            y0: run_y as i32,
            y1: (run_y + cell_h) as i32,
        };
        for glyph in &placed {
            self.blend_glyph_bitmap(
                img,
                run_x as i32 + glyph.x,
                run_y as i32 + glyph.y,
                &glyph.bitmap,
                fg_color,
                clip,
            );
            // Faux bold, exactly as the per-scalar path does it when no bold
            // face is configured.
            if bold && !has_bold_font {
                self.blend_glyph_bitmap(
                    img,
                    run_x as i32 + glyph.x + 1,
                    run_y as i32 + glyph.y,
                    &glyph.bitmap,
                    fg_color,
                    clip,
                );
            }
        }

        for offset in 0..run.cols {
            let Some(cell) = screen.cell(row as u16, (col + offset) as u16) else {
                continue;
            };
            if cell.underline() {
                let (cell_fg, _) = self.resolve_cell_colors(cell, theme);
                let uy = run_y + cell_h.saturating_sub(2 * RENDER_SCALE);
                self.draw_rect(
                    img,
                    run_x + offset * cell_w,
                    uy,
                    cell_w,
                    RENDER_SCALE,
                    cell_fg,
                );
            }
        }
        true
    }

    /// Blend one rasterized glyph bitmap into `img`, clipped to `clip`.
    ///
    /// A coverage bitmap is modulated by `color` exactly like a `fontdue`
    /// glyph; a color bitmap carries its own RGBA and only takes `color`'s
    /// alpha, so a color emoji keeps its own palette instead of being tinted
    /// with the cell's foreground.
    fn blend_glyph_bitmap(
        &self,
        img: &mut RgbaImage,
        x: i32,
        y: i32,
        bitmap: &GlyphBitmap,
        color: Rgba<u8>,
        clip: ClipRect,
    ) {
        for gy in 0..bitmap.height {
            let py = y + gy as i32;
            if py < clip.y0 || py >= clip.y1 || py < 0 || py as u32 >= img.height() {
                continue;
            }
            for gx in 0..bitmap.width {
                let px = x + gx as i32;
                if px < clip.x0 || px >= clip.x1 || px < 0 || px as u32 >= img.width() {
                    continue;
                }
                let index = (gy * bitmap.width + gx) as usize;
                let pixel = if bitmap.color {
                    let at = index * 4;
                    let Some(rgba) = bitmap.data.get(at..at + 4) else {
                        continue;
                    };
                    if rgba[3] == 0 {
                        continue;
                    }
                    Rgba([
                        rgba[0],
                        rgba[1],
                        rgba[2],
                        ((rgba[3] as u32 * color[3] as u32) / 255) as u8,
                    ])
                } else {
                    let Some(&coverage) = bitmap.data.get(index) else {
                        continue;
                    };
                    if coverage == 0 {
                        continue;
                    }
                    Rgba([
                        color[0],
                        color[1],
                        color[2],
                        ((coverage as u32 * color[3] as u32) / 255) as u8,
                    ])
                };
                self.put_pixel_blend(img, px as u32, py as u32, pixel);
            }
        }
    }

    /// Compose a chrome-framed screenshot around a terminal image.
    ///
    /// Kept as the image-in, image-out form for callers that already hold a
    /// rendered terminal; [`Renderer::render_to_image`] uses
    /// [`Renderer::compose_with_chrome_layer`] instead so the terminal is drawn
    /// straight into the frame and only one full-size layer exists at a time.
    fn compose_with_chrome(
        &self,
        terminal: RgbaImage,
        theme: &Theme,
        fonts: &ThemeFonts,
        chrome: &ChromeOptions,
    ) -> RgbaImage {
        if !chrome.enabled {
            return terminal;
        }
        let metrics = ChromeMetrics::new(
            chrome,
            terminal.width(),
            terminal.height(),
            self.timestamp_reserve(fonts),
        );
        self.compose_with_chrome_layer(theme, fonts, chrome, &metrics, |_, frame, ox, oy| {
            for y in 0..terminal.height() {
                for x in 0..terminal.width() {
                    frame.put_pixel(ox + x, oy + y, *terminal.get_pixel(x, y));
                }
            }
        })
    }

    /// Paint the window frame and let `draw_terminal` fill in the terminal
    /// area, at the offset it is given, directly inside the frame layer.
    ///
    /// Only the frame exists while the terminal is drawn. The shadowed canvas
    /// is allocated afterwards and only when there is a shadow to draw: without
    /// one the frame *is* the finished image, since compositing it over an
    /// empty transparent canvas would copy it pixel for pixel.
    fn compose_with_chrome_layer(
        &self,
        theme: &Theme,
        fonts: &ThemeFonts,
        chrome: &ChromeOptions,
        metrics: &ChromeMetrics,
        draw_terminal: impl FnOnce(&Self, &mut RgbaImage, u32, u32),
    ) -> RgbaImage {
        // Chrome is drawn at the same supersampling factor as the terminal so
        // the title bar, controls, and text stay proportional to the content.
        let scale = RENDER_SCALE;
        let &ChromeMetrics {
            radius,
            title_bar,
            shadow,
            frame_pad,
            bottom_pad,
            frame_w,
            frame_h,
            term_h,
            width,
            height,
        } = metrics;

        // The window body is always the terminal's own background, for every
        // preset: a screenshot must not sit inside a mismatched gray (or
        // otherwise off-theme) border. Presets differ in their title bar, not
        // in the color surrounding the capture.
        let frame_bg = theme.background;

        // The window is painted square into its own layer and rounded once, at
        // the end, with the same anti-aliased corner mask a chrome-less
        // screenshot gets. Every preset therefore shares one corner
        // implementation, and because the layer is the only opaque thing
        // composited onto the canvas, nothing outside the rounded frame can
        // stay opaque - no gray, black, or theme-colored halo around the
        // window.
        let mut frame: RgbaImage = ImageBuffer::from_pixel(frame_w, frame_h, frame_bg);

        if title_bar > 0 {
            let title_bg = match chrome.preset.as_str() {
                "macos" => Rgba([44, 44, 46, 255]),
                "gnome" => Rgba([32, 34, 39, 255]),
                "report" => Rgba([30, 32, 36, 255]),
                _ => Rgba([
                    theme.background[0].saturating_add(10),
                    theme.background[1].saturating_add(10),
                    theme.background[2].saturating_add(10),
                    255,
                ]),
            };

            // A plain rectangle: the corner mask applied to the whole layer
            // below rounds the title bar's top corners exactly like the frame's,
            // so there is no seam and no frame-colored wedge to paint over.
            self.draw_rect(&mut frame, 0, 0, frame_w, title_bar, title_bg);

            self.draw_title_bar_accents(&mut frame, chrome, 0, 0, frame_w, title_bar, theme, scale);
            if let Some(title) = chrome.title.as_deref() {
                let title = truncate_title(title);
                self.draw_text_line(
                    &mut frame,
                    fonts,
                    frame_w / 2,
                    title_bar / 2,
                    &title,
                    theme.foreground,
                    self.font_size * 0.85 * scale as f32,
                );
            }
        }

        let term_x = frame_pad;
        let term_y = frame_pad + title_bar;
        draw_terminal(self, &mut frame, term_x, term_y);

        if chrome.timestamp {
            let timestamp = Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string();
            let color = muted_text_color(theme);
            let right_x = frame_w.saturating_sub(frame_pad.max(6 * scale));
            let center_y = term_y + term_h + bottom_pad / 2;
            self.draw_text_right_aligned(
                &mut frame,
                fonts,
                right_x,
                center_y,
                &timestamp,
                color,
                self.timestamp_font_size(),
            );
        }

        // One anti-aliased corner mask for every preset, identical to the one a
        // chrome-less screenshot gets.
        self.round_image_corners(&mut frame, radius);

        if shadow == 0 {
            // Nothing to composite onto: the canvas would be transparent
            // everywhere the frame is not, and source-over onto a transparent
            // pixel reproduces the source exactly. Return the layer itself
            // rather than allocating a second image of the same size to copy
            // it into.
            return frame;
        }

        // Transparent background so rounded corners don't have a colored border
        let mut img: RgbaImage = ImageBuffer::from_pixel(width, height, Rgba([0, 0, 0, 0]));
        let frame_x = shadow / 2;
        let frame_y = shadow / 2;
        self.draw_shadow(
            &mut img,
            frame_x,
            frame_y,
            frame_w,
            frame_h,
            radius,
            4 * scale,
            6 * scale,
            12 * scale,
        );

        // Composite the window over the shadowed canvas source-over, so the
        // shadow stays visible through the corner cut-outs and the area outside
        // the window keeps the frame layer's own alpha.
        for y in 0..frame.height() {
            for x in 0..frame.width() {
                let px = *frame.get_pixel(x, y);
                if px[3] == 0 {
                    continue;
                }
                self.put_pixel_blend(&mut img, frame_x + x, frame_y + y, px);
            }
        }

        img
    }

    /// Draw the window's drop shadow.
    ///
    /// The shadow is a single pass over the ring of pixels *outside* the frame:
    /// pixels the opaque frame will cover are skipped with a cheap bounding-box
    /// test, and the remaining ones get one signed-distance evaluation against
    /// the offset rounded rectangle with a smooth falloff. The previous
    /// implementation composited twelve full-frame rounded rectangles, ~99% of
    /// which were then painted over - that cost about 97% of total render time
    /// (7.2 s vs. 0.24 s for a 200-row capture).
    ///
    /// `frame_*` is the window frame rectangle, `offset_*` how far the shadow
    /// is displaced from it, and `blur` the falloff distance in pixels.
    #[allow(clippy::too_many_arguments)]
    fn draw_shadow(
        &self,
        img: &mut RgbaImage,
        frame_x: u32,
        frame_y: u32,
        frame_w: u32,
        frame_h: u32,
        radius: u32,
        offset_x: u32,
        offset_y: u32,
        blur: u32,
    ) {
        if frame_w == 0 || frame_h == 0 || blur == 0 {
            return;
        }
        /// Peak shadow opacity directly under the frame edge.
        const PEAK_ALPHA: f32 = 110.0;

        let (img_w, img_h) = img.dimensions();
        let shadow_x = (frame_x + offset_x) as f32;
        let shadow_y = (frame_y + offset_y) as f32;
        let (sw, sh) = (frame_w as f32, frame_h as f32);
        let r = (radius as f32).min(sw / 2.0).min(sh / 2.0);
        // Rounded-rect signed distance: negative inside, positive outside.
        let sdf = |px: f32, py: f32| -> f32 {
            let cx = shadow_x + sw / 2.0;
            let cy = shadow_y + sh / 2.0;
            let qx = (px - cx).abs() - (sw / 2.0 - r);
            let qy = (py - cy).abs() - (sh / 2.0 - r);
            let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
            outside + qx.max(qy).min(0.0) - r
        };

        // Pixels well inside the frame are fully covered by the opaque window
        // and never need shadow work; this keeps the pass proportional to the
        // frame's perimeter rather than its area.
        let skip_x0 = frame_x + radius;
        let skip_x1 = frame_x + frame_w.saturating_sub(radius);
        let skip_y0 = frame_y + radius;
        let skip_y1 = frame_y + frame_h.saturating_sub(radius);

        let y0 = frame_y.saturating_sub(blur);
        let y1 = (frame_y + frame_h + offset_y + blur).min(img_h);
        let x0 = frame_x.saturating_sub(blur);
        let x1 = (frame_x + frame_w + offset_x + blur).min(img_w);
        let blur_f = blur as f32;

        for py in y0..y1 {
            let inside_y = py >= skip_y0 && py < skip_y1;
            for px in x0..x1 {
                if inside_y && px >= skip_x0 && px < skip_x1 {
                    continue;
                }
                let d = sdf(px as f32 + 0.5, py as f32 + 0.5);
                if d >= blur_f {
                    continue;
                }
                // Smoothstep falloff from the shadow edge outwards.
                let t = (1.0 - (d.max(0.0) / blur_f)).clamp(0.0, 1.0);
                let alpha = (PEAK_ALPHA * t * t * (3.0 - 2.0 * t)).round() as u8;
                if alpha == 0 {
                    continue;
                }
                self.put_pixel_blend(img, px, py, Rgba([0, 0, 0, alpha]));
            }
        }
    }

    /// Soften the corners of an already-rendered, fully opaque image by fading
    /// the alpha of pixels that fall outside a rounded-rectangle mask to zero,
    /// with a one-pixel anti-aliased edge. Used when `rounded` is enabled but
    /// no chrome frame is drawn, so a bare screenshot has soft corners on a
    /// transparent background. RGB is preserved; only alpha is scaled.
    fn round_image_corners(&self, img: &mut RgbaImage, radius: u32) {
        let (w, h) = img.dimensions();
        if radius == 0 || w == 0 || h == 0 {
            return;
        }
        // Clamp so the arcs never overlap on tiny images.
        let radius = radius.min(w / 2).min(h / 2);
        if radius == 0 {
            return;
        }
        let r = radius as f32;
        let (wf, hf) = (w as f32, h as f32);
        for py in 0..h {
            // Vertical distance into the top/bottom corner bands (0 elsewhere).
            let fy = py as f32 + 0.5;
            let dy = if fy < r {
                r - fy
            } else if fy > hf - r {
                fy - (hf - r)
            } else {
                0.0
            };
            for px in 0..w {
                let fx = px as f32 + 0.5;
                let dx = if fx < r {
                    r - fx
                } else if fx > wf - r {
                    fx - (wf - r)
                } else {
                    0.0
                };
                // Only the four corner squares need adjustment.
                if dx == 0.0 || dy == 0.0 {
                    continue;
                }
                let dist = (dx * dx + dy * dy).sqrt();
                // Coverage: 1 inside the arc, 0 outside, with a 1px soft edge.
                let coverage = (r + 0.5 - dist).clamp(0.0, 1.0);
                if coverage >= 1.0 {
                    continue;
                }
                let pixel = img.get_pixel_mut(px, py);
                pixel[3] = (pixel[3] as f32 * coverage).round() as u8;
            }
        }
    }

    /// Fill a rounded rectangle with a one-pixel anti-aliased edge.
    ///
    /// Coverage comes from the rounded-rectangle signed distance evaluated at
    /// each pixel center - the same rule [`draw_circle`](Self::draw_circle) and
    /// [`round_image_corners`](Self::round_image_corners) use - so every
    /// rounded shape termshot draws has the same smooth edge instead of a
    /// staircase.
    #[allow(clippy::too_many_arguments)]
    fn draw_rounded_rect(
        &self,
        img: &mut RgbaImage,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
        radius: u32,
        color: Rgba<u8>,
    ) {
        if w == 0 || h == 0 || color[3] == 0 {
            return;
        }
        // Clamp the radius to what the rectangle can actually accommodate.
        let r = radius.min(w / 2).min(h / 2) as f32;
        let (half_w, half_h) = (w as f32 / 2.0, h as f32 / 2.0);
        let (center_x, center_y) = (x as f32 + half_w, y as f32 + half_h);
        for py in y..(y + h).min(img.height()) {
            let qy = ((py as f32 + 0.5) - center_y).abs() - (half_h - r);
            for px in x..(x + w).min(img.width()) {
                let qx = ((px as f32 + 0.5) - center_x).abs() - (half_w - r);
                // Signed distance to the rounded rectangle: negative inside.
                let distance =
                    (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r;
                let coverage = (0.5 - distance).clamp(0.0, 1.0);
                if coverage <= 0.0 {
                    continue;
                }
                let alpha = (color[3] as f32 * coverage).round().clamp(0.0, 255.0) as u8;
                if alpha == 0 {
                    continue;
                }
                self.put_pixel_blend(img, px, py, Rgba([color[0], color[1], color[2], alpha]));
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn draw_title_bar_accents(
        &self,
        img: &mut RgbaImage,
        chrome: &ChromeOptions,
        frame_x: u32,
        frame_y: u32,
        width: u32,
        title_bar_height: u32,
        theme: &Theme,
        scale: u32,
    ) {
        match chrome.preset.as_str() {
            "macos" => {
                let colors = [
                    Rgba([255, 95, 86, 255]),
                    Rgba([255, 189, 46, 255]),
                    Rgba([39, 201, 63, 255]),
                ];
                // Every traffic light is the same true circle: one radius, one
                // vertical center, and centers spaced by a fixed pitch, so the
                // three buttons are identical discs rather than rounded squares
                // of drifting size.
                let radius = TRAFFIC_LIGHT_RADIUS * scale;
                let center_y = frame_y as f32 + title_bar_height as f32 / 2.0;
                for (i, color) in colors.into_iter().enumerate() {
                    let center_x = (frame_x
                        + (TRAFFIC_LIGHT_FIRST_CENTER + i as u32 * TRAFFIC_LIGHT_PITCH) * scale)
                        as f32;
                    self.draw_circle(img, center_x, center_y, radius as f32, color);
                }
            }
            "gnome" => {
                // Draw a compact pill on the right to imply window controls.
                let pill_w = 44 * scale;
                let pill_h = 14 * scale;
                let pill_x = frame_x + width.saturating_sub(16 * scale + pill_w);
                let pill_y = frame_y + (title_bar_height / 2).saturating_sub(pill_h / 2);
                self.draw_rounded_rect(
                    img,
                    pill_x,
                    pill_y,
                    pill_w,
                    pill_h,
                    7 * scale,
                    Rgba([255, 255, 255, 24]),
                );
                for offset in [12u32, 22, 32] {
                    self.draw_circle(
                        img,
                        (pill_x + offset * scale) as f32,
                        (pill_y + pill_h / 2) as f32,
                        (2 * scale) as f32,
                        Rgba([255, 255, 255, 90]),
                    );
                }
            }
            "report" => {
                self.draw_rect(
                    img,
                    frame_x,
                    frame_y + title_bar_height.saturating_sub(scale),
                    width,
                    scale,
                    Rgba([255, 255, 255, 20]),
                );
            }
            _ => {
                let accent = Rgba([
                    theme.foreground[0],
                    theme.foreground[1],
                    theme.foreground[2],
                    18,
                ]);
                self.draw_rect(
                    img,
                    frame_x,
                    frame_y + title_bar_height.saturating_sub(scale),
                    width,
                    scale,
                    accent,
                );
            }
        }
    }

    /// Draw a filled circle of radius `r` centered on `(cx, cy)`, with a
    /// one-pixel anti-aliased edge.
    ///
    /// Coverage is the distance from the *pixel center* to the circle center,
    /// so the disc is symmetric about `(cx, cy)` in both axes: with `cx`/`cy`
    /// on a pixel boundary (an integer coordinate) and an even diameter, the
    /// mask has exactly the same width and height and the same number of lit
    /// pixels on either side of the center. Testing squared distance against a
    /// squared radius - rather than approximating a circle with a small rounded
    /// rectangle - is what keeps the macOS traffic lights round instead of
    /// leaving single-pixel spikes at the cardinal points.
    fn draw_circle(&self, img: &mut RgbaImage, cx: f32, cy: f32, r: f32, color: Rgba<u8>) {
        if r <= 0.0 || color[3] == 0 {
            return;
        }
        let (img_w, img_h) = img.dimensions();
        // One extra pixel on each side leaves room for the anti-aliased edge.
        let x0 = (cx - r - 1.0).floor().max(0.0) as u32;
        let y0 = (cy - r - 1.0).floor().max(0.0) as u32;
        let x1 = ((cx + r + 1.0).ceil().max(0.0) as u32).min(img_w);
        let y1 = ((cy + r + 1.0).ceil().max(0.0) as u32).min(img_h);
        for py in y0..y1 {
            let dy = py as f32 + 0.5 - cy;
            for px in x0..x1 {
                let dx = px as f32 + 0.5 - cx;
                let distance = (dx * dx + dy * dy).sqrt();
                // Full coverage inside, zero outside, linear across the last
                // pixel of the edge.
                let coverage = (r + 0.5 - distance).clamp(0.0, 1.0);
                if coverage <= 0.0 {
                    continue;
                }
                let alpha = (color[3] as f32 * coverage).round().clamp(0.0, 255.0) as u8;
                if alpha == 0 {
                    continue;
                }
                self.put_pixel_blend(img, px, py, Rgba([color[0], color[1], color[2], alpha]));
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn draw_text_line(
        &self,
        img: &mut RgbaImage,
        fonts: &ThemeFonts,
        center_x: u32,
        center_y: u32,
        text: &str,
        color: Rgba<u8>,
        size: f32,
    ) {
        let total_width = self.text_width(fonts, text, size);
        self.draw_text_at(
            img,
            fonts,
            center_x as i32 - (total_width as i32 / 2),
            center_y,
            text,
            color,
            size,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn draw_text_right_aligned(
        &self,
        img: &mut RgbaImage,
        fonts: &ThemeFonts,
        right_x: u32,
        center_y: u32,
        text: &str,
        color: Rgba<u8>,
        size: f32,
    ) {
        let total_width = self.text_width(fonts, text, size);
        self.draw_text_at(
            img,
            fonts,
            right_x as i32 - total_width as i32,
            center_y,
            text,
            color,
            size,
        );
    }

    /// Font size, in device pixels, the chrome timestamp watermark is drawn at.
    fn timestamp_font_size(&self) -> f32 {
        self.font_size * TIMESTAMP_FONT_SCALE * RENDER_SCALE as f32
    }

    /// Vertical strip, in device pixels, to reserve below the terminal for the
    /// timestamp watermark: exactly one line of timestamp text plus a small gap
    /// above and below it.
    ///
    /// [`Self::draw_text_at`] centers a line on the y it is given, so the text
    /// occupies `line_height` around `bottom_pad / 2`; reserving at least that
    /// much keeps it inside the frame, and the gap keeps it off both the last
    /// row of output and the window's bottom edge.
    fn timestamp_reserve(&self, fonts: &ThemeFonts) -> u32 {
        let line_height = font_line_height(&fonts.font, self.timestamp_font_size()).ceil() as u32;
        line_height + TIMESTAMP_GAP * RENDER_SCALE * 2
    }

    fn text_width(&self, fonts: &ThemeFonts, text: &str, size: f32) -> u32 {
        // The chrome font is monospace, so every character occupies one fixed
        // cell whose width is derived from 'M'. Using a single cell advance for
        // every glyph keeps `text_width` in sync with `draw_text_at` and avoids
        // per-glyph rounding drift.
        let cell_advance = fonts.font.metrics('M', size).advance_width.round() as u32;
        text.chars().count() as u32 * cell_advance
    }

    /// Draw a run of chrome text (title, timestamp) starting at `start_x`,
    /// vertically centered on `center_y`.
    ///
    /// The chrome font is monospace, so every character advances by the exact
    /// same integer cell width; per-glyph advances would produce visible
    /// spacing wobble. Glyph placement inside each cell is delegated to
    /// [`draw_glyph`](Self::draw_glyph), the same routine that renders terminal
    /// content, so both paths share baseline and side-bearing handling.
    #[allow(clippy::too_many_arguments)]
    fn draw_text_at(
        &self,
        img: &mut RgbaImage,
        fonts: &ThemeFonts,
        start_x: i32,
        center_y: u32,
        text: &str,
        color: Rgba<u8>,
        size: f32,
    ) {
        let cell_advance = fonts.font.metrics('M', size).advance_width.round() as i32;
        let line_height = font_line_height(&fonts.font, size);
        let line_top = center_y as i32 - (line_height as i32 / 2);
        let mut cursor_x = start_x;
        for ch in text.chars() {
            let chosen = self.font_for_char(fonts, ch, false, size);
            let advance = cell_advance.max(0) as u32;
            let (render_size, placement) = if chosen.is_fallback {
                (
                    fallback_font_size(chosen.font, ch, size, advance),
                    GlyphPlacement::fallback(font_ascent(&fonts.font, size), advance),
                )
            } else {
                (size, GlyphPlacement::natural())
            };
            self.draw_glyph(
                img,
                cursor_x,
                line_top,
                ch,
                color,
                false,
                render_size,
                chosen.font,
                placement,
            );
            cursor_x += cell_advance;
        }
    }

    /// Scan the screen buffer for the last row that holds meaningful content
    /// and return the height, in cells, to render.
    ///
    /// No spare row is added. The image's normal [`Self::padding`] is the only
    /// gap kept below the last line, so a capture has the same visual margin
    /// above its first row and below its last one. Reserving an extra blank
    /// terminal row here would double the bottom margin - a whole cell of
    /// background plus the padding - and make every screenshot look
    /// bottom-heavy.
    fn find_content_rows(&self, screen: &CapturedScreen, rows: u32, cols: u32) -> u32 {
        let mut last_row_with_content = 0u32;
        for row in 0..rows {
            for col in 0..cols {
                // A row counts as content if it has visible text or any styled
                // cell (e.g. a colored background block), so background-only
                // rows are not cropped away.
                if screen
                    .cell(row as u16, col as u16)
                    .is_some_and(cell_has_content)
                {
                    last_row_with_content = row + 1;
                    break;
                }
            }
        }
        // A floor keeps an empty capture from collapsing to a zero-height
        // image; it never extends output that already has content past it.
        last_row_with_content.max(MIN_CONTENT_ROWS).min(rows)
    }

    /// Scan the screen buffer for the rightmost column that holds meaningful
    /// content - visible text, or a styled/inverse cell such as a colored
    /// background block - and return the width, in cells, to render.
    ///
    /// The bound comes from the terminal buffer, never from the pixels of a
    /// finished image: a composed screenshot's margin is the theme background,
    /// which differs per theme and is indistinguishable from an empty cell.
    ///
    /// No spare cells are added. The image's normal [`Self::padding`] is the
    /// only gap kept to the right of the last glyph, so a trimmed screenshot
    /// has the same visual margin on the left and the right. That padding also
    /// absorbs ink that legitimately overhangs its cell - anti-aliased edges,
    /// the italic shear, the one-pixel faux-bold smear, and box drawing glyphs
    /// that reach past their advance - so nothing is clipped. A double-width
    /// character keeps its vt100 continuation cell, and a wrapped row reaches
    /// the last column, so neither is cut in half.
    fn find_content_cols(&self, screen: &CapturedScreen, rows: u32, cols: u32) -> u32 {
        let mut max_col = 0u32;
        for row in 0..rows {
            for col in (0..cols).rev() {
                if let Some(cell) = screen.cell(row as u16, col as u16)
                    && cell_has_content(cell)
                {
                    // A double-width character owns this cell and the
                    // (blank) continuation cell after it.
                    let end = if cell.is_wide() { col + 2 } else { col + 1 };
                    max_col = max_col.max(end.min(cols));
                    break;
                }
            }
        }

        // A floor keeps an empty capture from collapsing to a zero-width
        // image; it never widens output that already has content past it.
        max_col.clamp(MIN_CONTENT_COLS.min(cols), cols)
    }

    fn resolve_cell_colors(&self, cell: &vt100::Cell, theme: &Theme) -> (Rgba<u8>, Rgba<u8>) {
        let mut fg = self.resolve_color(cell.fgcolor(), true, theme);
        let mut bg = self.resolve_color(cell.bgcolor(), false, theme);

        if cell.inverse() {
            std::mem::swap(&mut fg, &mut bg);
        }

        if cell.bold() {
            // Bold + standard color (0-7) should use the bright variant (8-15),
            // matching how GNOME Terminal and most emulators render bold.
            fg = match cell.fgcolor() {
                vt100::Color::Idx(idx) if idx < 8 => theme.palette[(idx + 8) as usize],
                vt100::Color::Default => theme.palette[15], // bold default = bright white
                _ => {
                    // For 256/RGB colors, lighten toward white
                    Rgba([
                        fg[0].saturating_add((255 - fg[0]) / 4),
                        fg[1].saturating_add((255 - fg[1]) / 4),
                        fg[2].saturating_add((255 - fg[2]) / 4),
                        fg[3],
                    ])
                }
            };
        }

        if cell.dim() {
            fg = Rgba([fg[0] / 2, fg[1] / 2, fg[2] / 2, fg[3]]);
        }

        (fg, bg)
    }

    fn resolve_color(&self, color: vt100::Color, is_foreground: bool, theme: &Theme) -> Rgba<u8> {
        match color {
            vt100::Color::Default => {
                if is_foreground {
                    theme.foreground
                } else {
                    theme.background
                }
            }
            vt100::Color::Idx(idx) => {
                if idx < 16 {
                    theme.palette[idx as usize]
                } else if idx < 232 {
                    // 216-color cube
                    let idx = idx - 16;
                    let r = (idx / 36) % 6;
                    let g = (idx / 6) % 6;
                    let b = idx % 6;
                    Rgba([
                        if r == 0 { 0 } else { 55 + 40 * r },
                        if g == 0 { 0 } else { 55 + 40 * g },
                        if b == 0 { 0 } else { 55 + 40 * b },
                        255,
                    ])
                } else {
                    // Grayscale ramp
                    let level = 8 + 10 * (idx - 232);
                    Rgba([level, level, level, 255])
                }
            }
            vt100::Color::Rgb(r, g, b) => Rgba([r, g, b, 255]),
        }
    }

    fn draw_rect(&self, img: &mut RgbaImage, x: u32, y: u32, w: u32, h: u32, color: Rgba<u8>) {
        for dy in 0..h {
            for dx in 0..w {
                let px = x + dx;
                let py = y + dy;
                if px < img.width() && py < img.height() {
                    self.put_pixel_blend(img, px, py, color);
                }
            }
        }
    }

    fn put_pixel_blend(&self, img: &mut RgbaImage, x: u32, y: u32, color: Rgba<u8>) {
        if color[3] == 255 {
            img.put_pixel(x, y, color);
            return;
        }
        if color[3] == 0 {
            return;
        }

        // Proper "source-over" alpha compositing that also computes the
        // resulting alpha channel. The previous implementation forced the
        // output alpha to 255, which turned semi-transparent pixels (such as
        // the drop shadow) into fully opaque ones. Because the shadow is
        // offset down-and-right, that left the top-left rounded corner clean
        // while the other three corners picked up opaque shadow artifacts.
        let bg = img.get_pixel(x, y);
        let src_a = color[3] as f32 / 255.0;
        let dst_a = bg[3] as f32 / 255.0;
        let out_a = src_a + dst_a * (1.0 - src_a);
        if out_a <= 0.0 {
            img.put_pixel(x, y, Rgba([0, 0, 0, 0]));
            return;
        }
        let blend = |sc: u8, dc: u8| -> u8 {
            let v = (sc as f32 * src_a + dc as f32 * dst_a * (1.0 - src_a)) / out_a;
            v.round().clamp(0.0, 255.0) as u8
        };
        let out = Rgba([
            blend(color[0], bg[0]),
            blend(color[1], bg[1]),
            blend(color[2], bg[2]),
            (out_a * 255.0).round().clamp(0.0, 255.0) as u8,
        ]);
        img.put_pixel(x, y, out);
    }

    /// Rasterize and blend a single glyph into `img`.
    ///
    /// This is the one glyph renderer in the codebase: both the terminal grid
    /// (via [`draw_char_with_font`](Self::draw_char_with_font)) and the chrome
    /// title/timestamp text (via [`draw_text_at`](Self::draw_text_at)) go
    /// through it, so they share identical positioning rules:
    ///
    /// * `cell_x` is the left edge of the character cell; the glyph is placed
    ///   at `cell_x + xmin` so its side bearing is respected, unless
    ///   `placement` asks for it to be centered (fallback glyphs).
    /// * `line_top` is the top of the line box; the glyph sits on the shared
    ///   baseline at `line_top + ascent`, offset by its own `ymin`. Using the
    ///   baseline (instead of centering each bitmap) is what keeps descenders
    ///   hanging and stops the per-glyph vertical wobble. `placement` may
    ///   override the ascent so fallback faces share the primary baseline.
    /// * `italic` applies a synthetic shear, used by terminal content.
    /// * `font` may be the regular, bold, or a fallback face; `color`'s alpha
    ///   modulates the glyph coverage and the result is composited source-over.
    #[allow(clippy::too_many_arguments)]
    fn draw_glyph(
        &self,
        img: &mut RgbaImage,
        cell_x: i32,
        line_top: i32,
        ch: char,
        color: Rgba<u8>,
        italic: bool,
        font_size: f32,
        font: &Font,
        placement: GlyphPlacement,
    ) {
        let (metrics, bitmap) = font.rasterize(ch, font_size);
        if bitmap.is_empty() || metrics.width == 0 || metrics.height == 0 {
            return;
        }

        let ascent = placement
            .ascent
            .unwrap_or_else(|| font_ascent(font, font_size));
        let glyph_x = match placement.center_width {
            // Center by *advance*, not by the ink bitmap: a box drawing corner
            // like `┌` only inks the right half of its cell, and centering its
            // bitmap would pull it away from the line it must join. Offsetting
            // the whole advance keeps every glyph's internal geometry intact.
            Some(width) => {
                cell_x
                    + ((width as f32 - metrics.advance_width) / 2.0).round() as i32
                    + metrics.xmin
            }
            None => cell_x + metrics.xmin,
        };
        let glyph_y = line_top + ascent.round() as i32 - metrics.height as i32 - metrics.ymin;

        let shear = |gy: usize| -> i32 {
            if !italic {
                return 0;
            }
            let from_bottom = metrics.height as i32 - gy as i32;
            (from_bottom as f32 * 0.22) as i32
        };

        for gy in 0..metrics.height {
            let dx_italic = shear(gy);
            for gx in 0..metrics.width {
                let coverage = bitmap[gy * metrics.width + gx];
                if coverage == 0 {
                    continue;
                }
                let px = glyph_x + gx as i32 + dx_italic;
                let py = glyph_y + gy as i32;
                if px < 0 || py < 0 {
                    continue;
                }
                let (px, py) = (px as u32, py as u32);
                if px >= img.width() || py >= img.height() {
                    continue;
                }
                let alpha = ((coverage as u32 * color[3] as u32) / 255) as u8;
                self.put_pixel_blend(img, px, py, Rgba([color[0], color[1], color[2], alpha]));
            }
        }
    }

    /// Draw a single terminal cell's character. `x`/`y` are the top-left
    /// corner of the cell in image space.
    ///
    /// `cell_span` is the width in pixels of the box the character occupies -
    /// one cell, or two for a wide (double-width) character - and is used to
    /// center fallback glyphs.
    #[allow(clippy::too_many_arguments)]
    fn draw_char_with_font(
        &self,
        img: &mut RgbaImage,
        fonts: &ThemeFonts,
        x: u32,
        y: u32,
        ch: char,
        color: Rgba<u8>,
        italic: bool,
        font_size: f32,
        font: &ChosenFont<'_>,
        cell_span: u32,
    ) {
        let (render_size, placement) = if font.is_fallback {
            (
                fallback_font_size(font.font, ch, font_size, cell_span),
                GlyphPlacement::fallback(font_ascent(&fonts.font, font_size), cell_span),
            )
        } else {
            (font_size, GlyphPlacement::natural())
        };
        self.draw_glyph(
            img,
            x as i32,
            y as i32,
            ch,
            color,
            italic,
            render_size,
            font.font,
            placement,
        );
    }

    /// Pick the font used to draw `ch`, walking the fallback chain in order:
    /// the primary face (the bold face for a bold cell), then the embedded
    /// JetBrains Mono, then any fonts the theme configured. When nothing
    /// covers the character the primary face is returned, so the terminal
    /// shows its usual missing-glyph behavior rather than silently borrowing
    /// an unrelated glyph.
    fn font_for_char<'f>(
        &self,
        fonts: &'f ThemeFonts,
        ch: char,
        bold: bool,
        font_size: f32,
    ) -> ChosenFont<'f> {
        let primary = match (bold, fonts.font_bold.as_ref()) {
            (true, Some(bold_font)) => bold_font,
            _ => &fonts.font,
        };
        if font_covers(primary, ch, font_size) {
            return ChosenFont {
                font: primary,
                is_fallback: false,
            };
        }
        for font in &fonts.fallback_fonts {
            if font_covers(font, ch, font_size) {
                return ChosenFont {
                    font,
                    is_fallback: true,
                };
            }
        }
        ChosenFont {
            font: primary,
            is_fallback: false,
        }
    }
}

/// Maximum length (in characters) of a generated screenshot base filename.
const MAX_FILENAME_CHARS: usize = 60;

/// Sanitize an arbitrary string (typically a command line) into a safe,
/// descriptive PNG base filename: lowercased, with every run of
/// non-alphanumeric characters collapsed to a single hyphen, trimmed of
/// leading/trailing hyphens, and capped at [`MAX_FILENAME_CHARS`] characters.
/// Empty or all-symbol input yields `"screenshot"`.
fn sanitize_base_name(input: &str) -> String {
    let mut out = String::new();
    let mut pending_hyphen = false;
    for ch in input.chars() {
        if ch.is_ascii_alphanumeric() {
            if pending_hyphen && !out.is_empty() {
                out.push('-');
            }
            pending_hyphen = false;
            out.push(ch.to_ascii_lowercase());
        } else {
            pending_hyphen = true;
        }
    }
    let mut out: String = out.chars().take(MAX_FILENAME_CHARS).collect();
    while out.ends_with('-') {
        out.pop();
    }
    if out.is_empty() {
        "screenshot".to_string()
    } else {
        out
    }
}

/// Build a unique `<base>.png` path in `output_dir`, appending `-2`, `-3`, ...
/// before the extension until an unused name is found.
fn unique_png_path(output_dir: &Path, base: &str) -> PathBuf {
    let first = output_dir.join(format!("{}.png", base));
    if !first.exists() {
        return first;
    }
    let mut n = 2u32;
    loop {
        let candidate = output_dir.join(format!("{}-{}.png", base, n));
        if !candidate.exists() {
            return candidate;
        }
        n += 1;
    }
}

/// Derive a fallback screenshot base name from the process working directory
/// and a command line, as `{cwd_basename} {first_word}` (later sanitized to
/// e.g. `nrs-cargo`). This is only a fallback for when no explicit name is
/// given: callers and agents should prefer a descriptive `output_name`
/// (e.g. `finding-01-sqli`) whenever possible.
pub fn fallback_output_name(cwd: Option<&Path>, command: &str) -> String {
    let dir = cwd
        .and_then(Path::file_name)
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let first = command.split_whitespace().next().unwrap_or("");
    match (dir.trim().is_empty(), first.is_empty()) {
        (false, false) => format!("{} {}", dir, first),
        (true, false) => first.to_string(),
        (false, true) => dir,
        (true, true) => String::new(),
    }
}

fn truncate_title(title: &str) -> String {
    if title.chars().count() <= MAX_TITLE_CHARS {
        return title.to_string();
    }
    format!(
        "{}...",
        title.chars().take(MAX_TITLE_CHARS).collect::<String>()
    )
}

fn is_light(color: Rgba<u8>) -> bool {
    let luminance = 0.2126 * color[0] as f32 + 0.7152 * color[1] as f32 + 0.0722 * color[2] as f32;
    luminance > 150.0
}

fn muted_text_color(theme: &Theme) -> Rgba<u8> {
    if is_light(theme.background) {
        Rgba([0, 0, 0, 128])
    } else {
        Rgba([255, 255, 255, 128])
    }
}

/// Pixel geometry of the terminal portion of a screenshot, worked out before
/// anything is allocated.
#[derive(Debug, Clone, Copy)]
struct ScreenLayout {
    content_rows: u32,
    content_cols: u32,
    cell_w: u32,
    cell_h: u32,
    padding: u32,
    /// Pixel size of the terminal image, padding included.
    width: u32,
    height: u32,
}

/// A run of consecutive cells that share one style and all need the shaper.
///
/// `cols` counts grid columns rather than cells, so the vt100 continuation
/// column of a double-width character is part of the run's span even though it
/// contributes no text of its own.
struct ShapedRunSpan {
    cells: Vec<RunCell>,
    cols: u32,
}

/// Pixel bounds a shaped glyph may paint inside: always the run's own
/// rectangle, so shaping can never leak into a neighbouring cell.
#[derive(Debug, Clone, Copy)]
struct ClipRect {
    x0: i32,
    x1: i32,
    y0: i32,
    y1: i32,
}

/// Pixel geometry of a chrome-framed screenshot, worked out before anything is
/// allocated so [`ChromeMetrics::check_budget`] can refuse an impossible render
/// instead of the allocator aborting on it.
#[derive(Debug, Clone, Copy)]
struct ChromeMetrics {
    radius: u32,
    title_bar: u32,
    /// Extra canvas reserved for the drop shadow; zero when there is none, in
    /// which case the frame layer is the finished image.
    shadow: u32,
    frame_pad: u32,
    bottom_pad: u32,
    frame_w: u32,
    frame_h: u32,
    /// Pixel height of the terminal area inside the frame; the timestamp is
    /// laid out below it.
    term_h: u32,
    /// Final image size.
    width: u32,
    height: u32,
}

impl ChromeMetrics {
    /// `timestamp_reserve` is the height the caller measured for the timestamp
    /// watermark (see [`Renderer::timestamp_reserve`]); it is only used when
    /// the timestamp is actually enabled.
    fn new(chrome: &ChromeOptions, term_w: u32, term_h: u32, timestamp_reserve: u32) -> Self {
        let scale = RENDER_SCALE;
        let radius = if chrome.rounded {
            chrome.radius * scale
        } else {
            0
        };
        let title_bar = match chrome.preset.as_str() {
            "minimal" => 0,
            _ => chrome.title_bar_height * scale,
        };
        let shadow = if chrome.shadow { 16 * scale } else { 0 };
        let frame_pad = chrome.outer_padding * scale;
        // Only a timestamp earns extra space below the terminal, and only as
        // much as the text it has to hold: the terminal image already carries
        // its own symmetric padding, so anything more would show up as a
        // lopsided bottom margin.
        let bottom_pad = if chrome.timestamp {
            frame_pad.max(timestamp_reserve)
        } else {
            frame_pad
        };
        let frame_w = term_w + frame_pad * 2;
        let frame_h = term_h + frame_pad + bottom_pad + title_bar;
        Self {
            radius,
            title_bar,
            shadow,
            frame_pad,
            bottom_pad,
            frame_w,
            frame_h,
            term_h,
            width: frame_w + shadow,
            height: frame_h + shadow,
        }
    }

    /// Refuse a render that would not fit in the memory budget. With a shadow
    /// the frame layer and the canvas it is composited onto are alive at the
    /// same time; without one the frame is the only buffer.
    fn check_budget(&self, screen: &CapturedScreen) -> Result<()> {
        let layers = if self.shadow > 0 { 2 } else { 1 };
        check_render_budget(self.width, self.height, layers, screen)
    }
}

/// Refuse to render an image the machine should not be asked to allocate.
///
/// Retained output is unbounded in practice, so a capture can ask for an image
/// of any size; `layers` is how many full-size RGBA buffers the render holds at
/// once, so the check reflects peak memory rather than just the final PNG. The
/// error names the limit that was actually reached, and the way out: render one
/// end of the capture instead of all of it.
fn check_render_budget(
    width: u32,
    height: u32,
    layers: u64,
    screen: &CapturedScreen,
) -> Result<()> {
    let pixels = u64::from(width) * u64::from(height);
    let bytes = pixels * BYTES_PER_PIXEL * layers;
    let reason = if pixels > MAX_IMAGE_PIXELS {
        format!(
            "{} megapixels, over the {} megapixel limit",
            pixels / 1_000_000,
            MAX_IMAGE_PIXELS / 1_000_000
        )
    } else if bytes > MAX_RENDER_BYTES {
        format!(
            "about {} MB of image buffers, over the {} MB limit",
            bytes / (1024 * 1024),
            MAX_RENDER_BYTES / (1024 * 1024)
        )
    } else {
        return Ok(());
    };
    anyhow::bail!(
        "the capture would render as a {}x{} px image, needing {}: it holds {} lines of \
         output. Narrow it with --head-lines/--tail-lines (head_lines/tail_lines over MCP), \
         or use fewer columns.",
        width,
        height,
        reason,
        screen.size().0
    );
}

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

    /// Parse `data` into a single-screenful capture: no scrollback, so the
    /// capture is exactly the `rows` x `cols` viewport. That is what the
    /// geometry tests below measure; the scrollback-backed behaviour has its
    /// own tests in [`crate::capture`] and below.
    fn screen_of(data: &[u8], rows: u16, cols: u16) -> CapturedScreen {
        CapturedScreen::parse(data, rows, cols, 0)
    }

    #[test]
    fn chrome_options_from_config_respects_enabled_and_preset() {
        let config = ChromeConfig {
            enabled: true,
            preset: "gnome".to_string(),
            title: Some("demo".to_string()),
            timestamp: false,
            shadow: true,
            radius: 12,
            rounded: true,
            outer_padding: 20,
            title_bar_height: 30,
        };

        let options = ChromeOptions::from_config(&config);
        assert!(options.enabled);
        assert_eq!(options.preset, "gnome");
        assert_eq!(options.title.as_deref(), Some("demo"));
        assert!(!options.timestamp);
    }

    #[test]
    fn compose_with_chrome_increases_canvas_size() {
        let renderer = renderer_with_chrome(ChromeOptions {
            enabled: false,
            preset: "none".to_string(),
            title: None,
            timestamp: false,
            shadow: true,
            radius: 14,
            rounded: true,
            outer_padding: 18,
            title_bar_height: 34,
        });

        let terminal = ImageBuffer::from_pixel(100, 50, Rgba([10, 10, 10, 255]));
        let theme = Theme::dark();
        let chrome = ChromeOptions {
            enabled: true,
            preset: "gnome".to_string(),
            title: Some("demo".to_string()),
            timestamp: false,
            shadow: true,
            radius: 14,
            rounded: true,
            outer_padding: 18,
            title_bar_height: 34,
        };

        let result =
            renderer.compose_with_chrome(terminal, &theme, &renderer.default_fonts, &chrome);
        assert!(result.width() > 100);
        assert!(result.height() > 50);
    }

    /// A timestamp is the only thing that earns space below the terminal, and
    /// it earns only as much as the text needs: one line plus a small gap,
    /// never the height of a terminal row.
    #[test]
    fn timestamp_reserves_bottom_padding() {
        let renderer = renderer_with_chrome(ChromeOptions {
            enabled: false,
            preset: "none".to_string(),
            title: None,
            timestamp: false,
            shadow: false,
            radius: 14,
            rounded: true,
            outer_padding: 0,
            title_bar_height: 34,
        });
        let terminal = ImageBuffer::from_pixel(100, 50, Rgba([10, 10, 10, 255]));
        let chrome = ChromeOptions {
            enabled: true,
            preset: "report".to_string(),
            title: None,
            timestamp: true,
            shadow: false,
            radius: 14,
            rounded: true,
            outer_padding: 0,
            title_bar_height: 34,
        };

        let result = renderer.compose_with_chrome(
            terminal,
            &Theme::dark(),
            &renderer.default_fonts,
            &chrome,
        );
        // Chrome metrics are drawn at RENDER_SCALE (2x): title bar 34*2=68 and
        // the timestamp reserves exactly one measured line of watermark text.
        let reserve = renderer.timestamp_reserve(&renderer.default_fonts);
        assert_eq!(result.height(), 50 + 68 + reserve);

        // The reserve is the text plus its gap and nothing else - in
        // particular it is smaller than the blank terminal row that used to
        // pad the bottom of every capture.
        let line_height =
            font_line_height(&renderer.default_fonts.font, renderer.timestamp_font_size()).ceil()
                as u32;
        assert_eq!(reserve, line_height + TIMESTAMP_GAP * RENDER_SCALE * 2);
        assert!(
            reserve
                < renderer.default_fonts.cell_height * RENDER_SCALE
                    + renderer.padding * RENDER_SCALE,
            "the timestamp reserve grew back into a blank terminal row: {reserve}"
        );
    }

    /// Without a timestamp the frame adds nothing below the terminal beyond the
    /// outer padding, so the terminal's own symmetric padding is the whole
    /// bottom margin.
    #[test]
    fn no_timestamp_reserves_no_extra_bottom_space() {
        let renderer = bare_renderer();
        let base = ChromeOptions {
            enabled: true,
            preset: "report".to_string(),
            title: None,
            timestamp: false,
            shadow: false,
            radius: 14,
            rounded: true,
            outer_padding: 0,
            title_bar_height: 34,
        };
        let with_stamp = ChromeOptions {
            timestamp: true,
            ..base.clone()
        };

        let compose = |chrome: &ChromeOptions| {
            renderer.compose_with_chrome(
                ImageBuffer::from_pixel(100, 50, Rgba([10, 10, 10, 255])),
                &Theme::dark(),
                &renderer.default_fonts,
                chrome,
            )
        };

        let plain = compose(&base);
        assert_eq!(plain.height(), 50 + 34 * RENDER_SCALE);
        assert_eq!(
            compose(&with_stamp).height() - plain.height(),
            renderer.timestamp_reserve(&renderer.default_fonts)
        );
    }

    /// The timestamp watermark must sit entirely inside the image it is drawn
    /// into: the reserve is measured from the same font metrics the text is
    /// drawn with, so no glyph can spill past the bottom edge.
    #[test]
    fn timestamp_pixels_stay_inside_the_image() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let theme = Theme::dark();
        let chrome = ChromeOptions {
            enabled: true,
            preset: "report".to_string(),
            title: None,
            timestamp: true,
            shadow: false,
            radius: 0,
            rounded: false,
            outer_padding: 0,
            title_bar_height: 34,
        };
        let captured = screen_of(b"hello", 6, 40);
        let img = renderer
            .render_to_image(
                &captured,
                &theme,
                &renderer.default_fonts,
                &chrome,
                None,
                true,
            )
            .unwrap();

        let layout = renderer.screen_layout(&captured, &renderer.default_fonts, true);
        let reserve = renderer.timestamp_reserve(&renderer.default_fonts);
        assert_eq!(
            img.height(),
            layout.height + 34 * RENDER_SCALE + reserve,
            "the frame reserved something other than the timestamp strip"
        );

        // Ink from the watermark exists inside the reserved strip...
        let strip_top = img.height() - reserve;
        let inked_rows: Vec<u32> = (strip_top..img.height())
            .filter(|&y| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background))
            .collect();
        assert!(
            !inked_rows.is_empty(),
            "the timestamp was not drawn in its reserved strip"
        );
        // ...and it is clear of both edges of the strip, so it is neither
        // clipped nor jammed against the last row of output.
        assert!(
            *inked_rows.first().unwrap() > strip_top,
            "timestamp ink touches the top of its reserve"
        );
        assert!(
            *inked_rows.last().unwrap() < img.height() - 1,
            "timestamp ink touches the bottom edge of the image"
        );
    }

    /// The bottom margin of a one-line capture matches its top margin: no
    /// blank terminal row is padded in below the text.
    ///
    /// Measured on a row of colored background rather than on glyphs, because
    /// a background block fills its cell exactly - so the ink band *is* the
    /// terminal row and the gap on either side of it is the padding itself.
    #[test]
    fn a_single_line_has_matching_top_and_bottom_padding() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        let captured = screen_of(b"\x1b[41m     \x1b[0m", 24, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.height(), cell_h + padding * 2);

        let inked = |y: u32| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background);
        let top = (0..img.height())
            .find(|&y| inked(y))
            .expect("content drawn");
        let bottom = (0..img.height()).rev().find(|&y| inked(y)).unwrap();
        let top_margin = top;
        let bottom_margin = img.height() - 1 - bottom;
        assert_eq!(top_margin, padding);
        assert!(
            (top_margin as i32 - bottom_margin as i32).abs() <= 1,
            "asymmetric vertical padding: {top_margin}px above, {bottom_margin}px below"
        );
    }

    /// A one-line capture of ordinary text is one cell tall plus its padding:
    /// the blank row the terminal leaves the cursor on is not drawn, and the
    /// glyphs still sit inside that single cell, so the padding above and below
    /// them is untouched on both sides.
    #[test]
    fn a_single_line_of_text_is_exactly_one_cell_tall() {
        let renderer = renderer_with_measured_cells();
        let theme = Theme::dark();
        let captured = screen_of(b"hello, jq!", 24, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.height(), cell_h + padding * 2);

        let inked = |y: u32| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background);
        let top = (0..img.height()).find(|&y| inked(y)).expect("text drawn");
        let bottom = (0..img.height()).rev().find(|&y| inked(y)).unwrap();
        assert!(
            top >= padding && bottom < padding + cell_h,
            "glyph ink escaped its cell: rows {top}..={bottom} of {}",
            img.height()
        );
    }

    /// Multi-line output ends at its last line: there is no full blank cell of
    /// terminal background between the last glyph row and the bottom padding.
    #[test]
    fn multiple_lines_leave_no_blank_row_below_the_last_line() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        let captured = screen_of(b"one\r\ntwo\r\nthree", 24, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.height(), 3 * cell_h + padding * 2);

        let inked = |y: u32| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background);
        let bottom = (0..img.height()).rev().find(|&y| inked(y)).unwrap();
        assert!(
            img.height() - 1 - bottom < padding + cell_h,
            "a blank terminal row was kept below the last line"
        );
    }

    /// An empty capture still renders: it collapses to a single padded row
    /// rather than to a zero-height PNG.
    #[test]
    fn an_empty_capture_still_renders_one_row() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        let captured = screen_of(b"", 24, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.height(), cell_h + padding * 2);
        assert_eq!(img.width(), cell_w + padding * 2);
    }

    /// Height trimming reads the terminal buffer, so a final row that is only
    /// a colored background block is content and is kept.
    #[test]
    fn height_trim_keeps_a_trailing_styled_row() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        // "hi", then a row that holds nothing but a green background run.
        let captured = screen_of(b"hi\r\n\x1b[42m    \x1b[0m", 24, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.height(), 2 * cell_h + padding * 2);
        assert_ne!(
            *img.get_pixel(padding + 2, padding + cell_h + cell_h / 2),
            theme.background,
            "the trailing styled row was trimmed away"
        );
    }

    /// Chrome does not change how much terminal is drawn: framed and bare
    /// renders of the same capture hold the same terminal image, and the frame
    /// only adds its own title bar and padding around it.
    #[test]
    fn chrome_and_bare_paths_trim_height_identically() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let theme = Theme::dark();
        let captured = screen_of(b"one\r\ntwo", 24, 80);

        let bare_chrome = ChromeOptions {
            enabled: false,
            preset: "none".to_string(),
            title: None,
            timestamp: false,
            shadow: false,
            radius: 0,
            rounded: false,
            outer_padding: 0,
            title_bar_height: 0,
        };
        let framed = ChromeOptions {
            enabled: true,
            preset: "gnome".to_string(),
            title: Some("demo".to_string()),
            timestamp: false,
            shadow: false,
            radius: 0,
            rounded: false,
            outer_padding: 0,
            title_bar_height: 34,
        };

        let render = |chrome: &ChromeOptions| {
            renderer
                .render_to_image(
                    &captured,
                    &theme,
                    &renderer.default_fonts,
                    chrome,
                    None,
                    true,
                )
                .unwrap()
        };

        let bare = render(&bare_chrome);
        let with_chrome = render(&framed);
        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(bare.height(), 2 * cell_h + padding * 2);
        assert_eq!(with_chrome.height(), bare.height() + 34 * RENDER_SCALE);
        assert_eq!(with_chrome.width(), bare.width());
    }

    #[test]
    fn long_titles_are_truncated_on_character_boundaries() {
        let title = "é".repeat(MAX_TITLE_CHARS + 1);
        let truncated = truncate_title(&title);
        assert_eq!(truncated.chars().count(), MAX_TITLE_CHARS + 3);
        assert!(truncated.ends_with("..."));
    }

    #[test]
    fn round_image_corners_makes_corners_transparent_but_keeps_body() {
        let renderer = bare_renderer();
        let mut img = ImageBuffer::from_pixel(40, 40, Rgba([20, 20, 20, 255]));
        renderer.round_image_corners(&mut img, 10);
        // The extreme corner sits outside the arc and becomes transparent.
        assert_eq!(img.get_pixel(0, 0)[3], 0);
        assert_eq!(img.get_pixel(39, 39)[3], 0);
        // Edge midpoints and the center are not in a corner: fully opaque.
        assert_eq!(img.get_pixel(20, 0)[3], 255);
        assert_eq!(img.get_pixel(0, 20)[3], 255);
        assert_eq!(img.get_pixel(20, 20)[3], 255);
        // RGB is preserved even where alpha is faded.
        assert_eq!([img.get_pixel(0, 0)[0], img.get_pixel(0, 0)[1]], [20, 20]);
    }

    #[test]
    fn round_image_corners_is_noop_for_zero_radius() {
        let renderer = bare_renderer();
        let mut img = ImageBuffer::from_pixel(20, 20, Rgba([10, 10, 10, 255]));
        renderer.round_image_corners(&mut img, 0);
        assert_eq!(img.get_pixel(0, 0)[3], 255);
    }

    #[test]
    fn bare_render_rounds_corners_when_enabled_and_squares_when_disabled() {
        let mut renderer = bare_renderer();
        // Give the (chrome-less) default a real corner radius to round against.
        renderer.default_chrome.radius = 8;
        let theme = Theme::dark();
        let captured = screen_of(b"hello world", 3, 20);
        let screen = &captured;

        renderer.default_chrome.rounded = true;
        let rounded = renderer
            .render_to_image(
                screen,
                &theme,
                &renderer.default_fonts,
                &renderer.default_chrome,
                None,
                false,
            )
            .unwrap();
        assert_eq!(rounded.get_pixel(0, 0)[3], 0, "rounded: corner transparent");

        renderer.default_chrome.rounded = false;
        let square = renderer
            .render_to_image(
                screen,
                &theme,
                &renderer.default_fonts,
                &renderer.default_chrome,
                None,
                false,
            )
            .unwrap();
        assert_eq!(square.get_pixel(0, 0)[3], 255, "square: corner opaque");
    }

    #[test]
    fn chrome_options_default_rounded_is_true() {
        let options = ChromeOptions::from_config(&ChromeConfig::default());
        assert!(options.rounded);
    }

    #[test]
    fn title_uses_fixed_monospace_cell_advance() {
        // The wobble fix hinges on every glyph advancing by the same fixed
        // cell width, so `text_width` must equal char_count * cell_advance and
        // be identical for narrow vs. wide characters of equal length.
        let r = bare_renderer();
        let size = 20.0;
        let one_m = r.text_width(&r.default_fonts, "M", size);
        assert!(one_m > 0);
        assert_eq!(
            r.text_width(&r.default_fonts, "MMMMMMMMMM", size),
            one_m * 10
        );
        assert_eq!(
            r.text_width(&r.default_fonts, "iiiiiiiiii", size),
            one_m * 10
        );
        assert_eq!(r.text_width(&r.default_fonts, "Mi.lWx/9-", size), one_m * 9);
    }

    /// Chrome text (window title *and* timestamp watermark, which share
    /// [`Renderer::draw_text_at`]) must sit on one baseline: flat and round
    /// glyphs align at the bottom while a descender hangs below it. Centering
    /// each glyph bitmap instead - the old behavior - made descenders sit *on*
    /// the baseline and gave titles a visible wobble.
    #[test]
    fn chrome_text_sits_on_a_shared_baseline() {
        let r = bare_renderer();
        let size = 24.0;
        let mut img: RgbaImage = ImageBuffer::from_pixel(400, 80, Rgba([0, 0, 0, 255]));
        r.draw_text_at(
            &mut img,
            &r.default_fonts,
            10,
            40,
            "oxy",
            Rgba([255, 255, 255, 255]),
            size,
        );

        // Bottom-most inked row per glyph cell (cells are a fixed advance wide).
        let advance = r.text_width(&r.default_fonts, "M", size) as i32;
        let bottom_of = |cell: i32| -> u32 {
            let (x0, x1) = (10 + cell * advance, 10 + (cell + 1) * advance);
            (0..img.height())
                .rfind(|&y| {
                    (x0.max(0) as u32..(x1.max(0) as u32).min(img.width()))
                        .any(|x| img.get_pixel(x, y)[0] > 40)
                })
                .expect("glyph should have been drawn")
        };

        let (o, x, y) = (bottom_of(0), bottom_of(1), bottom_of(2));
        // 'o' and 'x' share the baseline (round glyphs may overshoot by 1px).
        assert!(
            o.abs_diff(x) <= 1,
            "flat and round glyphs must share a baseline: o={o}, x={x}"
        );
        // 'y' descends below it.
        assert!(
            y > o + 1,
            "descender must hang below the baseline: y={y}, o={o}"
        );
    }

    /// The timestamp watermark is drawn right-aligned through the same routine,
    /// so it must end at the requested edge and share that one baseline.
    #[test]
    fn timestamp_is_right_aligned_on_the_same_baseline() {
        let r = bare_renderer();
        let size = 20.0;
        let text = "2026-08-26 01:38:03 UTC";
        let right_x = 380u32;
        let mut img: RgbaImage = ImageBuffer::from_pixel(400, 60, Rgba([0, 0, 0, 255]));
        r.draw_text_right_aligned(
            &mut img,
            &r.default_fonts,
            right_x,
            30,
            text,
            Rgba([255, 255, 255, 255]),
            size,
        );

        let advance = r.text_width(&r.default_fonts, "M", size);
        let start_x = right_x - r.text_width(&r.default_fonts, text, size);

        // Per character cell, the top and bottom inked rows.
        let mut extents: Vec<(usize, u32, u32)> = Vec::new();
        for (cell, _) in text.chars().enumerate().filter(|(_, c)| *c != ' ') {
            let x0 = start_x + cell as u32 * advance;
            let x1 = (x0 + advance).min(img.width());
            let rows: Vec<u32> = (0..img.height())
                .filter(|&y| (x0..x1).any(|x| img.get_pixel(x, y)[0] > 40))
                .collect();
            assert!(!rows.is_empty(), "cell {cell} was not drawn");
            extents.push((cell, rows[0], *rows.last().unwrap()));
        }

        // Digits and letters (the tall glyphs) must share one baseline; round
        // shapes may overshoot it by a single pixel.
        let tallest = extents.iter().map(|(_, t, b)| b - t).max().unwrap();
        let full: Vec<u32> = extents
            .iter()
            .filter(|(_, t, b)| b - t >= tallest - 1)
            .map(|(_, _, b)| *b)
            .collect();
        let (lo, hi) = (*full.iter().min().unwrap(), *full.iter().max().unwrap());
        assert!(
            hi - lo <= 1,
            "timestamp glyphs drifted off the baseline: {lo} vs {hi}"
        );

        // Hyphens and colons sit above the baseline, proving glyphs are placed
        // by their own metrics rather than centered in the line box.
        let hyphen = extents
            .iter()
            .find(|(cell, _, _)| text.chars().nth(*cell) == Some('-'))
            .expect("hyphen cell");
        assert!(
            hyphen.2 < lo,
            "a hyphen must not reach the baseline: {} vs {lo}",
            hyphen.2
        );

        // The run ends at the requested right edge and starts a text width back.
        let inked: Vec<u32> = (0..img.width())
            .filter(|&x| (0..img.height()).any(|y| img.get_pixel(x, y)[0] > 40))
            .collect();
        assert!(*inked.last().unwrap() < right_x);
        assert!(right_x - *inked.last().unwrap() <= advance);
        assert!(inked[0] >= start_x);
    }

    #[test]
    fn sample_background_prefers_opaque_pane_color() {
        let mut img = ImageBuffer::from_pixel(20, 20, Rgba([12, 34, 56, 255]));
        // A transparent (rounded) corner must not be chosen.
        img.put_pixel(0, 0, Rgba([0, 0, 0, 0]));
        assert_eq!(
            sample_background(&img, Rgba([9, 9, 9, 255])),
            Rgba([12, 34, 56, 255])
        );
        // A fully transparent image falls back to the provided default.
        let clear = ImageBuffer::from_pixel(20, 20, Rgba([0, 0, 0, 0]));
        assert_eq!(
            sample_background(&clear, Rgba([9, 9, 9, 255])),
            Rgba([9, 9, 9, 255])
        );
    }

    #[test]
    fn normalize_newlines_converts_bare_lf_and_is_idempotent() {
        use std::borrow::Cow;
        // Bare LF (piped / redirected output) is upgraded to CRLF.
        assert_eq!(
            normalize_newlines(b"a\nb\n").as_ref(),
            b"a\r\nb\r\n".as_slice()
        );
        // Existing CRLF (PTY output from `exec`) is untouched and not cloned.
        assert!(matches!(
            normalize_newlines(b"a\r\nb\r\n"),
            Cow::Borrowed(_)
        ));
        // Data with no newline at all is borrowed unchanged.
        assert!(matches!(
            normalize_newlines(b"no newline"),
            Cow::Borrowed(_)
        ));
        // A leading LF is handled without underflow.
        assert_eq!(normalize_newlines(b"\nx").as_ref(), b"\r\nx".as_slice());
    }

    /// The bundled JetBrains Mono with fixed 8x16 cell metrics, used as the
    /// single font chain of the test renderers below.
    fn test_fonts() -> ThemeFonts {
        ThemeFonts {
            font: Font::from_bytes(
                std::fs::read("fonts/JetBrainsMono-Regular.ttf").expect("font present"),
                FontSettings::default(),
            )
            .expect("font parse"),
            font_bold: None,
            fallback_fonts: Vec::new(),
            cell_width: 8,
            cell_height: 16,
            // Explicit fonts only: a unit test must not render differently
            // depending on what the machine running it has installed.
            shaping: ShapingEngine::new(
                vec![FontSource::Embedded(EMBEDDED_FONT)],
                ShapingOptions::deterministic(),
            ),
        }
    }

    /// A renderer with one font chain and the given chrome defaults.
    fn renderer_with_chrome(default_chrome: ChromeOptions) -> Renderer {
        Renderer {
            theme_fonts: HashMap::new(),
            default_fonts: Arc::new(test_fonts()),
            font_size: 16.0,
            themes: HashMap::new(),
            default_theme: "dark".to_string(),
            default_chrome,
            padding: 16,
            max_scrollback_lines: crate::capture::DEFAULT_MAX_SCROLLBACK_LINES,
        }
    }

    fn bare_renderer() -> Renderer {
        renderer_with_chrome(ChromeOptions {
            enabled: false,
            preset: "none".to_string(),
            title: None,
            timestamp: false,
            shadow: false,
            radius: 0,
            rounded: true,
            outer_padding: 0,
            title_bar_height: 0,
        })
    }

    /// A bare renderer whose cell metrics are measured from the embedded font,
    /// the way [`Renderer::new`] computes them, instead of the fixed 8x16 grid
    /// [`test_fonts`] hard-codes. Tests that look at where glyph ink lands
    /// inside its cell need the real numbers.
    fn renderer_with_measured_cells() -> Renderer {
        let fonts = ThemeFonts::load(
            &FontChainSpec {
                primary: None,
                bold: None,
                fallbacks: Vec::new(),
            },
            16.0,
            &ShapingOptions::deterministic(),
        )
        .expect("the embedded font loads");
        let mut renderer = bare_renderer();
        renderer.default_fonts = Arc::new(fonts);
        renderer
    }

    /// Width trimming must leave exactly the renderer's own padding to the
    /// right of the last glyph - the same gap as on the left - rather than a
    /// handful of spare cells or the whole unused terminal width.
    #[test]
    fn width_trim_leaves_the_same_padding_on_both_sides() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        let cols = 120u16;
        // Fills 92% of the terminal: wide enough that an earlier "close
        // enough to full width" shortcut would have kept all 120 columns.
        let used = 110usize;
        let captured = screen_of("x".repeat(used).as_bytes(), 4, cols);
        let screen = &captured;

        let img = renderer
            .render_screen(screen, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.width(), used as u32 * cell_w + padding * 2);

        // The last cell still carries ink, so nothing was clipped, and the
        // margins on either side of the text match to within a cell.
        assert!(
            ink_in_columns(
                &img,
                padding + (used as u32 - 1) * cell_w,
                padding + used as u32 * cell_w
            ) > 0,
            "the last column of text was trimmed away"
        );
        let bg = theme.background;
        let inked = |x: u32| (0..img.height()).any(|y| *img.get_pixel(x, y) != bg);
        let left = (0..img.width()).find(|&x| inked(x)).expect("ink");
        let right = (0..img.width()).rev().find(|&x| inked(x)).expect("ink");
        let right_margin = img.width() - 1 - right;
        assert!(
            right_margin >= 1,
            "anti-aliased glyph edge touches the right border"
        );
        assert!(
            (left as i32 - right_margin as i32).unsigned_abs() <= cell_w,
            "asymmetric margins: {left}px on the left, {right_margin}px on the right"
        );
    }

    /// The trim bound is taken from the terminal buffer, so a styled cell with
    /// no text (a colored background block) still counts as content.
    #[test]
    fn width_trim_keeps_trailing_styled_cells() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        // "hi" then a green background run of four blank cells.
        let captured = screen_of(b"hi\x1b[42m    \x1b[0m", 4, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.width(), 6 * cell_w + padding * 2);
        assert_ne!(
            *img.get_pixel(padding + 5 * cell_w + cell_w / 2, padding + 2),
            theme.background,
            "the trailing styled cell was trimmed away"
        );
    }

    /// A double-width character owns a blank vt100 continuation cell; trimming
    /// must keep it so the glyph is not sliced down the middle.
    #[test]
    fn width_trim_keeps_a_wide_characters_continuation_cell() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        let captured = screen_of("ab\u{4f60}".as_bytes(), 4, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.width(), 4 * cell_w + padding * 2);
    }

    /// Trimming is opt-out: `auto_crop = false` still renders the full
    /// terminal width.
    #[test]
    fn width_trim_can_be_disabled() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        let captured = screen_of(b"hi", 4, 80);
        let img = renderer
            .render_screen(&captured, &theme, &renderer.default_fonts, None, false)
            .unwrap();

        let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        assert_eq!(img.width(), 80 * cell_w + padding * 2);
    }

    #[test]
    fn redaction_masks_sensitive_cells_in_rendered_image() {
        use crate::redaction::{RedactionConfig, RedactionEngine};

        let renderer = bare_renderer();
        let theme = Theme::dark();
        let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();

        let captured = screen_of(b"ip 10.20.30.40 up", 3, 40);
        let screen = &captured;

        let map = engine.redact_screen(screen, None);
        assert!(!map.is_empty(), "expected the IPv4 address to be redacted");

        let redacted = renderer
            .render_screen(screen, &theme, &renderer.default_fonts, Some(&map), true)
            .unwrap();
        let plain = renderer
            .render_screen(screen, &theme, &renderer.default_fonts, None, true)
            .unwrap();

        // "[IP]" labels columns 3-6; sample a later plain-block column so we
        // land on solid redaction red rather than a label glyph.
        let scale = 2u32;
        let cell_w = renderer.default_fonts.cell_width * scale;
        let cell_h = renderer.default_fonts.cell_height * scale;
        let padding = renderer.padding * scale;
        let px = 10 * cell_w + padding + cell_w / 2;
        let py = padding + cell_h / 2;

        assert_eq!(
            *redacted.get_pixel(px, py),
            REDACT_BG,
            "redacted cell should be painted red"
        );
        assert_ne!(
            *plain.get_pixel(px, py),
            REDACT_BG,
            "un-redacted render should not contain redaction red"
        );
    }

    #[test]
    fn render_bytes_scrubs_plain_text_and_reports_audit() {
        use crate::redaction::{RedactionConfig, RedactionEngine};

        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());

        let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
        let request = RedactionRequest {
            engine: &engine,
            rules: None,
        };

        let out_dir = std::path::Path::new("target/redaction-test-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let secret = b"host 203.0.113.55 admin@example.com\n";
        let (path, plain_text, audit, _meta) = renderer
            .render_bytes(
                secret,
                40,
                3,
                out_dir,
                Some("redaction test"),
                Some("dark"),
                None,
                Some(&request),
                TextOptions {
                    strip_ansi: false,
                    redact_text: true,
                    embed_description: true,
                    from_screen: false,
                },
                true,
            )
            .unwrap();

        // With redact_text = true the returned text must not leak values.
        assert!(!plain_text.contains("203.0.113.55"));
        assert!(!plain_text.contains("admin@example.com"));
        assert!(plain_text.contains('\u{2588}'));

        // The rendered PNG must not embed the sensitive characters as glyphs;
        // verify at least by confirming redaction red is present in the file.
        let img = image::open(&path).unwrap().to_rgba8();
        let has_red = img.pixels().any(|p| *p == REDACT_BG);
        assert!(has_red, "rendered PNG should contain redaction blocks");

        // Audit reports counts but never values.
        assert!(audit.iter().any(|(name, _)| name == "ipv4"));
        assert!(audit.iter().any(|(name, _)| name == "email"));

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn render_bytes_default_keeps_original_text_but_redacts_image() {
        use crate::redaction::{RedactionConfig, RedactionEngine};

        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());

        let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
        let request = RedactionRequest {
            engine: &engine,
            rules: None,
        };

        let out_dir = std::path::Path::new("target/redaction-default-out");
        std::fs::create_dir_all(out_dir).unwrap();

        // Default TextOptions: image is redacted, but the returned text keeps
        // the original (unredacted) values so an agent can inspect them.
        let secret = b"host 203.0.113.55 here\n";
        let (path, plain_text, audit, _meta) = renderer
            .render_bytes(
                secret,
                40,
                3,
                out_dir,
                Some("default redaction test"),
                Some("dark"),
                None,
                Some(&request),
                TextOptions::default(),
                true,
            )
            .unwrap();

        assert!(
            plain_text.contains("203.0.113.55"),
            "default text should keep original value: {}",
            plain_text
        );
        assert!(!plain_text.contains('\u{2588}'));
        assert!(audit.iter().any(|(name, _)| name == "ipv4"));

        // The PNG is still redacted.
        let img = image::open(&path).unwrap().to_rgba8();
        assert!(img.pixels().any(|p| *p == REDACT_BG));

        std::fs::remove_file(&path).ok();
    }

    /// Read the PNG `iTXt` chunk stored under `Description`, if any.
    fn png_description(path: &std::path::Path) -> Option<String> {
        let file = std::io::BufReader::new(std::fs::File::open(path).unwrap());
        let decoder = png::Decoder::new(file);
        let mut reader = decoder.read_info().unwrap();
        // `iTXt` chunks may trail the image data, so drain the frame first.
        let mut buf = vec![0; reader.output_buffer_size().unwrap()];
        reader.next_frame(&mut buf).unwrap();
        reader
            .info()
            .utf8_text
            .iter()
            .find(|chunk| chunk.keyword == "Description")
            .map(|chunk| chunk.get_text().expect("iTXt text should decode"))
    }

    #[test]
    fn png_embeds_terminal_text_as_description() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/description-test-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let (path, _text, _audit, _meta) = renderer
            .render_bytes(
                b"hello accessible world\n",
                40,
                3,
                out_dir,
                Some("description on"),
                Some("dark"),
                None,
                None,
                TextOptions {
                    embed_description: true,
                    ..TextOptions::default()
                },
                true,
            )
            .unwrap();
        let description = png_description(&path).expect("Description chunk missing");
        assert!(
            description.contains("hello accessible world"),
            "unexpected description: {:?}",
            description
        );
        std::fs::remove_file(&path).ok();

        // Opt-out writes no metadata at all.
        let (path, _text, _audit, _meta) = renderer
            .render_bytes(
                b"hello accessible world\n",
                40,
                3,
                out_dir,
                Some("description off"),
                Some("dark"),
                None,
                None,
                TextOptions::default(),
                true,
            )
            .unwrap();
        assert_eq!(png_description(&path), None);
        std::fs::remove_file(&path).ok();
    }

    /// The embedded description must never carry a value the image redacts.
    #[test]
    fn embedded_description_is_redacted() {
        use crate::redaction::{RedactionConfig, RedactionEngine};

        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
        let request = RedactionRequest {
            engine: &engine,
            rules: None,
        };
        let out_dir = std::path::Path::new("target/description-test-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let (path, _text, _audit, _meta) = renderer
            .render_bytes(
                b"key AKIAIOSFODNN7EXAMPLE end\n",
                60,
                3,
                out_dir,
                Some("description redacted"),
                Some("dark"),
                None,
                Some(&request),
                TextOptions {
                    embed_description: true,
                    ..TextOptions::default()
                },
                true,
            )
            .unwrap();

        let description = png_description(&path).expect("Description chunk missing");
        assert!(
            !description.contains("AKIAIOSFODNN7EXAMPLE"),
            "description leaked a redacted secret: {:?}",
            description
        );
        assert!(description.contains("key "));
        // Redaction blocks survive verbatim: `iTXt` carries UTF-8, so the
        // masked span reads as the same `█` run the image draws.
        assert!(
            description.contains("\u{2588}\u{2588}\u{2588}\u{2588}"),
            "got: {:?}",
            description
        );
        std::fs::remove_file(&path).ok();
    }

    /// The embedded description must survive non-Latin-1 terminal output:
    /// `bat`/`tree` box drawing, check marks, Greek, and CJK all have to come
    /// back out of the PNG byte-for-byte, with no `?` transliteration and no
    /// U+FFFD replacement.
    #[test]
    fn embedded_description_preserves_unicode() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/description-test-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let unicode = "\u{2500} \u{2502} \u{250c} \u{2713} \u{3bb} \u{6f22}";
        let source = format!("{}\n", unicode);

        let (path, _text, _audit, _meta) = renderer
            .render_bytes(
                source.as_bytes(),
                40,
                3,
                out_dir,
                Some("description unicode"),
                Some("dark"),
                None,
                None,
                TextOptions {
                    embed_description: true,
                    ..TextOptions::default()
                },
                true,
            )
            .unwrap();

        let description = png_description(&path).expect("Description chunk missing");
        assert!(
            description.contains(unicode),
            "unicode did not round-trip: {:?}",
            description
        );
        assert!(
            !description.contains('?') && !description.contains('\u{fffd}'),
            "unicode was transliterated or replaced: {:?}",
            description
        );
        std::fs::remove_file(&path).ok();
    }

    /// Control characters are dropped, newlines are kept, and the cap
    /// truncates on a character boundary (never mid-codepoint).
    #[test]
    fn description_text_chunk_sanitizes_and_truncates_on_char_boundary() {
        assert_eq!(description_text_chunk("a\u{7}b\u{1b}c\nd\n\n"), "abc\nd");

        // Every character is 3 bytes, so the cap lands mid-character unless
        // truncation is boundary-aware.
        let long = "\u{6f22}".repeat(MAX_DESCRIPTION_BYTES);
        let capped = description_text_chunk(&long);
        assert!(capped.len() <= MAX_DESCRIPTION_BYTES);
        assert!(capped.chars().all(|c| c == '\u{6f22}'));
        assert_eq!(capped.len() % '\u{6f22}'.len_utf8(), 0);
    }

    #[test]
    fn parse_hex_color_rejects_non_ascii_input() {
        // Six *bytes*, but slicing them would split a UTF-8 character.
        assert!(parse_hex_color("#abc\u{20ac}").is_err());
        assert!(parse_hex_color("#zzzzzz").is_err());
        assert_eq!(parse_hex_color("#1e1e1e").unwrap(), Rgba([30, 30, 30, 255]));
    }

    #[test]
    fn sanitize_base_name_derives_readable_slugs() {
        assert_eq!(sanitize_base_name("ls -la"), "ls-la");
        assert_eq!(sanitize_base_name("whoami uname -a"), "whoami-uname-a");
        // Leading/trailing/duplicate separators collapse and trim.
        assert_eq!(sanitize_base_name("  git   status!! "), "git-status");
        // All-symbol / empty input falls back to a generic name.
        assert_eq!(sanitize_base_name("///"), "screenshot");
        assert_eq!(sanitize_base_name(""), "screenshot");
        // Length is capped and never ends on a hyphen.
        let long = "a ".repeat(80);
        let slug = sanitize_base_name(&long);
        assert!(slug.chars().count() <= 60);
        assert!(!slug.ends_with('-'));
    }

    #[test]
    fn fallback_output_name_combines_cwd_and_first_word() {
        use std::path::Path;
        assert_eq!(
            fallback_output_name(Some(Path::new("/home/adam/Desktop/nrs")), "cargo test"),
            "nrs cargo"
        );
        assert_eq!(
            fallback_output_name(Some(Path::new("/home/adam/Desktop/nrs/src")), "ls -la"),
            "src ls"
        );
        // Missing cwd or command degrades gracefully.
        assert_eq!(fallback_output_name(None, "git log --oneline"), "git");
        assert_eq!(
            fallback_output_name(Some(Path::new("/tmp/work")), ""),
            "work"
        );
        assert_eq!(fallback_output_name(None, ""), "");
    }

    #[test]
    fn unique_png_path_appends_numeric_suffixes() {
        let dir = std::path::Path::new("target/unique-name-test");
        std::fs::create_dir_all(dir).unwrap();
        // Clean any leftovers from a previous run.
        for name in ["cmd.png", "cmd-2.png", "cmd-3.png"] {
            std::fs::remove_file(dir.join(name)).ok();
        }

        let first = unique_png_path(dir, "cmd");
        assert_eq!(first, dir.join("cmd.png"));
        std::fs::write(&first, b"x").unwrap();

        let second = unique_png_path(dir, "cmd");
        assert_eq!(second, dir.join("cmd-2.png"));
        std::fs::write(&second, b"x").unwrap();

        let third = unique_png_path(dir, "cmd");
        assert_eq!(third, dir.join("cmd-3.png"));

        for name in ["cmd.png", "cmd-2.png", "cmd-3.png"] {
            std::fs::remove_file(dir.join(name)).ok();
        }
    }

    // ---------------------------------------------------------------------
    // Font fallback
    // ---------------------------------------------------------------------

    /// Stand-in for a real primary font (MonoLisa and friends) that only
    /// covers printable ASCII: no box drawing, no symbols, no CJK.
    const LIMITED_PRIMARY: &str = "tests/fixtures/limited-ascii.ttf";
    /// Stand-in for a user-configured fallback font (WenQuanYi Zen Hei and
    /// friends): a single CJK character and nothing else.
    const CJK_FALLBACK: &str = "tests/fixtures/cjk-fallback.ttf";

    /// Box drawing, symbol, and Greek characters `bat`/`batcat` frames use and
    /// MonoLisa does not ship.
    const FALLBACK_CHARS: [char; 5] = ['\u{2500}', '\u{2502}', '\u{250c}', '\u{2713}', '\u{3bb}'];

    fn renderer_with(primary: Option<&str>, fallbacks: &[&str]) -> Renderer {
        renderer_with_shaping(primary, fallbacks, ShapingOptions::deterministic())
    }

    /// [`renderer_with`] with the shaped path configured explicitly.
    ///
    /// Every font test uses [`ShapingOptions::deterministic`] so the result
    /// depends only on the fixtures in this repository: automatic system font
    /// fallback is a real feature, but a test that asserts on it would assert
    /// on whatever the machine running it happens to have installed.
    fn renderer_with_shaping(
        primary: Option<&str>,
        fallbacks: &[&str],
        shaping: ShapingOptions,
    ) -> Renderer {
        let fallbacks: Vec<PathBuf> = fallbacks.iter().map(PathBuf::from).collect();
        Renderer::new_with_shaping(
            &FontSelection {
                font_override: primary.map(PathBuf::from),
                font_bold_override: None,
                global_font: None,
                global_fallback_fonts: fallbacks,
            },
            16.0,
            &HashMap::new(),
            "dark",
            &ChromeConfig::default(),
            RendererOptions::default(),
            shaping,
        )
        .expect("renderer builds")
    }

    /// Render `text` through the normal terminal path and return the image.
    fn render_line(renderer: &Renderer, text: &str, cols: u16) -> RgbaImage {
        let captured = screen_of(text.as_bytes(), 2, cols);
        renderer
            .render_screen(
                &captured,
                &Theme::dark(),
                &renderer.default_fonts,
                None,
                false,
            )
            .expect("render")
    }

    /// Count pixels that differ from the theme background, i.e. how much ink a
    /// glyph actually put on the canvas.
    fn ink(img: &RgbaImage) -> usize {
        let bg = Theme::dark().background;
        img.pixels().filter(|p| **p != bg).count()
    }

    /// Ink inside the horizontal span `[x0, x1)` of the image.
    fn ink_in_columns(img: &RgbaImage, x0: u32, x1: u32) -> usize {
        let bg = Theme::dark().background;
        let mut count = 0;
        for y in 0..img.height() {
            for x in x0..x1.min(img.width()) {
                if *img.get_pixel(x, y) != bg {
                    count += 1;
                }
            }
        }
        count
    }

    /// A primary font without box drawing glyphs must hand those characters to
    /// the embedded JetBrains Mono instead of drawing a tofu box.
    #[test]
    fn missing_box_drawing_glyphs_fall_back_to_the_embedded_font() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
        for ch in FALLBACK_CHARS {
            assert!(
                !font_covers(&renderer.default_fonts.font, ch, 32.0),
                "fixture primary font unexpectedly covers {:?}",
                ch
            );
            let chosen = renderer.font_for_char(&renderer.default_fonts, ch, false, 32.0);
            assert!(chosen.is_fallback, "{:?} did not use a fallback font", ch);
            assert!(
                font_covers(chosen.font, ch, 32.0),
                "fallback font chosen for {:?} does not cover it",
                ch
            );
        }
        // ASCII still comes from the primary font.
        let chosen = renderer.font_for_char(&renderer.default_fonts, 'M', false, 32.0);
        assert!(!chosen.is_fallback, "ASCII must stay on the primary font");
    }

    /// The embedded JetBrains Mono is always the first fallback, even when the
    /// theme configures extra fonts.
    #[test]
    fn embedded_font_is_always_the_first_fallback() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
        assert_eq!(
            renderer.default_fonts.fallback_fonts.len(),
            2,
            "expected the embedded font plus one configured fallback"
        );
        let embedded = &renderer.default_fonts.fallback_fonts[0];
        for ch in FALLBACK_CHARS {
            assert!(
                font_covers(embedded, ch, 32.0),
                "embedded JetBrains Mono should cover {:?}",
                ch
            );
            let chosen = renderer.font_for_char(&renderer.default_fonts, ch, false, 32.0);
            assert!(
                std::ptr::eq(chosen.font, embedded),
                "{:?} skipped the embedded font",
                ch
            );
        }
    }

    /// The embedded font really rasterizes the box drawing and symbol
    /// characters, and they reach the canvas through the full render path.
    #[test]
    fn embedded_font_renders_box_drawing_and_symbols() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
        let embedded = &renderer.default_fonts.fallback_fonts[0];
        for ch in FALLBACK_CHARS {
            let (metrics, bitmap) = embedded.rasterize(ch, 32.0);
            assert!(
                !bitmap.is_empty() && metrics.width > 0 && metrics.height > 0,
                "embedded font produced no bitmap for {:?}",
                ch
            );
        }

        let drawn: String = FALLBACK_CHARS.iter().collect();
        let img = render_line(&renderer, &drawn, 10);
        assert!(ink(&img) > 0, "fallback glyphs left no ink on the canvas");
    }

    /// A character no font in the chain covers keeps the terminal's normal
    /// missing-glyph behavior: nothing is borrowed from an unrelated font, and
    /// no tofu box is invented.
    #[test]
    fn uncovered_cjk_stays_missing_without_a_configured_fallback() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
        let chosen = renderer.font_for_char(&renderer.default_fonts, '\u{4e2d}', false, 32.0);
        assert!(
            !chosen.is_fallback,
            "no fallback should cover this CJK char"
        );
        assert!(!font_covers(chosen.font, '\u{4e2d}', 32.0));
        assert_eq!(
            ink(&render_line(&renderer, "\u{4e2d}", 10)),
            0,
            "a character no font covers must not draw a substitute glyph"
        );
    }

    /// A fallback font configured by the theme is loaded and used for the
    /// characters only it covers.
    #[test]
    fn configured_fallback_font_is_loaded_and_selected() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
        let chosen = renderer.font_for_char(&renderer.default_fonts, '\u{4e2d}', false, 32.0);
        assert!(chosen.is_fallback, "configured fallback was not selected");
        assert!(std::ptr::eq(
            chosen.font,
            &renderer.default_fonts.fallback_fonts[1]
        ));
        assert!(
            ink(&render_line(&renderer, "\u{4e2d}", 10)) > 0,
            "configured fallback glyph was not drawn"
        );
    }

    /// A fallback that does not exist, or is not a font at all, is skipped
    /// with a warning: the renderer still builds and the rest of the chain
    /// keeps working.
    #[test]
    fn broken_fallback_fonts_warn_and_are_skipped() {
        let dir = Path::new("target/font-fallback-test");
        std::fs::create_dir_all(dir).unwrap();
        let junk = dir.join("not-a-font.ttf");
        std::fs::write(&junk, b"this is definitely not a font").unwrap();

        let renderer = renderer_with(
            Some(LIMITED_PRIMARY),
            &[
                "target/font-fallback-test/missing-font.ttf",
                junk.to_str().unwrap(),
                CJK_FALLBACK,
            ],
        );

        // Embedded font + the one usable configured fallback.
        assert_eq!(renderer.default_fonts.fallback_fonts.len(), 2);
        assert!(
            renderer
                .font_for_char(&renderer.default_fonts, '\u{2500}', false, 32.0)
                .is_fallback
        );
        assert!(
            renderer
                .font_for_char(&renderer.default_fonts, '\u{4e2d}', false, 32.0)
                .is_fallback
        );
    }

    /// Fallback fonts must not disturb the monospace grid: cell metrics come
    /// from the primary font alone, and a fallback glyph stays inside its own
    /// cell.
    #[test]
    fn fallback_glyphs_keep_the_primary_cell_metrics() {
        let plain = renderer_with(Some(LIMITED_PRIMARY), &[]);
        let with_fallbacks = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
        assert_eq!(
            plain.default_fonts.cell_width,
            with_fallbacks.default_fonts.cell_width
        );
        assert_eq!(
            plain.default_fonts.cell_height,
            with_fallbacks.default_fonts.cell_height
        );

        let cols = 4;
        let img = render_line(&with_fallbacks, "\u{2500}", cols);
        let expected_width = cols as u32 * plain.default_fonts.cell_width * RENDER_SCALE
            + plain.padding * RENDER_SCALE * 2;
        assert_eq!(
            img.width(),
            expected_width,
            "fallback changed the grid width"
        );

        // The glyph is drawn in its own (first) cell. Box drawing glyphs
        // deliberately overhang the advance width a little so horizontal rules
        // join across cells, so the check is that the ink never reaches the
        // middle of the neighbouring cell.
        let cell_w = plain.default_fonts.cell_width * RENDER_SCALE;
        let padding = plain.padding * RENDER_SCALE;
        assert!(ink_in_columns(&img, padding, padding + cell_w) > 0);
        assert_eq!(
            ink_in_columns(&img, padding + cell_w + cell_w / 2, img.width()),
            0,
            "fallback glyph spilled into the next cell"
        );
    }

    /// A fallback glyph is positioned as cleanly in its cell as a primary
    /// glyph is in its own: it fills the cell horizontally (so rules join) and
    /// sits at the same height on the line.
    #[test]
    fn fallback_glyphs_sit_cleanly_in_the_cell() {
        // Primary = embedded JetBrains Mono: the glyph is drawn directly.
        let direct = renderer_with(None, &[]);
        // Primary = the ASCII-only fixture, whose cell is wider (0.64 em, like
        // MonoLisa): the glyph now comes from the embedded fallback.
        let via_fallback = renderer_with(Some(LIMITED_PRIMARY), &[]);

        let bbox = |img: &RgbaImage| -> (u32, u32, u32, u32) {
            let bg = Theme::dark().background;
            let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
            for (x, y, p) in img.enumerate_pixels() {
                if *p != bg {
                    x0 = x0.min(x);
                    y0 = y0.min(y);
                    x1 = x1.max(x);
                    y1 = y1.max(y);
                }
            }
            (x0, y0, x1, y1)
        };

        let measure = |r: &Renderer| {
            let img = render_line(r, "\u{2500}", 4);
            let padding = r.padding * RENDER_SCALE;
            let cell_w = r.default_fonts.cell_width * RENDER_SCALE;
            let (x0, y0, x1, y1) = bbox(&img);
            // Insets from the cell edges, and the ink's vertical midpoint
            // measured from the top of the line.
            (
                x0 as i64 - padding as i64,
                (padding + cell_w) as i64 - (x1 + 1) as i64,
                ((y0 + y1) / 2) as i64 - padding as i64,
            )
        };

        let (direct_left, direct_right, direct_mid) = measure(&direct);
        let (fb_left, fb_right, fb_mid) = measure(&via_fallback);

        assert!(
            fb_left <= direct_left + 1 && fb_right <= direct_right + 1,
            "fallback rule does not reach its cell edges (insets {}/{} vs {}/{})",
            fb_left,
            fb_right,
            direct_left,
            direct_right
        );
        assert!(
            fb_mid.abs_diff(direct_mid) <= 2,
            "fallback glyph sits at a different height: {} vs {}",
            fb_mid,
            direct_mid
        );
    }

    /// A double-width fallback glyph is centered across the cell *and* its
    /// vt100 continuation cell, and does not bleed into the next character.
    #[test]
    fn wide_fallback_glyphs_respect_continuation_cells() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
        let cols = 6;
        let img = render_line(&renderer, "\u{4e2d}", cols);
        let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;

        assert!(
            ink_in_columns(&img, padding, padding + cell_w * 2) > 0,
            "wide glyph drew nothing in its two cells"
        );
        assert_eq!(
            ink_in_columns(&img, padding + cell_w * 2, img.width()),
            0,
            "wide glyph spilled past its continuation cell"
        );
    }

    /// A horizontal rule drawn from a fallback font must tile: the glyph is
    /// scaled to the primary font's advance, so a run of `─` comes out as one
    /// unbroken line instead of a dashed one.
    #[test]
    fn fallback_box_drawing_tiles_without_gaps() {
        // A primary font whose cell is wider than the fallback's natural
        // advance is exactly the MonoLisa + JetBrains Mono case.
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
        let cols = 6;
        let img = render_line(&renderer, &"\u{2500}".repeat(4), cols);
        let bg = Theme::dark().background;
        let padding = renderer.padding * RENDER_SCALE;
        let run_end = padding + renderer.default_fonts.cell_width * RENDER_SCALE * 4;

        // The row carrying the rule must have ink in every column of the run.
        let row = (0..img.height())
            .max_by_key(|y| {
                (0..img.width())
                    .filter(|x| *img.get_pixel(*x, *y) != bg)
                    .count()
            })
            .expect("image has rows");
        let gaps: Vec<u32> = (padding..run_end)
            .filter(|x| *img.get_pixel(*x, row) == bg)
            .collect();
        assert!(
            gaps.is_empty(),
            "horizontal rule from the fallback font has gaps at columns {:?}",
            gaps
        );
    }

    /// Box drawing corners only ink part of their cell, so they must be placed
    /// by advance (side bearings preserved) rather than by centering their ink:
    /// `┌` keeps its stub on the right, where the rule it joins begins.
    #[test]
    fn fallback_box_corners_keep_their_side_bearings() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
        let img = render_line(&renderer, "\u{250c}", 4);
        let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        let mid = padding + cell_w / 2;

        let left = ink_in_columns(&img, padding, mid);
        let right = ink_in_columns(&img, mid, padding + cell_w);
        assert!(
            right > left,
            "'┌' should ink mostly the right half of its cell (left {} vs right {})",
            left,
            right
        );
    }

    // ---------------------------------------------------------------------
    // Per-theme font chains
    // ---------------------------------------------------------------------

    fn theme_config_with_fonts(font: Option<&str>, fallbacks: &[&str]) -> ThemeConfig {
        ThemeConfig {
            foreground: "#ffffff".to_string(),
            background: "#000000".to_string(),
            font: font.map(str::to_string),
            font_bold: None,
            fallback_fonts: fallbacks.iter().map(|f| f.to_string()).collect(),
            palette: std::array::from_fn(|_| "#808080".to_string()),
            base_dir: None,
        }
    }

    /// Every theme gets the font chain it declares, and themes that resolve to
    /// the same files share one parsed chain instead of reparsing the fonts.
    #[test]
    fn each_theme_gets_its_own_font_chain() {
        let mut themes = HashMap::new();
        themes.insert(
            "ascii-only".to_string(),
            theme_config_with_fonts(Some(LIMITED_PRIMARY), &[]),
        );
        themes.insert(
            "cjk".to_string(),
            theme_config_with_fonts(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]),
        );
        themes.insert("embedded".to_string(), theme_config_with_fonts(None, &[]));
        themes.insert(
            "embedded-too".to_string(),
            theme_config_with_fonts(None, &[]),
        );

        let renderer = Renderer::new(
            &FontSelection::default(),
            16.0,
            &themes,
            "embedded",
            &ChromeConfig::default(),
        )
        .expect("renderer builds");

        // Only the theme that configured the CJK fallback can draw the CJK
        // character; the others keep the terminal's missing-glyph behavior.
        let cjk_fonts = renderer.fonts_for(Some("cjk"));
        assert!(
            renderer
                .font_for_char(cjk_fonts, '\u{4e2d}', false, 32.0)
                .is_fallback
        );
        let ascii_fonts = renderer.fonts_for(Some("ascii-only"));
        assert!(
            !renderer
                .font_for_char(ascii_fonts, '\u{4e2d}', false, 32.0)
                .is_fallback
        );

        // The fixture primary font has a wider cell than the embedded font.
        let embedded_fonts = renderer.fonts_for(Some("embedded"));
        assert!(ascii_fonts.cell_width > embedded_fonts.cell_width);

        // Themes resolving to identical files share one chain, so adding
        // themes does not multiply font parsing.
        assert!(std::ptr::eq(
            renderer.fonts_for(Some("embedded-too")),
            embedded_fonts
        ));
        // An unknown theme falls back to the default theme's chain.
        assert!(std::ptr::eq(
            renderer.fonts_for(Some("nope")),
            embedded_fonts
        ));
        assert!(std::ptr::eq(renderer.fonts_for(None), embedded_fonts));
    }

    /// An explicit `--font` override wins over every theme's own font.
    #[test]
    fn font_override_applies_to_every_theme() {
        let mut themes = HashMap::new();
        themes.insert("embedded".to_string(), theme_config_with_fonts(None, &[]));
        themes.insert(
            "ascii-only".to_string(),
            theme_config_with_fonts(Some(LIMITED_PRIMARY), &[]),
        );

        let renderer = Renderer::new(
            &FontSelection {
                font_override: Some(PathBuf::from(LIMITED_PRIMARY)),
                ..FontSelection::default()
            },
            16.0,
            &themes,
            "embedded",
            &ChromeConfig::default(),
        )
        .expect("renderer builds");

        let overridden = renderer.fonts_for(Some("embedded"));
        let declared = renderer.fonts_for(Some("ascii-only"));
        assert_eq!(overridden.cell_width, declared.cell_width);
        assert!(std::ptr::eq(overridden, declared));
    }

    // ---------------------------------------------------------------------
    // Composed image descriptions
    // ---------------------------------------------------------------------

    /// Width trimming makes panes of different widths the normal case, so
    /// composing must pad a narrower pane with its own background rather than
    /// rescale it: every source pixel has to survive unchanged.
    #[test]
    fn compose_pads_narrow_panes_instead_of_rescaling_them() {
        let dir = std::path::Path::new("target/compose-padding-test");
        std::fs::create_dir_all(dir).unwrap();

        let wide_path = dir.join("wide.png");
        let narrow_path = dir.join("narrow.png");
        let wide: RgbaImage = ImageBuffer::from_pixel(40, 10, Rgba([10, 10, 10, 255]));
        let mut narrow: RgbaImage = ImageBuffer::from_pixel(20, 10, Rgba([80, 20, 20, 255]));
        // A single bright pixel: any resample would smear it into neighbours.
        narrow.put_pixel(5, 5, Rgba([255, 255, 0, 255]));
        save_png(&wide, &wide_path, None).unwrap();
        save_png(&narrow, &narrow_path, None).unwrap();

        let composed = compose_images(
            &[wide_path, narrow_path],
            ComposeLayout::Vertical,
            0,
            Rgba([0, 0, 0, 255]),
        )
        .expect("compose");

        assert_eq!(composed.dimensions(), (40, 20));
        assert_eq!(*composed.get_pixel(5, 15), Rgba([255, 255, 0, 255]));
        assert_eq!(*composed.get_pixel(6, 15), Rgba([80, 20, 20, 255]));
        // The pad to the right of the narrow pane uses that pane's own
        // background, so the seam is invisible.
        assert_eq!(*composed.get_pixel(30, 15), Rgba([80, 20, 20, 255]));
    }

    /// A composed image's description is the panes' descriptions, in order,
    /// with a clear separator and Unicode preserved.
    #[test]
    fn composed_description_joins_panes_and_keeps_unicode() {
        let dir = std::path::Path::new("target/composed-description-test");
        std::fs::create_dir_all(dir).unwrap();
        let img: RgbaImage = ImageBuffer::from_pixel(4, 4, Rgba([0, 0, 0, 255]));

        let first = dir.join("first.png");
        let second = dir.join("second.png");
        let bare = dir.join("bare.png");
        save_png(&img, &first, Some("héllo ✓ \u{4e2d}\u{6587}")).unwrap();
        save_png(&img, &second, Some("λ ─┐ second")).unwrap();
        save_png(&img, &bare, None).unwrap();

        assert_eq!(
            read_png_description(&first).as_deref(),
            Some("héllo ✓ \u{4e2d}\u{6587}")
        );
        assert_eq!(read_png_description(&bare), None);

        let joined = composed_description(&[first.clone(), second.clone()])
            .expect("panes have descriptions");
        assert_eq!(
            joined,
            "héllo ✓ \u{4e2d}\u{6587}\n\n--- Pane 2 ---\n\nλ ─┐ second"
        );

        // A pane without a description is marked, so pane numbers still line
        // up with the image.
        let mixed =
            composed_description(&[bare.clone(), second]).expect("one pane has a description");
        assert!(mixed.starts_with("(no description)"));
        assert!(mixed.contains("--- Pane 2 ---"));

        // No descriptions at all: nothing is invented.
        assert_eq!(composed_description(&[bare.clone(), bare]), None);
    }

    // ---------------------------------------------------------------------
    // Chrome geometry: rounded frames and macOS traffic lights
    // ---------------------------------------------------------------------

    /// Every preset that draws a window frame.
    const CHROME_PRESETS: [&str; 4] = ["minimal", "gnome", "macos", "report"];

    fn preset_chrome(preset: &str, rounded: bool, shadow: bool) -> ChromeOptions {
        ChromeOptions {
            enabled: true,
            preset: preset.to_string(),
            title: Some("demo".to_string()),
            timestamp: false,
            shadow,
            radius: 14,
            rounded,
            outer_padding: 18,
            title_bar_height: 34,
        }
    }

    /// Render a terminal image inside `preset`'s window frame.
    fn framed(preset: &str, rounded: bool, shadow: bool) -> RgbaImage {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        // Wide enough that the centered title cannot overlap the traffic
        // lights on the left, so masks stay comparable.
        let terminal = ImageBuffer::from_pixel(400, 80, theme.background);
        renderer.compose_with_chrome(
            terminal,
            &theme,
            &renderer.default_fonts,
            &preset_chrome(preset, rounded, shadow),
        )
    }

    /// Signed distance from a pixel center to a rounded rectangle: negative
    /// inside, positive outside.
    fn rounded_rect_distance(x: u32, y: u32, w: u32, h: u32, r: f32) -> f32 {
        let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
        let (hw, hh) = (w as f32 / 2.0, h as f32 / 2.0);
        let qx = (px - hw).abs() - (hw - r);
        let qy = (py - hh).abs() - (hh - r);
        (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r
    }

    /// Rounded corners are a property of the frame, not of one preset: every
    /// chrome preset must leave its four outer corner pixels fully transparent.
    #[test]
    fn every_chrome_preset_has_transparent_outer_corners() {
        for preset in CHROME_PRESETS {
            let img = framed(preset, true, false);
            let (w, h) = img.dimensions();
            for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] {
                assert_eq!(
                    img.get_pixel(x, y)[3],
                    0,
                    "{preset}: corner ({x}, {y}) is not transparent"
                );
            }
            // The corner is anti-aliased, not a hard staircase: the frame edge
            // produces partially transparent pixels.
            let partial = img.pixels().filter(|p| p[3] > 0 && p[3] < 255).count();
            assert!(
                partial > 0,
                "{preset}: rounded corners have no anti-aliased pixels"
            );
        }
    }

    /// Nothing opaque may exist outside the rounded frame - no gray, black, or
    /// theme-colored halo around the window - for any preset.
    #[test]
    fn no_opaque_pixels_outside_the_rounded_frame() {
        let radius = (14 * RENDER_SCALE) as f32;
        for preset in CHROME_PRESETS {
            let img = framed(preset, true, false);
            let (w, h) = img.dimensions();
            for y in 0..h {
                for x in 0..w {
                    let alpha = img.get_pixel(x, y)[3];
                    // Half a pixel of slack for the anti-aliased edge itself.
                    if rounded_rect_distance(x, y, w, h, radius) > 0.75 {
                        assert_eq!(
                            alpha, 0,
                            "{preset}: pixel ({x}, {y}) outside the frame is not transparent"
                        );
                    }
                }
            }
        }
    }

    /// With a shadow the area outside the frame may hold shadow pixels, but
    /// they must stay semi-transparent - never an opaque backdrop.
    #[test]
    fn shadow_outside_the_frame_is_never_opaque() {
        let radius = (14 * RENDER_SCALE) as f32;
        for preset in CHROME_PRESETS {
            let img = framed(preset, true, true);
            let (w, h) = img.dimensions();
            // `compose_with_chrome` reserves `16 * RENDER_SCALE` pixels for the
            // shadow and centers the frame in them.
            let offset = 16 * RENDER_SCALE / 2;
            let (frame_w, frame_h) = (w - offset * 2, h - offset * 2);
            let mut shadow_pixels = 0usize;
            for y in 0..h {
                for x in 0..w {
                    let alpha = img.get_pixel(x, y)[3];
                    if alpha == 0 {
                        continue;
                    }
                    let (fx, fy) = (x as i64 - offset as i64, y as i64 - offset as i64);
                    let outside = fx < 0
                        || fy < 0
                        || fx >= frame_w as i64
                        || fy >= frame_h as i64
                        || rounded_rect_distance(fx as u32, fy as u32, frame_w, frame_h, radius)
                            > 0.75;
                    if outside {
                        shadow_pixels += 1;
                        assert!(
                            alpha < 255,
                            "{preset}: opaque pixel ({x}, {y}) outside the frame"
                        );
                    }
                }
            }
            assert!(shadow_pixels > 0, "{preset}: shadow was not drawn");
        }
    }

    /// The window body is the terminal's own background for every preset, so a
    /// screenshot is never surrounded by a mismatched gray border.
    #[test]
    fn frame_padding_matches_the_terminal_background() {
        let background = Theme::dark().background;
        for preset in CHROME_PRESETS {
            let img = framed(preset, true, false);
            let (w, h) = img.dimensions();
            // Left padding (below any title bar) and bottom padding, both well
            // inside the rounded corners.
            for (x, y) in [(4, h / 2), (w / 2, h - 4)] {
                assert_eq!(
                    *img.get_pixel(x, y),
                    background,
                    "{preset}: padding at ({x}, {y}) is not the terminal background"
                );
            }
        }
    }

    /// `--no-rounded` must still produce a square, fully opaque frame: the
    /// corner mask is applied only when rounding is on.
    #[test]
    fn square_chrome_keeps_opaque_corners() {
        for preset in CHROME_PRESETS {
            let img = framed(preset, false, false);
            let (w, h) = img.dimensions();
            for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] {
                assert_eq!(
                    img.get_pixel(x, y)[3],
                    255,
                    "{preset}: square corner ({x}, {y}) lost its opacity"
                );
            }
        }
    }

    /// Shape statistics of the pixels exactly matching one color.
    #[derive(Debug, PartialEq, Eq)]
    struct MaskStats {
        width: u32,
        height: u32,
        count: usize,
        left: usize,
        right: usize,
        top: usize,
        bottom: usize,
        origin: (u32, u32),
    }

    /// Bounding box, pixel count, and left/right + top/bottom symmetry of the
    /// pixels exactly matching `color`.
    fn mask_stats(img: &RgbaImage, color: Rgba<u8>) -> MaskStats {
        let points: Vec<(u32, u32)> = img
            .enumerate_pixels()
            .filter(|(_, _, p)| **p == color)
            .map(|(x, y, _)| (x, y))
            .collect();
        assert!(!points.is_empty(), "no pixels of {:?} were drawn", color);
        let (x0, x1) = (
            points.iter().map(|p| p.0).min().unwrap(),
            points.iter().map(|p| p.0).max().unwrap(),
        );
        let (y0, y1) = (
            points.iter().map(|p| p.1).min().unwrap(),
            points.iter().map(|p| p.1).max().unwrap(),
        );
        let cx = (x0 + x1) as f32 / 2.0;
        let cy = (y0 + y1) as f32 / 2.0;
        MaskStats {
            width: x1 - x0 + 1,
            height: y1 - y0 + 1,
            count: points.len(),
            left: points.iter().filter(|p| (p.0 as f32) < cx).count(),
            right: points.iter().filter(|p| (p.0 as f32) > cx).count(),
            top: points.iter().filter(|p| (p.1 as f32) < cy).count(),
            bottom: points.iter().filter(|p| (p.1 as f32) > cy).count(),
            origin: (x0, y0),
        }
    }

    /// The macOS traffic lights must be three identical circles: equal
    /// diameters, square (and therefore circular) masks, mirror symmetry about
    /// both axes, and evenly spaced centers.
    #[test]
    fn macos_traffic_lights_are_equal_symmetric_circles() {
        let img = framed("macos", true, false);
        let colors = [
            Rgba([255, 95, 86, 255]),
            Rgba([255, 189, 46, 255]),
            Rgba([39, 201, 63, 255]),
        ];

        let stats: Vec<MaskStats> = colors.iter().map(|c| mask_stats(&img, *c)).collect();
        for (stat, color) in stats.iter().zip(colors) {
            assert_eq!(
                stat.width, stat.height,
                "{color:?} button is not square (so not round)"
            );
            assert_eq!(
                stat.left, stat.right,
                "{color:?} button is not left/right symmetric"
            );
            assert_eq!(
                stat.top, stat.bottom,
                "{color:?} button is not top/bottom symmetric"
            );
        }

        // All three buttons are the same disc.
        for other in &stats[1..] {
            assert_eq!(
                (other.width, other.height, other.count),
                (stats[0].width, stats[0].height, stats[0].count),
                "traffic lights differ in size"
            );
        }

        // Evenly spaced, on one horizontal line.
        let pitch = (TRAFFIC_LIGHT_PITCH * RENDER_SCALE) as i64;
        for (index, stat) in stats.iter().enumerate() {
            assert_eq!(
                stat.origin.1, stats[0].origin.1,
                "traffic lights are not on the same line"
            );
            assert_eq!(
                stat.origin.0 as i64 - stats[0].origin.0 as i64,
                pitch * index as i64,
                "traffic light {index} is misplaced"
            );
        }

        // A rounded square would fill its bounding box; a disc leaves the
        // corners of the box empty.
        let (x0, y0) = stats[0].origin;
        let side = stats[0].width - 1;
        for (dx, dy) in [(0, 0), (side, 0), (0, side), (side, side)] {
            assert_ne!(
                *img.get_pixel(x0 + dx, y0 + dy),
                colors[0],
                "the button fills its bounding box corner, so it is not a circle"
            );
        }
    }

    /// The circle helper itself: a true disc, symmetric about its center, with
    /// a one-pixel anti-aliased edge.
    #[test]
    fn draw_circle_is_a_symmetric_antialiased_disc() {
        let renderer = bare_renderer();
        let mut img: RgbaImage = ImageBuffer::from_pixel(41, 41, Rgba([0, 0, 0, 0]));
        // An even diameter centered on a pixel boundary is exactly symmetric.
        let (cx, cy, r) = (20.0f32, 20.0f32, 10.0f32);
        renderer.draw_circle(&mut img, cx, cy, r, Rgba([255, 0, 0, 255]));

        let opaque: Vec<(u32, u32)> = img
            .enumerate_pixels()
            .filter(|(_, _, p)| p[3] == 255)
            .map(|(x, y, _)| (x, y))
            .collect();
        let xs: Vec<u32> = opaque.iter().map(|p| p.0).collect();
        let ys: Vec<u32> = opaque.iter().map(|p| p.1).collect();
        let (x0, x1) = (*xs.iter().min().unwrap(), *xs.iter().max().unwrap());
        let (y0, y1) = (*ys.iter().min().unwrap(), *ys.iter().max().unwrap());
        assert_eq!(x1 - x0, y1 - y0, "the disc is not as wide as it is tall");

        // Mirror symmetry about both axes, pixel for pixel.
        for (x, y) in &opaque {
            let mirrored_x = (2.0 * cx - 1.0) as u32 - x;
            let mirrored_y = (2.0 * cy - 1.0) as u32 - y;
            assert_eq!(
                img.get_pixel(mirrored_x, *y)[3],
                255,
                "no horizontal mirror for ({x}, {y})"
            );
            assert_eq!(
                img.get_pixel(*x, mirrored_y)[3],
                255,
                "no vertical mirror for ({x}, {y})"
            );
        }

        // Round, not square: the bounding-box corners stay empty, and a point
        // just outside the radius is never lit.
        assert_eq!(img.get_pixel(x0, y0)[3], 0);
        assert_eq!(img.get_pixel(x1, y1)[3], 0);
        for (x, y) in [(cx + r + 1.0, cy), (cx, cy + r + 1.0)] {
            assert_eq!(
                img.get_pixel(x as u32, y as u32)[3],
                0,
                "ink outside the circle radius"
            );
        }

        // The edge is anti-aliased rather than a hard staircase.
        let partial = img.pixels().filter(|p| p[3] > 0 && p[3] < 255).count();
        assert!(partial > 0, "circle edge is not anti-aliased");
    }

    /// An interactive capture's text comes from the screen: colors survive,
    /// but the terminal bookkeeping in the raw stream (bracketed paste, window
    /// titles, cursor motion, and the erased trailing prompt) does not.
    #[test]
    fn screen_text_keeps_colors_and_drops_terminal_bookkeeping() {
        let captured = screen_of(
            b"\x1b[?2004h$ echo hi\r\n\x1b[?2004l\r\x1b[1;36mhi\x1b[0m\r\n$ \r\x1b[0m\x1b[J",
            6,
            40,
        );
        let text = screen_ansi_text(&captured, 40);

        assert!(
            text.contains("$ echo hi"),
            "command echo missing: {:?}",
            text
        );
        assert!(text.contains("hi"), "output missing: {:?}", text);
        assert!(text.contains('\u{1b}'), "colors were lost: {:?}", text);
        assert!(
            !text.contains("?2004"),
            "bracketed paste leaked: {:?}",
            text
        );
        assert_eq!(
            text.lines().count(),
            2,
            "the erased trailing prompt should be gone: {:?}",
            text
        );
    }

    /// The cyan attribute of a colored cell is re-emitted verbatim, and the
    /// line is closed with a reset so the style cannot bleed.
    #[test]
    fn screen_text_reemits_the_cells_own_sgr() {
        let captured = screen_of(b"\x1b[1;36mMCP\x1b[0m ok\r\n", 3, 20);
        let text = screen_ansi_text(&captured, 20);
        assert!(
            text.starts_with("\x1b[0;1;36mMCP"),
            "unexpected text: {:?}",
            text
        );
        assert!(text.ends_with("\x1b[0m"), "line not reset: {:?}", text);
    }

    /// Screen-derived text is one line per *screen row*: a soft-wrapped line
    /// becomes two, matching the image the reader is looking at.
    #[test]
    fn screen_text_is_one_line_per_row() {
        let captured = screen_of(b"abcdefghijklmno\r\n", 4, 10);
        let text = screen_ansi_text(&captured, 10);
        assert_eq!(text.lines().count(), 2);
        assert!(text.contains("abcdefghij"));
        assert!(text.contains("klmno"));
    }

    /// A screenshot shows every retained line, not the last screenful: the
    /// image is as tall as the whole capture and its `Description` metadata
    /// carries the first line as well as the last.
    #[test]
    fn render_bytes_renders_every_line_that_scrolled_off() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/full-capture-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let data: String = (1..=200).map(|i| format!("line {}\r\n", i)).collect();
        let (path, text, _, context) = renderer
            .render_bytes_with_options(
                data.as_bytes(),
                40,
                10,
                out_dir,
                Some("full capture"),
                Some("dark"),
                None,
                None,
                TextOptions {
                    strip_ansi: true,
                    embed_description: true,
                    ..TextOptions::default()
                },
                true,
                RenderOptions::default(),
            )
            .unwrap();

        assert!(!context.truncated);
        assert!(
            text.starts_with("line 1\n"),
            "text starts: {:?}",
            &text[..20]
        );
        assert!(text.trim_end().ends_with("line 200"));

        let img = image::open(&path).unwrap().to_rgba8();
        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        // 200 printed lines; the row the cursor rests on is blank and is no
        // longer padded out into an extra row of background.
        assert_eq!(img.height(), 200 * cell_h + padding * 2);

        let description = read_png_description(&path).expect("description");
        assert!(description.starts_with("line 1\n"));
        assert!(description.ends_with("line 200"));

        std::fs::remove_file(&path).ok();
    }

    /// Colors set on a line that has long since scrolled out of the viewport
    /// are still the colors that line is drawn and re-emitted with.
    #[test]
    fn styling_survives_from_the_oldest_scrollback_rows() {
        let renderer = bare_renderer();
        let mut data = String::from("\x1b[1;31mALERT\x1b[0m first\r\n");
        for i in 2..=100 {
            data.push_str(&format!("line {}\r\n", i));
        }
        let captured = renderer.capture(data.as_bytes(), 10, 40, LineSelection::All);

        let cell = captured.cell(0, 0).expect("first cell");
        assert_eq!(cell.contents(), "A");
        assert_eq!(cell.fgcolor(), vt100::Color::Idx(1));
        assert!(cell.bold());

        let text = screen_ansi_text(&captured, 40);
        assert!(
            text.starts_with("\x1b[0;1;31mALERT"),
            "scrollback style lost: {:?}",
            &text[..24]
        );
    }

    /// A selection narrows the image to the lines it kept, and the returned
    /// text follows it rather than reporting output the picture does not show.
    #[test]
    fn head_and_tail_selections_narrow_the_render() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/selection-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let data: String = (1..=200).map(|i| format!("line {}\r\n", i)).collect();
        let render = |lines| {
            renderer
                .render_bytes_with_options(
                    data.as_bytes(),
                    40,
                    10,
                    out_dir,
                    Some("selection"),
                    Some("dark"),
                    None,
                    None,
                    TextOptions {
                        strip_ansi: true,
                        ..TextOptions::default()
                    },
                    true,
                    RenderOptions::default().with_lines(lines),
                )
                .unwrap()
        };

        let (head_path, head_text, _, head_context) = render(LineSelection::Head(10));
        assert_eq!(head_context.lines, LineSelection::Head(10));
        assert_eq!(head_text.lines().count(), 10);
        assert_eq!(head_text.lines().next().unwrap(), "line 1");
        assert_eq!(head_text.lines().last().unwrap(), "line 10");

        let (tail_path, tail_text, _, tail_context) = render(LineSelection::Tail(10));
        assert_eq!(tail_context.lines, LineSelection::Tail(10));
        assert_eq!(tail_text.lines().count(), 10);
        assert_eq!(tail_text.lines().next().unwrap(), "line 191");
        assert_eq!(tail_text.lines().last().unwrap(), "line 200");

        let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
        let padding = renderer.padding * RENDER_SCALE;
        for path in [&head_path, &tail_path] {
            let img = image::open(path).unwrap().to_rgba8();
            assert_eq!(img.height(), 10 * cell_h + padding * 2);
            std::fs::remove_file(path).ok();
        }
    }

    /// A capture too tall to render is refused with an actionable error rather
    /// than an allocation the machine cannot satisfy.
    #[test]
    fn an_oversized_capture_is_refused_with_advice() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/oversized-out");
        std::fs::create_dir_all(out_dir).unwrap();

        // A full 10k-line scrollback, 200 columns wide, is well past the
        // pixel ceiling.
        let data: String = (1..=12_000).map(|i| format!("line {}\r\n", i)).collect();
        let err = renderer
            .render_bytes(
                data.as_bytes(),
                200,
                10,
                out_dir,
                Some("oversized"),
                Some("dark"),
                None,
                None,
                TextOptions::default(),
                false,
            )
            .expect_err("an image this size must be refused");
        let message = err.to_string();
        assert!(
            message.contains("--head-lines") && message.contains("megapixels"),
            "unhelpful error: {message}"
        );
    }

    /// The budget is a *memory* budget, not just a pixel count: adding chrome
    /// keeps a second full-size layer alive, so the same capture that renders
    /// bare can be over the line once it is framed and shadowed.
    #[test]
    fn the_render_budget_counts_every_simultaneous_buffer() {
        let screen = screen_of(b"hi", 4, 80);

        // One buffer at the pixel ceiling is allowed.
        let side = (MAX_IMAGE_PIXELS as f64).sqrt() as u32;
        assert!(check_render_budget(side, side, 1, &screen).is_ok());
        // The same image with a second layer alive is over the byte budget.
        let err = check_render_budget(side, side, 2, &screen)
            .expect_err("two buffers of a 64 MP image exceed the budget");
        assert!(
            err.to_string().contains("MB of image buffers"),
            "the error should name the memory cost: {err}"
        );
        // And one pixel too many is refused outright.
        assert!(check_render_budget(side + 1, side + 1, 1, &screen).is_err());
    }

    /// A capture the machine cannot render is refused *before* anything is
    /// allocated, whether the size comes from the number of rows or from the
    /// width of the terminal.
    #[test]
    fn huge_geometry_is_refused_before_allocation() {
        let mut renderer = bare_renderer();
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/huge-geometry-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let render = |cols: u16, rows: u16, data: &str, chrome: Option<&ChromeOptions>| {
            renderer.render_bytes(
                data.as_bytes(),
                cols,
                rows,
                out_dir,
                Some("huge"),
                Some("dark"),
                chrome,
                None,
                TextOptions::default(),
                false,
            )
        };

        // Too many rows: a full scrollback of a narrow terminal.
        let tall: String = (1..=12_000).map(|i| format!("line {}\r\n", i)).collect();
        let err = render(200, 10, &tall, None).expect_err("a 12,000-line image must be refused");
        assert!(err.to_string().contains("--head-lines"), "{err}");

        // Too many columns: the widest terminal the CLI accepts, filled.
        let wide = format!("{}\r\n", "x".repeat(500)).repeat(2_000);
        let err = render(500, 10, &wide, None).expect_err("a 500-column wall must be refused");
        assert!(err.to_string().contains("--head-lines"), "{err}");

        // Selecting one end of the same capture renders fine, which is what
        // the error tells the caller to do.
        let (path, _, _, _) = renderer
            .render_bytes_with_options(
                tall.as_bytes(),
                200,
                10,
                out_dir,
                Some("huge-head"),
                Some("dark"),
                None,
                None,
                TextOptions::default(),
                false,
                RenderOptions::default().with_lines(LineSelection::Head(20)),
            )
            .expect("a twenty-line selection is renderable");
        std::fs::remove_file(&path).ok();
    }

    /// Head selection is the first lines of the *output*, even when far more
    /// output was produced than the scrollback could hold - which is what makes
    /// it usable as an escape hatch from the render budget.
    #[test]
    fn head_selection_survives_a_capture_larger_than_the_scrollback() {
        let mut renderer = bare_renderer();
        renderer.max_scrollback_lines = 100;
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/head-overflow-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let data: String = (1..=20_000).map(|i| format!("line {}\r\n", i)).collect();
        let (path, text, _, context) = renderer
            .render_bytes_with_options(
                data.as_bytes(),
                80,
                24,
                out_dir,
                Some("head-overflow"),
                Some("dark"),
                None,
                None,
                TextOptions {
                    strip_ansi: true,
                    ..TextOptions::default()
                },
                true,
                RenderOptions::default().with_lines(LineSelection::Head(10)),
            )
            .unwrap();

        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), 10);
        assert_eq!(lines[0], "line 1");
        assert_eq!(lines[9], "line 10");
        assert!(
            !context.truncated,
            "the head is complete, so nothing it shows was dropped"
        );
        std::fs::remove_file(&path).ok();
    }

    /// The configured scrollback is a *tail*-retention setting, so a head
    /// render must not be at its mercy: a one-line capacity still answers with
    /// the first ten lines of a thousand-line run.
    #[test]
    fn head_selection_ignores_the_configured_scrollback_capacity() {
        let mut renderer = bare_renderer();
        renderer.max_scrollback_lines = 1;
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/head-tiny-capacity-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let data: String = (1..=1_000).map(|i| format!("line {}\r\n", i)).collect();
        let (path, text, _, context) = renderer
            .render_bytes_with_options(
                data.as_bytes(),
                80,
                40,
                out_dir,
                Some("head-tiny-capacity"),
                Some("dark"),
                None,
                None,
                TextOptions {
                    strip_ansi: true,
                    ..TextOptions::default()
                },
                true,
                RenderOptions::default().with_lines(LineSelection::Head(10)),
            )
            .unwrap();

        let lines: Vec<&str> = text.lines().collect();
        let expected: Vec<String> = (1..=10).map(|i| format!("line {}", i)).collect();
        assert_eq!(lines, expected);
        assert!(!context.truncated);
        std::fs::remove_file(&path).ok();
    }

    /// A capture that lost output says so, and one that filled its scrollback
    /// to the last row does not.
    #[test]
    fn render_meta_reports_truncation_exactly() {
        let mut renderer = bare_renderer();
        renderer.max_scrollback_lines = 10;
        renderer.themes.insert("dark".to_string(), Theme::dark());
        let out_dir = std::path::Path::new("target/truncation-meta-out");
        std::fs::create_dir_all(out_dir).unwrap();

        let render = |lines: usize| {
            let data: String = (1..=lines).map(|i| format!("line {}\r\n", i)).collect();
            renderer
                .render_bytes_with_options(
                    data.as_bytes(),
                    40,
                    5,
                    out_dir,
                    Some("truncation"),
                    Some("dark"),
                    None,
                    None,
                    TextOptions::default(),
                    true,
                    RenderOptions::default(),
                )
                .unwrap()
        };

        // 14 lines through a 5-row viewport scroll exactly 10 rows off.
        let (path, _, _, context) = render(14);
        assert!(!context.truncated);
        std::fs::remove_file(&path).ok();

        let (path, _, _, context) = render(15);
        assert!(context.truncated);
        std::fs::remove_file(&path).ok();
    }

    /// The renderer reports the capacity that actually applied, which the
    /// retained-cell budget can push below the configured one.
    #[test]
    fn effective_scrollback_follows_the_terminal_width() {
        let renderer = bare_renderer();
        assert_eq!(
            renderer.effective_scrollback_lines(40, 120),
            DEFAULT_MAX_SCROLLBACK_LINES
        );
        assert!(renderer.effective_scrollback_lines(40, 500) < DEFAULT_MAX_SCROLLBACK_LINES);
    }

    /// Drawing the terminal straight into the window frame saves a full-size
    /// buffer; it must not change a single pixel of the result. Both presets
    /// and both shadow settings are checked against the copy-then-compose path
    /// they replaced.
    #[test]
    fn chrome_composition_is_pixel_identical_with_one_fewer_buffer() {
        let renderer = bare_renderer();
        let theme = Theme::dark();
        let captured = screen_of(b"\x1b[1;32mok\x1b[0m composed", 4, 40);

        for (preset, shadow, rounded) in [
            ("gnome", true, true),
            ("macos", false, true),
            ("minimal", true, false),
            ("report", false, false),
        ] {
            let chrome = ChromeOptions {
                enabled: true,
                preset: preset.to_string(),
                title: Some("demo".to_string()),
                // A timestamp would differ between the two renders for reasons
                // that have nothing to do with buffering.
                timestamp: false,
                shadow,
                radius: 14,
                rounded,
                outer_padding: 18,
                title_bar_height: 34,
            };

            let one_layer = renderer
                .render_to_image(
                    &captured,
                    &theme,
                    &renderer.default_fonts,
                    &chrome,
                    None,
                    true,
                )
                .unwrap();

            let terminal = renderer
                .render_screen(&captured, &theme, &renderer.default_fonts, None, true)
                .unwrap();
            let copied =
                renderer.compose_with_chrome(terminal, &theme, &renderer.default_fonts, &chrome);

            assert_eq!(
                one_layer.dimensions(),
                copied.dimensions(),
                "{preset} changed size"
            );
            assert!(
                one_layer.as_raw() == copied.as_raw(),
                "{preset} (shadow={shadow}) is no longer pixel identical"
            );
        }
    }
    // ---------------------------------------------------------------------
    // Unicode shaping
    // ---------------------------------------------------------------------

    /// Two synthetic fonts covering the same characters with visibly different
    /// outlines: `A` inks the left third of the cell, `B` the right third.
    const SHAPE_A: &str = "tests/fixtures/shape-a.ttf";
    /// See [`SHAPE_A`].
    const SHAPE_B: &str = "tests/fixtures/shape-b.ttf";
    /// A COLRv0 font: two layers per glyph, in two loud palette colors.
    const COLOR_EMOJI: &str = "tests/fixtures/color-emoji.ttf";
    /// A two-face collection whose faces cover different code points.
    const COLLECTION: &str = "tests/fixtures/collection.ttc";

    /// Devanagari KA. Its script always needs a shaper, so it exercises font
    /// precedence on the *shaped* path rather than the fontdue one.
    const DEVANAGARI_KA: char = '\u{0915}';

    fn cell_at(screen: &CapturedScreen, col: u16) -> &vt100::Cell {
        screen.cell(0, col).expect("cell in range")
    }

    /// Ordinary output must never reach the shaper: that is the whole reason
    /// existing screenshots still render the way they always did.
    #[test]
    fn ordinary_output_never_reaches_the_shaper() {
        let renderer = renderer_with(None, &[]);
        let fonts = &renderer.default_fonts;
        let plain = "abc XYZ 019 => != -> <= |> ::";
        let captured = screen_of(plain.as_bytes(), 2, 40);
        for col in 0..plain.chars().count() as u16 {
            assert!(
                !renderer.cell_needs_shaping(fonts, cell_at(&captured, col)),
                "ASCII cell {col} was sent to the shaper"
            );
        }
        // Box drawing, Greek, Cyrillic and CJK the chain covers are all
        // correct one cell at a time.
        for text in [
            "\u{250C}\u{2500}\u{2510}\u{2502}\u{2514}\u{2518}",
            "\u{03B1}\u{03B2}\u{0416}\u{0429}",
        ] {
            let captured = screen_of(text.as_bytes(), 2, 20);
            for col in 0..text.chars().count() as u16 {
                assert!(
                    !renderer.cell_needs_shaping(fonts, cell_at(&captured, col)),
                    "{text:?} cell {col} was sent to the shaper"
                );
            }
        }
    }

    /// The four - and only four - reasons a cell is shaped.
    #[test]
    fn only_cells_the_fast_path_cannot_draw_are_shaped() {
        let renderer = renderer_with(None, &[]);
        let fonts = &renderer.default_fonts;
        // (sample, column that must need shaping, why)
        let corpus: &[(&str, u16, &str)] = &[
            ("e\u{0301}", 0, "base plus combining mark is one cell"),
            ("1\u{FE0F}\u{20E3}", 0, "keycap sequence is one cell"),
            ("\u{2764}\u{FE0F}", 0, "variation selector sequence"),
            ("\u{1F600}", 0, "emoji presentation"),
            ("\u{1F44D}\u{1F3FD}", 0, "emoji plus skin tone modifier"),
            ("\u{1F1FA}\u{1F1F8}", 0, "regional indicators"),
            ("\u{0645}\u{0631}", 0, "Arabic joins"),
            ("\u{0915}\u{094D}\u{0937}", 1, "Devanagari reorders"),
            ("\u{4F60}", 0, "no configured font covers this CJK"),
        ];
        for (text, col, why) in corpus {
            let captured = screen_of(text.as_bytes(), 2, 20);
            assert!(
                renderer.cell_needs_shaping(fonts, cell_at(&captured, *col)),
                "{text:?} column {col} should be shaped: {why}"
            );
        }
    }

    /// The shaper is only reached when it is enabled, so
    /// [`ShapingOptions::disabled`] really is the 1.1.5 renderer.
    #[test]
    fn disabling_shaping_turns_the_whole_path_off() {
        let renderer = renderer_with_shaping(None, &[], ShapingOptions::disabled());
        assert!(!renderer.default_fonts.shaping().enabled());
        assert!(renderer.default_fonts.shaping().families().is_empty());
    }

    /// A run stops at the first cell whose style differs, so a ligature or an
    /// overhanging mark can never cross a color change.
    #[test]
    fn a_shaped_run_stops_at_a_style_boundary() {
        let renderer = renderer_with(None, &[]);
        let fonts = &renderer.default_fonts;
        // Two Arabic letters, the second in a different color.
        let captured = screen_of("\u{0645}\u{001b}[31m\u{0631}\u{001b}[0m".as_bytes(), 2, 20);
        let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
        assert_eq!(
            run.cells.len(),
            1,
            "the run crossed a style boundary: {:?}",
            run.cells
        );
        // Same two letters in one style shape together.
        let captured = screen_of("\u{0645}\u{0631}".as_bytes(), 2, 20);
        let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
        assert_eq!(
            run.cells.len(),
            2,
            "same-style Arabic did not shape as one run"
        );
    }

    /// Spaces between words stay inside a contiguous RTL run so the bidi
    /// shaper sees the phrase as a phrase rather than independently reversing
    /// and anchoring each word.
    #[test]
    fn an_arabic_phrase_shapes_across_its_space() {
        let renderer = renderer_with(None, &[]);
        let fonts = &renderer.default_fonts;
        let phrase = "\u{0645}\u{0631}\u{062D}\u{0628}\u{0627} \
                      \u{0628}\u{0627}\u{0644}\u{0639}\u{0627}\u{0644}\u{0645}";
        let captured = screen_of(phrase.as_bytes(), 2, 30);
        let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 30, None);
        assert_eq!(
            run.cells
                .iter()
                .map(|cell| cell.text.as_str())
                .collect::<String>(),
            phrase
        );
        assert_eq!(run.cols, phrase.chars().count() as u32);
    }

    #[test]
    fn a_supported_width_arabic_phrase_stays_in_one_run() {
        let renderer = renderer_with(None, &[]);
        let fonts = &renderer.default_fonts;
        let phrase = "\u{0645}\u{0631}\u{062D}\u{0628}\u{0627} ".repeat(80);
        let captured = screen_of(phrase.as_bytes(), 2, 500);
        let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 500, None);
        assert!(
            run.cols > 256 && run.cols <= 500,
            "fixture must cross the ordinary shaping limit"
        );
        assert_eq!(
            run.cells
                .iter()
                .map(|cell| cell.text.as_str())
                .collect::<String>(),
            phrase.trim_end()
        );
    }

    /// A run also stops where the *kind* of shaping changes: a joining script
    /// is laid out as one contiguous piece and an emoji is projected cluster
    /// by cluster, so mixing them in one run would apply the wrong rule to
    /// half of it.
    #[test]
    fn a_shaped_run_stops_where_the_shaping_kind_changes() {
        let renderer = renderer_with(None, &[]);
        let fonts = &renderer.default_fonts;

        // Arabic followed by an emoji: two runs, not one.
        let captured = screen_of("\u{0645}\u{1F600}".as_bytes(), 2, 20);
        let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
        assert_eq!(run.cells.len(), 1, "an emoji joined an Arabic run");

        // The pieces vt100 splits an emoji sequence into are all emoji, so
        // they still shape as one run - which is what makes the picture right.
        let captured = screen_of("\u{1F44D}\u{1F3FD}".as_bytes(), 2, 20);
        let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
        assert_eq!(
            run.cells.len(),
            2,
            "a split emoji sequence did not shape as one run"
        );
        assert_eq!(run.cols, 4, "the run must own every column vt100 gave it");
    }

    /// A run stops at a redacted cell, so nothing shaped is ever laid out
    /// across a redaction block.
    #[test]
    fn a_shaped_run_stops_at_a_redaction_boundary() {
        use crate::redaction::RedactionMap;

        let renderer = renderer_with(None, &[]);
        let fonts = &renderer.default_fonts;
        let captured = screen_of("\u{0645}\u{0631}\u{062D}".as_bytes(), 2, 20);

        let mut map = RedactionMap::default();
        map.add_manual(0, 1, 2, None);
        let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, Some(&map));
        assert_eq!(
            run.cells.len(),
            1,
            "the run ran into a redacted cell: {:?}",
            run.cells
        );
    }

    /// Explicit fonts are searched in the order they were configured, and that
    /// order decides which glyph a shaped run gets. The two fixtures ink
    /// opposite halves of the cell, so the pixels say which one won.
    #[test]
    fn configured_font_order_decides_a_shaped_glyph() {
        let ka = DEVANAGARI_KA.to_string();
        for (fallbacks, expect_left) in [([SHAPE_A, SHAPE_B], true), ([SHAPE_B, SHAPE_A], false)] {
            let renderer = renderer_with(None, &fallbacks);
            let img = render_line(&renderer, &ka, 6);
            let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
            let padding = renderer.padding * RENDER_SCALE;
            let left = ink_in_columns(&img, padding, padding + cell_w / 2);
            let right = ink_in_columns(&img, padding + cell_w / 2, padding + cell_w);
            if expect_left {
                assert!(
                    left > right,
                    "{fallbacks:?}: expected the first font's left bar, got left={left} right={right}"
                );
            } else {
                assert!(
                    right > left,
                    "{fallbacks:?}: expected the first font's right bar, got left={left} right={right}"
                );
            }
        }
    }

    /// The families the shaper will try are the configured chain, in order,
    /// with the embedded font between the explicit faces and the fallbacks.
    #[test]
    fn shaped_font_precedence_matches_the_configured_chain() {
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[SHAPE_A, SHAPE_B]);
        assert_eq!(
            renderer.default_fonts.shaping().families(),
            vec![
                "Termshot Test ASCII".to_string(),
                "JetBrains Mono".to_string(),
                "Termshot Shape A".to_string(),
                "Termshot Shape B".to_string(),
            ]
        );
    }

    /// Every face of a font collection is loaded with the index `fontdb`
    /// discovered, not collapsed onto face 0.
    #[test]
    fn font_collection_faces_keep_their_indices() {
        let renderer = renderer_with(None, &[COLLECTION]);
        let faces = renderer.default_fonts.shaping().loaded_faces();
        assert!(
            faces.contains(&("Termshot Collection Zero".to_string(), 0)),
            "face 0 missing from {faces:?}"
        );
        assert!(
            faces.contains(&("Termshot Collection One".to_string(), 1)),
            "face 1 missing from {faces:?}"
        );
    }

    /// `fontdue` only ever loads face 0 of a collection, so a character that
    /// exists only in face 1 proves the shaped path used the right index.
    #[test]
    fn a_glyph_only_in_the_second_collection_face_still_renders() {
        // A primary face whose `.notdef` is empty, so "nothing was drawn"
        // really means nothing: the embedded JetBrains Mono draws a tofu box
        // for a character no font covers, exactly as it did in 1.1.5.
        let renderer = renderer_with(Some(LIMITED_PRIMARY), &[COLLECTION]);
        assert!(
            ink(&render_line(&renderer, "\u{E021}", 6)) > 0,
            "the second collection face was never reached"
        );
        assert_eq!(
            ink(&render_line(&renderer, "\u{E022}", 6)),
            0,
            "a code point no configured face covers must stay blank"
        );
    }

    /// A cluster that asks for emoji presentation is shaped with a color font
    /// when one is configured, and its own palette reaches the canvas.
    #[test]
    fn emoji_presentation_uses_a_configured_color_font() {
        let renderer = renderer_with(None, &[COLOR_EMOJI]);
        assert_eq!(
            renderer.default_fonts.shaping().emoji_family().as_deref(),
            Some("Termshot Color Emoji")
        );
        let img = render_line(&renderer, "\u{1F600}", 6);
        let reds = count_near(&img, Rgba([255, 0, 0, 255]));
        let blues = count_near(&img, Rgba([0, 0, 255, 255]));
        assert!(
            reds > 0 && blues > 0,
            "color layers missing: {reds} red, {blues} blue pixels"
        );
    }

    /// Variation selectors decide presentation: `FE0F` asks for the color
    /// font, `FE0E` keeps the monochrome text glyph.
    #[test]
    fn variation_selectors_choose_the_presentation() {
        // A monochrome font covering U+2764 ahead of the color one, so the
        // test can tell "text presentation" from "no glyph at all".
        let renderer = renderer_with(None, &[SHAPE_A, COLOR_EMOJI]);

        let emoji = render_line(&renderer, "\u{2764}\u{FE0F}", 6);
        assert!(
            count_near(&emoji, Rgba([255, 0, 0, 255])) > 0
                && count_near(&emoji, Rgba([0, 0, 255, 255])) > 0,
            "VS16 did not select the color font"
        );

        let text = render_line(&renderer, "\u{2764}\u{FE0E}", 6);
        assert_eq!(
            count_near(&text, Rgba([0, 0, 255, 255])),
            0,
            "VS15 must keep the text presentation, not the color font"
        );
        assert!(ink(&text) > 0, "VS15 drew no glyph at all");
    }

    /// The renderer is shared behind an `Arc` by the MCP server and its tokio
    /// tasks, so everything the shaped path added has to stay shareable: the
    /// font system, the swash scaler, and the caches all sit behind one mutex
    /// that is taken per run, never for a whole image.
    #[test]
    fn the_renderer_stays_shareable_across_threads() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Renderer>();
        assert_send_sync::<ThemeFonts>();
    }

    /// Pixels within a small distance of `want`, so anti-aliased edges of a
    /// palette color still count.
    fn count_near(img: &RgbaImage, want: Rgba<u8>) -> usize {
        img.pixels()
            .filter(|p| (0..3).all(|i| (p[i] as i32 - want[i] as i32).abs() <= 40) && p[3] > 200)
            .count()
    }
}