superlighttui 0.22.0

Super Light TUI - A lightweight, ergonomic terminal UI library
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
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::{self, BufWriter, Read, Stdout, Write};
use std::time::{Duration, Instant};

use crossterm::event::{
    DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
    EnableFocusChange, EnableMouseCapture,
};
use crossterm::style::{
    Attribute, Color as CtColor, Print, ResetColor, SetAttribute, SetBackgroundColor,
    SetForegroundColor,
};
use crossterm::terminal::{BeginSynchronizedUpdate, EndSynchronizedUpdate};
use crossterm::{cursor, execute, queue, terminal};

use unicode_width::UnicodeWidthStr;

use crate::buffer::{Buffer, KittyPlacement};
use crate::rect::Rect;
use crate::style::{Color, ColorDepth, Modifiers, Style, UnderlineStyle};

/// Saturating cast from `u32` to `u16` — clamps to `u16::MAX` instead of truncating.
#[inline]
fn sat_u16(v: u32) -> u16 {
    v.min(u16::MAX as u32) as u16
}

/// Output sink for a [`Terminal`] / [`InlineTerminal`] flush pipeline.
///
/// The production path is always [`Sink::Stdout`], a `BufWriter<Stdout>` — its
/// byte stream and buffering are byte-for-byte identical to the pre-seam code
/// (the [`Write`] impl below is a thin delegation, so the hot path is
/// unchanged). When the `pty-test` dev feature (or `cfg(test)`) is enabled, a
/// second [`Sink::Capture`] variant lets the PTY test harness drive the *real*
/// flush emitters into an in-process `Vec<u8>` instead of a terminal, so the
/// emitted escape / image-protocol bytes can be asserted end-to-end. The
/// capture variant never exists in a default build.
pub(crate) enum Sink {
    /// Production sink: buffered stdout.
    Stdout(BufWriter<Stdout>),
    /// Test sink: in-process byte capture, used only by the PTY harness.
    #[cfg(any(test, feature = "pty-test"))]
    Capture(Vec<u8>),
}

impl Write for Sink {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            Sink::Stdout(w) => w.write(buf),
            #[cfg(any(test, feature = "pty-test"))]
            Sink::Capture(v) => v.write(buf),
        }
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        match self {
            Sink::Stdout(w) => w.flush(),
            #[cfg(any(test, feature = "pty-test"))]
            Sink::Capture(v) => v.flush(),
        }
    }
}

// ---------------------------------------------------------------------------
// Kitty graphics protocol image manager
// ---------------------------------------------------------------------------

/// Manages Kitty graphics protocol image IDs, uploads, and placements.
///
/// Images are deduplicated by content hash — identical RGBA data is uploaded
/// only once. Each frame, placements are diffed against the previous frame
/// to minimize terminal I/O.
pub(crate) struct KittyImageManager {
    next_id: u32,
    /// content_hash → kitty image ID for uploaded images.
    uploaded: HashMap<u64, u32>,
    /// Previous frame's placements (for diff).
    prev_placements: Vec<KittyPlacement>,
    /// Reused dedup scratch for already-deleted image IDs in `flush`. Typical
    /// placement counts are 0–8 (well below where a `HashSet` beats a linear /
    /// sorted scan), so a `SmallVec` stays on the stack and carries its
    /// capacity across frames — no per-frame heap allocation, no SipHash.
    scratch_ids: smallvec::SmallVec<[u32; 8]>,
    /// Reused scratch for content hashes still referenced this frame, used to
    /// prune stale uploads. Sorted in place for `binary_search` membership.
    scratch_hashes: smallvec::SmallVec<[u64; 8]>,
}

impl KittyImageManager {
    /// Construct a new image manager with no uploaded images.
    pub(crate) fn new() -> Self {
        Self {
            next_id: 1,
            uploaded: HashMap::new(),
            prev_placements: Vec::new(),
            scratch_ids: smallvec::SmallVec::new(),
            scratch_hashes: smallvec::SmallVec::new(),
        }
    }

    /// Flush Kitty image placements: upload new images, manage placements.
    ///
    /// `row_offset` shifts `current[i].y` for both terminal output and the
    /// diff comparison against `prev_placements`. Stored placements always
    /// include the offset (the displayed `y`) so re-emit detection works
    /// across resize even when the offset itself changes (issue #206).
    pub(crate) fn flush(
        &mut self,
        stdout: &mut impl Write,
        current: &[KittyPlacement],
        row_offset: u32,
    ) -> io::Result<()> {
        // Fast path: nothing changed (compare against post-offset y values
        // stored in `prev_placements`). This avoids materializing a translated
        // `Vec<KittyPlacement>` in the caller (issue #206).
        if current.len() == self.prev_placements.len()
            && current
                .iter()
                .zip(self.prev_placements.iter())
                .all(|(c, p)| placement_eq_with_offset(c, row_offset, p))
        {
            return Ok(());
        }

        // Delete all previous placements (keep uploaded image data for reuse).
        // Dedup via a reused `SmallVec` instead of a per-frame `HashSet`: at the
        // 0–8 image counts this path actually sees, a linear membership scan
        // beats hashing, and the scratch keeps its capacity across frames. The
        // emit order (first-seen) is unchanged, so the byte stream is identical.
        if !self.prev_placements.is_empty() {
            self.scratch_ids.clear();
            for p in &self.prev_placements {
                if let Some(&img_id) = self.uploaded.get(&p.content_hash)
                    && !self.scratch_ids.contains(&img_id)
                {
                    self.scratch_ids.push(img_id);
                    // Delete all placements of this image (but keep image data)
                    queue!(
                        stdout,
                        Print(format!("\x1b_Ga=d,d=i,i={},q=2\x1b\\", img_id))
                    )?;
                }
            }
        }

        // Upload new images and create placements
        for (idx, p) in current.iter().enumerate() {
            let img_id = if let Some(&existing_id) = self.uploaded.get(&p.content_hash) {
                existing_id
            } else {
                // Upload new image with zlib compression if available
                let id = self.next_id;
                self.next_id += 1;
                self.upload_image(stdout, id, p)?;
                self.uploaded.insert(p.content_hash, id);
                id
            };

            // Place the image (with row_offset applied to y at point of use).
            let pid = idx as u32 + 1;
            self.place_image_offset(stdout, img_id, pid, p, row_offset)?;
        }

        // Clean up images no longer used by any placement. Build the
        // still-referenced hash set into a reused `SmallVec`, sort it, and test
        // membership with `binary_search` instead of a per-frame `HashSet`.
        // (The set of stale uploads is the same regardless of scan order; the
        // delete emission was already unordered via `HashMap` key iteration.)
        self.scratch_hashes.clear();
        self.scratch_hashes
            .extend(current.iter().map(|p| p.content_hash));
        self.scratch_hashes.sort_unstable();
        let scratch_hashes = &self.scratch_hashes;
        let stale: smallvec::SmallVec<[u64; 8]> = self
            .uploaded
            .keys()
            .filter(|h| scratch_hashes.binary_search(h).is_err())
            .copied()
            .collect();
        for hash in stale {
            if let Some(id) = self.uploaded.remove(&hash) {
                // Delete image data from terminal memory
                queue!(stdout, Print(format!("\x1b_Ga=d,d=I,i={},q=2\x1b\\", id)))?;
            }
        }

        // Persist post-offset placements for the next frame's diff. We still
        // write `current.len()` items but rebuild the Vec in place — capacity
        // is preserved across frames so this is at most an `Arc::clone` per
        // image (the `Vec<u8>` is shared via `Arc`, no pixel copy). This
        // remains the only `Arc::clone` cost; the per-frame `Vec` allocation
        // in the caller (`InlineTerminal::flush`) is what #206 eliminates.
        self.prev_placements.clear();
        self.prev_placements.reserve(current.len());
        for p in current {
            let mut copy = p.clone();
            copy.y = copy.y.saturating_add(row_offset);
            self.prev_placements.push(copy);
        }
        Ok(())
    }

    /// Upload image data to the terminal with `a=t` (transmit only, no display).
    fn upload_image(&self, stdout: &mut impl Write, id: u32, p: &KittyPlacement) -> io::Result<()> {
        let (payload, compression) = compress_rgba(&p.rgba);
        let encoded = base64_encode(&payload);
        let chunks = split_base64(&encoded, 4096);

        for (i, chunk) in chunks.iter().enumerate() {
            let more = if i < chunks.len() - 1 { 1 } else { 0 };
            if i == 0 {
                queue!(
                    stdout,
                    Print(format!(
                        "\x1b_Ga=t,i={},f=32,{}s={},v={},q=2,m={};{}\x1b\\",
                        id, compression, p.src_width, p.src_height, more, chunk
                    ))
                )?;
            } else {
                queue!(stdout, Print(format!("\x1b_Gm={};{}\x1b\\", more, chunk)))?;
            }
        }
        Ok(())
    }

    /// Place an already-uploaded image at a screen position with optional crop.
    ///
    /// `row_offset` is added to `p.y` at output time so callers (notably
    /// `InlineTerminal::flush`) can avoid materializing a translated copy of
    /// the placements list per frame (issue #206).
    fn place_image_offset(
        &self,
        stdout: &mut impl Write,
        img_id: u32,
        placement_id: u32,
        p: &KittyPlacement,
        row_offset: u32,
    ) -> io::Result<()> {
        let display_y = p.y.saturating_add(row_offset);
        queue!(stdout, cursor::MoveTo(sat_u16(p.x), sat_u16(display_y)))?;

        let mut cmd = format!(
            "\x1b_Ga=p,i={},p={},c={},r={},C=1,q=2",
            img_id, placement_id, p.cols, p.rows
        );

        // Add crop parameters for scroll clipping
        if p.crop_y > 0 || p.crop_h > 0 {
            cmd.push_str(&format!(",y={}", p.crop_y));
            if p.crop_h > 0 {
                cmd.push_str(&format!(",h={}", p.crop_h));
            }
        }

        cmd.push_str("\x1b\\");
        queue!(stdout, Print(cmd))?;
        Ok(())
    }

    /// Delete all images from the terminal (used on drop/cleanup).
    pub(crate) fn delete_all(&self, stdout: &mut impl Write) -> io::Result<()> {
        queue!(stdout, Print("\x1b_Ga=d,d=A,q=2\x1b\\"))
    }
}

/// Compare a fresh placement (`current`, in pre-offset coordinates) against a
/// stored placement (`prev`, already includes any prior `row_offset`).
///
/// Equivalent to `*current == *prev` after virtually applying `row_offset` to
/// `current.y`, without materializing the translated copy. Used by
/// `KittyImageManager::flush` to keep the diff fast-path even when the inline
/// terminal applies a non-zero offset (issue #206).
#[inline]
fn placement_eq_with_offset(
    current: &KittyPlacement,
    row_offset: u32,
    prev: &KittyPlacement,
) -> bool {
    current.content_hash == prev.content_hash
        && current.x == prev.x
        && current.y.saturating_add(row_offset) == prev.y
        && current.cols == prev.cols
        && current.rows == prev.rows
        && current.crop_y == prev.crop_y
        && current.crop_h == prev.crop_h
}

/// Compress RGBA data with zlib if available, returning (payload, format_string).
///
/// The payload is returned as a [`Cow`] so the no-compression path (the
/// `kitty-compress` feature off, or compression that fails to save space)
/// **borrows** the caller's slice instead of cloning the full RGBA buffer into
/// a throwaway `Vec` on every `upload_image` call. The compressed path still
/// returns an owned `Vec`. The downstream `base64_encode(&payload)` call sees
/// `&[u8]` via `Deref` in both cases, so no signature change ripples out.
fn compress_rgba(data: &[u8]) -> (Cow<'_, [u8]>, &'static str) {
    #[cfg(feature = "kitty-compress")]
    {
        use flate2::Compression;
        use flate2::write::ZlibEncoder;
        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast());
        if encoder.write_all(data).is_ok()
            && let Ok(compressed) = encoder.finish()
        {
            // Only use compression if it actually saves space
            if compressed.len() < data.len() {
                return (Cow::Owned(compressed), "o=z,");
            }
        }
    }
    (Cow::Borrowed(data), "")
}

/// Query the terminal for the actual cell pixel dimensions via CSI 16 t.
///
/// Returns `(cell_width, cell_height)` in pixels. Falls back to `(8, 16)` if
/// detection fails. Used by `kitty_image_fit` for accurate aspect ratio.
///
/// Cached after first successful detection.
pub(crate) fn cell_pixel_size() -> (u32, u32) {
    use std::sync::OnceLock;
    static CACHED: OnceLock<(u32, u32)> = OnceLock::new();
    *CACHED.get_or_init(|| detect_cell_pixel_size().unwrap_or((8, 16)))
}

fn detect_cell_pixel_size() -> Option<(u32, u32)> {
    // CSI 16 t → reports cell size as CSI 6 ; height ; width t
    let mut stdout = io::stdout();
    write!(stdout, "\x1b[16t").ok()?;
    stdout.flush().ok()?;

    let response = read_osc_response(Duration::from_millis(100))?;

    // Parse: ESC [ 6 ; <height> ; <width> t
    // Locate the reply anywhere in the buffer rather than anchoring to its
    // start/end: interleaved control bytes — e.g. a pump-retirement nudge
    // answer (`CSI 0 n`) from a previous reply session — may surround it.
    let bytes = response.as_bytes();
    let start = bytes
        .windows(4)
        .position(|w| w == b"\x1b[6;")
        .map(|pos| pos + 4)
        .or_else(|| {
            // CSI can also start with 0x9B (single-byte CSI).
            bytes
                .windows(3)
                .position(|w| w == [0x9b, b'6', b';'])
                .map(|pos| pos + 3)
        })?;
    let tail = response.get(start..)?;
    let body = &tail[..tail.find('t')?];
    let mut parts = body.split(';');
    let ch: u32 = parts.next()?.parse().ok()?;
    let cw: u32 = parts.next()?.parse().ok()?;
    if cw > 0 && ch > 0 {
        Some((cw, ch))
    } else {
        None
    }
}

// ---------------------------------------------------------------------------
// Runtime terminal capability probe (issue #264)
// ---------------------------------------------------------------------------
//
// Historically SLT decided whether a terminal could render images / accept the
// Kitty keyboard protocol / do truecolor *purely from environment-variable
// allowlists*, which silently degraded capable modern terminals (WezTerm,
// Ghostty) to an error string. This block adds a one-shot DA1/DA2/XTGETTCAP
// probe at session enter, parses the replies into a read-only [`Capabilities`]
// snapshot, and drives an automatic blitter ladder so app code never has to
// branch on terminal identity. The data types are always compiled (so the
// `Context` field exists on every build); only the runtime probe is
// `crossterm`-gated.

/// Image-rendering primitives the terminal can drive, used to build the
/// automatic blitter ladder. Each flag is conservative: when the runtime probe
/// returns no answer the defaults assume only the universally available
/// primitives (half-block + quadrants).
///
/// App code is **not** required to inspect this; it exists for diagnostics and
/// to feed [`Capabilities::best_blitter`].
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// let blitters = ui.capabilities().blitters;
/// // Half-block is available on any ANSI terminal.
/// assert!(blitters.half);
/// # });
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlitterSupport {
    /// `▀` upper-half block — available on any ANSI terminal.
    pub half: bool,
    /// `▖▗▘▝` quadrant blocks — available on any Unicode-capable terminal.
    pub quad: bool,
    /// `🬀`..`🬻` sextants (Unicode 13+) — off by default until a renderer
    /// confirms support. This issue wires the capability slot; a sextant
    /// renderer is a separate feature.
    pub sextant: bool,
}

impl Default for BlitterSupport {
    fn default() -> Self {
        Self {
            half: true,
            quad: true,
            sextant: false,
        }
    }
}

/// Read-only snapshot of negotiated terminal capabilities, populated once at
/// session enter via DA1/DA2/XTGETTCAP.
///
/// App code **must not** be required to branch on this — it exists for
/// diagnostics and to drive the automatic blitter ladder (see
/// [`Capabilities::best_blitter`]). On a headless backend (TestBackend / piped
/// stdout) or when the probe gets no reply, every field falls back to a
/// conservative default.
///
/// Available since `0.21.0`.
///
/// # Example
///
/// ```no_run
/// # slt::run(|ui: &mut slt::Context| {
/// let caps = ui.capabilities();
/// if caps.sixel {
///     // Diagnostics only — image rendering already routes through the ladder.
/// }
/// # });
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Capabilities {
    /// 24-bit color confirmed (XTGETTCAP `Tc`/`RGB` or `COLORTERM`).
    pub truecolor: bool,
    /// Sixel graphics confirmed (DA1 attribute `4`).
    pub sixel: bool,
    /// iTerm2 OSC 1337 inline-image protocol confirmed (env identity for
    /// iTerm2 / WezTerm / Tabby / mintty; issue #265).
    pub iterm2: bool,
    /// Kitty graphics protocol confirmed (DA2 terminal-ID heuristic).
    pub kitty_graphics: bool,
    /// Kitty keyboard protocol confirmed.
    pub kitty_keyboard: bool,
    /// Synchronized output (DECSET 2026) confirmed.
    pub sync_output: bool,
    /// Set of cell-art blitters the terminal can drive.
    pub blitters: BlitterSupport,
}

/// Descending image-render preference. The first capability that is available
/// wins; app code never selects a [`Blitter`] directly.
///
/// Ladder order: [`Kitty`](Blitter::Kitty) > [`Sixel`](Blitter::Sixel) >
/// [`Iterm2`](Blitter::Iterm2) > [`Sextant`](Blitter::Sextant) >
/// [`HalfBlock`](Blitter::HalfBlock).
///
/// Available since `0.21.0`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Blitter {
    /// Kitty graphics protocol (highest fidelity).
    Kitty,
    /// Sixel graphics protocol.
    Sixel,
    /// iTerm2 OSC 1337 inline-image protocol (issue #265). Pixel-accurate on
    /// Tabby, older iTerm2, and WezTerm's iTerm2-compat mode.
    Iterm2,
    /// Unicode sextant cell art.
    Sextant,
    /// Half-block cell art (universal fallback).
    HalfBlock,
}

impl Capabilities {
    /// Resolve the best available image blitter for this terminal.
    ///
    /// Returns the first supported rung of the ladder
    /// (Kitty > Sixel > iTerm2 > Sextant > HalfBlock). This is total: it always
    /// returns a [`Blitter`], falling through to [`Blitter::HalfBlock`] which
    /// every terminal supports.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// let _ = ui.capabilities().best_blitter();
    /// # });
    /// ```
    pub fn best_blitter(&self) -> Blitter {
        if self.kitty_graphics {
            Blitter::Kitty
        } else if self.sixel {
            Blitter::Sixel
        } else if self.iterm2 {
            Blitter::Iterm2
        } else if self.blitters.sextant {
            Blitter::Sextant
        } else {
            Blitter::HalfBlock
        }
    }
}

/// Return the process-global negotiated [`Capabilities`], probing the terminal
/// exactly once on first call and caching the result.
///
/// The probe issues DA1 (`CSI c`), DA2 (`CSI > c`), and XTGETTCAP for the
/// truecolor capname, reading replies through the existing OSC round-trip
/// infrastructure with a bounded total timeout (≤150ms). On no reply every
/// field falls back to a conservative default. Repeated calls are free.
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn capabilities() -> Capabilities {
    use std::sync::OnceLock;
    static CACHED: OnceLock<Capabilities> = OnceLock::new();
    *CACHED.get_or_init(probe_capabilities)
}

/// Send DA1/DA2/XTGETTCAP and parse the replies into a [`Capabilities`].
///
/// Conservative on failure: any unread / unparsable reply leaves the
/// corresponding flag at its default. The total stdin wait is bounded to keep
/// startup latency within the same budget as the existing OSC 11 query.
#[cfg(feature = "crossterm")]
fn probe_capabilities() -> Capabilities {
    let mut caps = Capabilities::default();

    // Total stdin wait is bounded to ≤180ms (90 + 30 + 30 + 30) so a silent
    // terminal cannot stall startup beyond a small multiple of the existing
    // OSC-11 budget. A responsive terminal replies in well under 10ms per
    // query, so the common path adds negligible latency.
    let mut out = io::stdout();
    // DA1 then DA2 in one write — both terminate with `c`, so a single
    // DA-aware read drains both replies (in order) when supported.
    if write!(out, "\x1b[c\x1b[>c").is_ok()
        && out.flush().is_ok()
        && let Some(resp) = read_da_response(Duration::from_millis(90))
    {
        parse_da1(&resp, &mut caps);
        parse_da2(&resp, &mut caps);
    }

    // Kitty graphics query: APC G a=q (query) with a 1×1 RGB direct payload.
    // Supporting terminals ack with `APC G i=31;OK ST`; others stay silent so
    // the bounded read just times out. Base64 of three zero bytes = "AAAA".
    if write!(out, "\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\").is_ok()
        && out.flush().is_ok()
        && let Some(resp) = read_osc_response(Duration::from_millis(30))
    {
        parse_kitty_graphics_ack(&resp, &mut caps);
    }

    // XTGETTCAP for the `Tc` (truecolor) capname: DCS + q <hex> ST.
    // `Tc` -> hex "5463".
    if write!(out, "\x1bP+q5463\x1b\\").is_ok()
        && out.flush().is_ok()
        && let Some(resp) = read_osc_response(Duration::from_millis(30))
    {
        parse_xtgettcap_truecolor(&resp, &mut caps);
    }

    // DECRQM for synchronized output (mode ?2026): CSI ? 2026 $ p. A supporting
    // terminal replies CSI ? 2026 ; <Ps> $ y, where Ps ∈ {1,2} (set / reset)
    // both mean *recognized*; Ps = 0 means the mode is not recognized. The
    // reply terminates with `y` rather than BEL / ST, so it needs the
    // DECRPM-aware reader. A silent terminal leaves the resolution `Unknown`,
    // which the flush gate treats as "keep emitting" — preserving the historic
    // always-emit behavior on headless / non-answering hosts.
    if write!(out, "\x1b[?2026$p").is_ok()
        && out.flush().is_ok()
        && let Some(resp) = read_decrpm_response(Duration::from_millis(30))
    {
        match parse_decrpm_sync_output(&resp) {
            Some(true) => {
                caps.sync_output = true;
                let _ = SYNC_OUTPUT_RESOLUTION.set(SyncOutputResolution::Supported);
            }
            Some(false) => {
                let _ = SYNC_OUTPUT_RESOLUTION.set(SyncOutputResolution::Unsupported);
            }
            None => {}
        }
    }

    // Env precedence chain stays authoritative for truecolor: a positive
    // COLORTERM/TERM signal confirms it even when the probe is silent.
    if matches!(ColorDepth::detect(), ColorDepth::TrueColor) {
        caps.truecolor = true;
    }

    // Env-fallback: when the runtime queries are silent (no reply within the
    // timeout), trust the terminal identity for the Kitty-graphics family so a
    // known-capable host (Kitty, Ghostty, WezTerm) still climbs the top rung.
    // The query above wins when it answers; this only fills an unknown.
    if !caps.kitty_graphics && term_is_kitty_graphics_host() {
        caps.kitty_graphics = true;
    }

    // iTerm2 OSC 1337 has no DA1/DA2 signal (issue #265): the protocol is
    // identified purely by terminal identity. Fill the capability slot from the
    // env so the blitter ladder can offer it below Kitty/Sixel.
    if term_is_iterm_host() {
        caps.iterm2 = true;
    }

    caps
}

/// Heuristic env-detection for iTerm2 OSC 1337 inline-image hosts (issue #265).
///
/// The protocol carries no DA reply, so detection is by `TERM_PROGRAM` identity
/// only: iTerm2, WezTerm (iTerm2-compat), Tabby, and mintty.
#[cfg(feature = "crossterm")]
fn term_is_iterm_host() -> bool {
    let term_program = std::env::var("TERM_PROGRAM")
        .unwrap_or_default()
        .to_ascii_lowercase();
    matches!(
        term_program.as_str(),
        "iterm.app" | "wezterm" | "tabby" | "mintty"
    )
}

/// Heuristic env-fallback for Kitty-graphics hosts, consulted only when the
/// runtime Kitty graphics query returned no reply. Matches the documented
/// `TERM` / `TERM_PROGRAM` identities of terminals that implement the Kitty
/// graphics protocol.
#[cfg(feature = "crossterm")]
fn term_is_kitty_graphics_host() -> bool {
    let term = std::env::var("TERM")
        .unwrap_or_default()
        .to_ascii_lowercase();
    let term_program = std::env::var("TERM_PROGRAM")
        .unwrap_or_default()
        .to_ascii_lowercase();
    // Kitty sets `TERM=xterm-kitty`; Ghostty/WezTerm advertise via TERM_PROGRAM.
    term.contains("kitty") || matches!(term_program.as_str(), "ghostty" | "wezterm" | "kitty")
}

/// Process-wide pump that owns the only blocking `stdin` read used for
/// terminal-reply probing. See [`read_stdin_reply`] for why it exists.
#[cfg(feature = "crossterm")]
struct ReplyPump {
    rx: std::sync::mpsc::Receiver<u8>,
    /// `true` while a reader session wants bytes. The pump thread re-checks it
    /// after every successful read and exits once it is cleared.
    serve: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Set by the pump thread on exit, distinguishing "parked inside a
    /// blocking `read()`" (reusable) from "gone" (must respawn).
    exited: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

#[cfg(feature = "crossterm")]
static REPLY_PUMP: std::sync::Mutex<Option<ReplyPump>> = std::sync::Mutex::new(None);

/// Read one terminal reply from raw stdin, hard-bounded by `timeout`, stopping
/// early once `is_complete` recognizes a full reply (or at the 4096-byte cap).
///
/// Why a pump thread: the previous readers gated a blocking
/// `io::stdin().read()` behind `crossterm::event::poll()`. Those two observe
/// different things — `poll()` answers "does crossterm's *internal event
/// queue* have something?", while the raw `read()` waits for bytes on the
/// stdin descriptor — and crossterm's poller consumes bytes from that same
/// descriptor into its own parser. On a host that never answers probe queries
/// (a detached tmux pane, `script`-style PTY wrappers, CI runners), `poll()`
/// could return `true` for a queued non-byte event while raw stdin stayed
/// empty, so the one-byte `read()` blocked forever *inside* the deadline loop
/// and the application hung on a blank alternate screen before its first
/// frame; later keystrokes were swallowed by crossterm's queue instead of
/// unblocking it. Moving the only blocking `read()` onto a dedicated thread
/// and waiting on a channel with `recv_timeout` makes every reply read
/// genuinely bounded by its budget no matter what the host does.
///
/// The pump is a process-wide singleton so back-to-back probes share one byte
/// stream instead of racing two readers for the same reply. After each
/// session the thread is retired: `serve` is cleared and a DSR status query
/// (`CSI 5 n`) nudges the terminal — an answering host replies `CSI 0 n`,
/// which wakes the parked `read()`, the thread observes `serve == false` and
/// exits, and the nudge bytes stay in the channel where the next session's
/// drain discards them (they never reach the application's input stream). A
/// host that answers nothing leaves the thread parked; it is reused by the
/// next session, and at worst it swallows one byte of typeahead on a host
/// class where, before this fix, startup deadlocked outright.
#[cfg(feature = "crossterm")]
fn read_stdin_reply(
    timeout: Duration,
    mut is_complete: impl FnMut(&[u8]) -> bool,
) -> Option<String> {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, mpsc};

    let deadline = Instant::now() + timeout;

    let Ok(mut slot) = REPLY_PUMP.lock() else {
        // Poisoned: a prior session panicked mid-read. Skip probing entirely
        // rather than risk a second fault; every caller treats `None` as "the
        // terminal stayed silent".
        return None;
    };

    let pump = match slot.take().filter(|p| !p.exited.load(Ordering::Acquire)) {
        Some(pump) => {
            // A parked pump from an earlier session: its thread is still
            // blocked in `read()` on a silent host. Reusing it (instead of
            // spawning a second thread) is what prevents two readers from
            // racing each other for the same reply bytes.
            pump.serve.store(true, Ordering::Release);
            pump
        }
        None => {
            let (tx, rx) = mpsc::channel::<u8>();
            let serve = Arc::new(AtomicBool::new(true));
            let exited = Arc::new(AtomicBool::new(false));
            let thread_serve = Arc::clone(&serve);
            let thread_exited = Arc::clone(&exited);
            let spawned = std::thread::Builder::new()
                .name("slt-reply-pump".into())
                .spawn(move || {
                    let mut stdin = io::stdin();
                    // One byte per read on purpose: a parked thread that wakes
                    // on real key input forwards at most this single byte
                    // before observing `serve == false` and exiting, so the
                    // worst-case typeahead loss on a silent host is exactly
                    // one byte (replies are short; the syscall-per-byte cost
                    // is irrelevant for one-shot probes).
                    let mut buf = [0u8; 1];
                    loop {
                        match stdin.read(&mut buf) {
                            Ok(0) | Err(_) => break,
                            Ok(_) => {
                                if tx.send(buf[0]).is_err() {
                                    thread_exited.store(true, Ordering::Release);
                                    return;
                                }
                            }
                        }
                        if !thread_serve.load(Ordering::Acquire) {
                            break;
                        }
                    }
                    thread_exited.store(true, Ordering::Release);
                });
            if spawned.is_err() {
                return None;
            }
            ReplyPump { rx, serve, exited }
        }
    };

    // Discard bytes left over from a previous session: a reply that arrived
    // after its deadline, or the retirement nudge's `CSI 0 n` answer.
    while pump.rx.try_recv().is_ok() {}

    let bytes = collect_reply(&pump.rx, deadline, &mut is_complete);

    // Retire the thread so it does not sit on a pending `read()` competing
    // with crossterm's event loop for real key input once the session ends.
    // The nudge fires only under raw mode (the `run()` / session-enter probe
    // paths): in cooked mode — e.g. a standalone `detect_color_scheme()`
    // call — the terminal would *echo* its `CSI 0 n` answer into the user's
    // scrollback as visible garbage, so there the parked thread is simply
    // left for the next session to reuse.
    pump.serve.store(false, Ordering::Release);
    if crossterm::terminal::is_raw_mode_enabled().unwrap_or(false) {
        let mut out = io::stdout();
        let _ = write!(out, "\x1b[5n");
        let _ = out.flush();
    }
    *slot = Some(pump);
    drop(slot);

    if bytes.is_empty() {
        return None;
    }
    String::from_utf8(bytes).ok()
}

/// Deadline-bounded accumulation loop shared by every reply reader: pull bytes
/// off the pump channel until `is_complete` fires, the 4096-byte cap is hit,
/// the deadline passes, or the pump disconnects (stdin EOF). Returns whatever
/// arrived — callers map an empty buffer to "no reply" and a partial buffer to
/// a best-effort parse, matching the pre-pump readers exactly.
#[cfg(feature = "crossterm")]
fn collect_reply(
    rx: &std::sync::mpsc::Receiver<u8>,
    deadline: Instant,
    is_complete: &mut dyn FnMut(&[u8]) -> bool,
) -> Vec<u8> {
    let mut bytes = Vec::new();
    loop {
        let now = Instant::now();
        if now >= deadline {
            break;
        }
        match rx.recv_timeout(deadline - now) {
            Ok(byte) => {
                bytes.push(byte);
                if is_complete(&bytes) || bytes.len() >= 4096 {
                    break;
                }
            }
            // Timed out, or the pump thread is gone (stdin EOF / error).
            Err(_) => break,
        }
    }
    bytes
}

/// Completion predicate for OSC / DCS / CSI-`t` style replies, which terminate
/// with BEL (`\x07`) or ST (`ESC \`).
#[cfg(feature = "crossterm")]
fn osc_reply_complete(bytes: &[u8]) -> bool {
    let len = bytes.len();
    bytes[len - 1] == b'\x07' || (len >= 2 && bytes[len - 2] == 0x1B && bytes[len - 1] == b'\\')
}

/// Completion predicate builder for Device-Attributes replies: `c` is the
/// final byte of each DA reply, and a combined `CSI c CSI > c` query yields
/// two of them, so completion fires on the second `c`.
#[cfg(feature = "crossterm")]
fn da_reply_complete() -> impl FnMut(&[u8]) -> bool {
    let mut terminators = 0usize;
    move |bytes: &[u8]| {
        if bytes[bytes.len() - 1] == b'c' {
            terminators += 1;
        }
        terminators >= 2
    }
}

/// Completion predicate for DECRPM replies (`CSI ? <mode> ; <Ps> $ y`).
#[cfg(feature = "crossterm")]
fn decrpm_reply_complete(bytes: &[u8]) -> bool {
    bytes[bytes.len() - 1] == b'y'
}

/// Read a Device-Attributes reply, which (unlike OSC) terminates with the byte
/// `c` rather than BEL / ST. Drains up to two `c`-terminated CSI replies
/// (DA1 + DA2) within the timeout so a combined `CSI c CSI > c` query yields
/// both answers in one string.
#[cfg(feature = "crossterm")]
fn read_da_response(timeout: Duration) -> Option<String> {
    read_stdin_reply(timeout, da_reply_complete())
}

/// Parse a DA1 reply (`CSI ? <attrs> c`). Attribute `4` indicates Sixel
/// support. Only the DA1 segment is consulted; a trailing DA2 segment in the
/// same string is ignored here.
#[cfg(feature = "crossterm")]
fn parse_da1(response: &str, caps: &mut Capabilities) {
    // DA1 reply: ESC [ ? <n> ; <n> ; ... c  (no `>` after `[`).
    let mut search = response;
    while let Some(pos) = search.find("\x1b[?") {
        let body = &search[pos + 3..];
        let Some(end) = body.find('c') else { break };
        let attrs = &body[..end];
        for attr in attrs.split(';') {
            if attr.trim() == "4" {
                caps.sixel = true;
            }
        }
        search = &body[end + 1..];
    }
}

/// Parsed DA2 (secondary device attributes) terminal identity:
/// `(primary_id, firmware_version)` from `CSI > <id> ; <ver> ; <sub> c`.
///
/// Returns `None` if the string contains no DA2 reply. Kept separate from the
/// `Capabilities` mutation so it is independently testable and so callers that
/// want the raw identity (e.g. future per-terminal quirks) are not forced
/// through capability inference.
#[cfg(feature = "crossterm")]
fn parse_da2(response: &str, caps: &mut Capabilities) {
    let Some((id, _ver)) = parse_da2_identity(response) else {
        return;
    };
    // DA2 primary id `41` is the documented Kitty graphics terminal id (Kitty
    // reports `\x1b[>41;<ver>;<sub>c`). This is the one unambiguous DA2 graphics
    // signal; every other host is resolved by the Kitty graphics query above or
    // the env-fallback, so we deliberately do not maintain a wider id registry.
    const KITTY_GRAPHICS_DA2_ID: u32 = 41;
    if id == KITTY_GRAPHICS_DA2_ID {
        caps.kitty_graphics = true;
    }
}

/// Extract `(primary_id, version)` from a DA2 reply, or `None` if absent.
#[cfg(feature = "crossterm")]
fn parse_da2_identity(response: &str) -> Option<(u32, u32)> {
    let pos = response.find("\x1b[>")?;
    let body = &response[pos + 3..];
    let end = body.find('c')?;
    let mut parts = body[..end].split(';');
    let id = parts.next()?.trim().parse::<u32>().ok()?;
    let ver = parts.next().and_then(|s| s.trim().parse::<u32>().ok());
    Some((id, ver.unwrap_or(0)))
}

/// Parse a Kitty graphics protocol query ack (`APC G i=31;OK ST`). A terminal
/// that supports the protocol echoes the image id with an `OK` status; anything
/// else (silence, error status) leaves the flag untouched.
#[cfg(feature = "crossterm")]
fn parse_kitty_graphics_ack(response: &str, caps: &mut Capabilities) {
    // Ack form: ESC _ G <key=val>;OK ESC \  — we sent i=31, so look for that id
    // paired with an OK status.
    if let Some(pos) = response.find("\x1b_G") {
        let body = &response[pos + 3..];
        let end = body.find("\x1b\\").unwrap_or(body.len());
        let payload = &body[..end];
        if payload.contains("i=31") && payload.contains("OK") {
            caps.kitty_graphics = true;
        }
    }
}

/// Parse an XTGETTCAP reply for the `Tc` (truecolor) capname. A valid reply is
/// `DCS 1 + r <hex(capname)>[=<hex(value)>] ST`; a leading `1` means the
/// capability is present.
#[cfg(feature = "crossterm")]
fn parse_xtgettcap_truecolor(response: &str, caps: &mut Capabilities) {
    // Valid reply prefix: ESC P 1 + r  (DCS 1 + r ...). `Tc` -> hex 5463.
    if let Some(pos) = response.find("\x1bP1+r") {
        let body = &response[pos + 5..];
        if body
            .to_ascii_lowercase()
            .split([';', '\x1b'])
            .any(|seg| seg.starts_with("5463"))
        {
            caps.truecolor = true;
        }
    }
}

/// Tri-state outcome of the DECRQM ?2026 (synchronized output) probe.
///
/// The synchronized-output BSU/ESU emission is gated on this rather than on the
/// public [`Capabilities::sync_output`] bool alone, because the public flag is
/// only ever set on *positive* support evidence. Gating emission on that flag
/// directly would flip the historic always-emit behavior to never-emit on every
/// headless / non-answering host (a regression). This tri-state lets the gate
/// suppress BSU/ESU **only** when the terminal definitively reported the mode
/// unrecognized, and keep emitting in the `Unknown` (silent / headless) case.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SyncOutputResolution {
    /// DECRQM confirmed mode ?2026 is recognized (set or reset).
    Supported,
    /// DECRQM explicitly reported mode ?2026 as not recognized (Ps = 0).
    Unsupported,
}

/// Process-global resolution of the synchronized-output probe, populated at most
/// once by [`probe_capabilities`]. Absent (`Unknown`) until the probe answers.
static SYNC_OUTPUT_RESOLUTION: std::sync::OnceLock<SyncOutputResolution> =
    std::sync::OnceLock::new();

/// Whether the flush pipeline should wrap a frame in synchronized-output
/// BSU/ESU guards.
///
/// Returns `true` (emit) unless the DECRQM ?2026 probe *definitively* reported
/// the mode as unrecognized. A silent / headless / never-run probe leaves the
/// resolution `Unknown`, in which case this keeps emitting exactly as the
/// pre-gate code always did. This is the behavior-preserving half of the
/// capability gate: positive support and the unknown default both emit; only a
/// confirmed-unsupported terminal suppresses.
fn should_emit_synchronized_update() -> bool {
    !matches!(
        SYNC_OUTPUT_RESOLUTION.get(),
        Some(SyncOutputResolution::Unsupported)
    )
}

/// Read a DECRPM reply, which terminates with the byte `y` rather than BEL / ST
/// (used for the DECRQM ?2026 synchronized-output probe). Bounded by `timeout`
/// so a terminal that ignores the query cannot stall startup.
#[cfg(feature = "crossterm")]
fn read_decrpm_response(timeout: Duration) -> Option<String> {
    read_stdin_reply(timeout, decrpm_reply_complete)
}

/// Parse a DECRPM reply for synchronized output (mode `2026`):
/// `CSI ? 2026 ; <Ps> $ y`.
///
/// Returns:
///   * `Some(true)`  — mode recognized (`Ps` ∈ {1, 2, 3, 4}: set / reset /
///     permanently-set / permanently-reset all mean *supported*),
///   * `Some(false)` — mode not recognized (`Ps` = 0),
///   * `None`        — no DECRPM reply for mode 2026 in the string.
#[cfg(feature = "crossterm")]
fn parse_decrpm_sync_output(response: &str) -> Option<bool> {
    // Reply body: ESC [ ? 2026 ; <Ps> $ y
    let pos = response.find("\x1b[?2026;")?;
    let body = &response[pos + "\x1b[?2026;".len()..];
    let end = body.find("$y")?;
    let ps = body[..end].trim().parse::<u32>().ok()?;
    // Ps = 0 → not recognized; any other reported state means the mode exists.
    Some(ps != 0)
}

fn split_base64(encoded: &str, chunk_size: usize) -> Vec<&str> {
    let mut chunks = Vec::new();
    let bytes = encoded.as_bytes();
    let mut offset = 0;
    while offset < bytes.len() {
        let end = (offset + chunk_size).min(bytes.len());
        chunks.push(&encoded[offset..end]);
        offset = end;
    }
    if chunks.is_empty() {
        chunks.push("");
    }
    chunks
}

pub(crate) struct Terminal {
    stdout: Sink,
    current: Buffer,
    previous: Buffer,
    cursor_visible: bool,
    session: TerminalSessionGuard,
    color_depth: ColorDepth,
    pub(crate) theme_bg: Option<Color>,
    kitty_mgr: KittyImageManager,
    /// Reused run-coalescing scratch for `flush_buffer_diff` (issue #269). Its
    /// capacity persists across frames so the hot flush loop never allocates a
    /// fresh `String` per call.
    run_buf: String,
}

pub(crate) struct InlineTerminal {
    stdout: Sink,
    current: Buffer,
    previous: Buffer,
    cursor_visible: bool,
    session: TerminalSessionGuard,
    height: u32,
    start_row: u16,
    reserved: bool,
    color_depth: ColorDepth,
    pub(crate) theme_bg: Option<Color>,
    kitty_mgr: KittyImageManager,
    /// Reused run-coalescing scratch for `flush_buffer_diff` (issue #269).
    run_buf: String,
}

/// Initial capacity for the reused per-frame run-coalescing buffer. Sized to
/// comfortably hold a full wide terminal row of multi-byte graphemes so the
/// allocation is paid once at construction, never per frame.
const RUN_BUF_INITIAL_CAPACITY: usize = 4096;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TerminalSessionMode {
    Fullscreen,
    Inline,
}

#[derive(Debug, Clone, Copy)]
struct TerminalSessionGuard {
    mode: TerminalSessionMode,
    mouse_enabled: bool,
    kitty_keyboard: bool,
    report_all_keys: bool,
    /// When `true`, the guard never touched real raw-mode / terminal state
    /// (PTY test harness path). `restore` then becomes a no-op so dropping a
    /// captured-sink `Terminal` does not call `disable_raw_mode` or emit
    /// teardown escapes into the byte capture. Always `false` on the
    /// production `enter` path.
    harness: bool,
}

impl TerminalSessionGuard {
    fn enter(
        mode: TerminalSessionMode,
        stdout: &mut impl Write,
        mouse_enabled: bool,
        kitty_keyboard: bool,
        report_all_keys: bool,
    ) -> io::Result<Self> {
        let guard = Self {
            mode,
            mouse_enabled,
            kitty_keyboard,
            report_all_keys,
            harness: false,
        };

        terminal::enable_raw_mode()?;
        if let Err(err) = write_session_enter(stdout, &guard) {
            guard.restore(stdout, false);
            return Err(err);
        }

        // Issue #264: run the one-shot DA1/DA2/XTGETTCAP capability probe at
        // session enter, while raw mode is active so the replies are readable.
        // `capabilities()` caches in a `OnceLock`, so the resume re-enter path
        // never re-probes. Never runs on the PTY-harness path (`harness` is
        // always `false` here, but resume/harness re-entries go through
        // `write_session_enter` directly, not `enter`).
        let _ = capabilities();

        Ok(guard)
    }

    fn restore(&self, stdout: &mut impl Write, inline_reserved: bool) {
        // PTY harness guard: nothing was ever entered, so nothing to restore.
        if self.harness {
            return;
        }
        if self.kitty_keyboard {
            use crossterm::event::PopKeyboardEnhancementFlags;
            let _ = execute!(stdout, PopKeyboardEnhancementFlags);
        }
        if self.mouse_enabled {
            let _ = execute!(stdout, DisableMouseCapture);
        }
        let _ = execute!(stdout, DisableFocusChange);
        let _ = write_session_cleanup(stdout, self.mode, inline_reserved);
        let _ = terminal::disable_raw_mode();
    }
}

impl Terminal {
    /// Construct a fullscreen terminal backend; enters raw mode and the
    /// alternate screen and optionally enables mouse capture and the
    /// kitty keyboard protocol. When `report_all_keys` is set (and
    /// `kitty_keyboard` is too), bare modifier presses are reported.
    pub(crate) fn new(
        mouse: bool,
        kitty_keyboard: bool,
        report_all_keys: bool,
        color_depth: ColorDepth,
    ) -> io::Result<Self> {
        let (cols, rows) = terminal::size()?;
        let area = Rect::new(0, 0, cols as u32, rows as u32);

        let mut raw = io::stdout();
        let session = TerminalSessionGuard::enter(
            TerminalSessionMode::Fullscreen,
            &mut raw,
            mouse,
            kitty_keyboard,
            report_all_keys,
        )?;

        Ok(Self {
            stdout: Sink::Stdout(BufWriter::with_capacity(65536, raw)),
            current: Buffer::empty(area),
            previous: Buffer::empty(area),
            cursor_visible: false,
            session,
            color_depth,
            theme_bg: None,
            kitty_mgr: KittyImageManager::new(),
            run_buf: String::with_capacity(RUN_BUF_INITIAL_CAPACITY),
        })
    }

    /// Return the fullscreen terminal's current `(cols, rows)`.
    pub(crate) fn size(&self) -> (u32, u32) {
        (self.current.area.width, self.current.area.height)
    }

    /// Mutable access to the back buffer used by the next render pass.
    pub(crate) fn buffer_mut(&mut self) -> &mut Buffer {
        &mut self.current
    }

    /// Diff the back buffer against the front buffer, write the changed
    /// cells to stdout under a synchronized-output guard, then swap
    /// front and back buffers.
    pub(crate) fn flush(&mut self) -> io::Result<()> {
        if self.current.area.width < self.previous.area.width {
            execute!(self.stdout, terminal::Clear(terminal::ClearType::All))?;
        }

        // Synchronized output (BSU/ESU) is gated on the DECRQM ?2026 probe
        // (v0.21.1): emit unless the terminal definitively reported the mode
        // unrecognized. A silent / headless probe keeps emitting as before.
        let sync_guard = should_emit_synchronized_update();
        if sync_guard {
            queue!(self.stdout, BeginSynchronizedUpdate)?;
        }
        // Issue #171: refresh both buffers' per-row digests so the per-row
        // skip inside `flush_buffer_diff` can short-circuit unchanged rows.
        // `previous` only needs a recompute when the prior frame mutated
        // it (e.g. after a swap); cheap when nothing's dirty.
        self.current.recompute_line_hashes();
        self.previous.recompute_line_hashes();
        flush_buffer_diff(
            &mut self.stdout,
            &self.current,
            &self.previous,
            self.color_depth,
            0,
            &mut self.run_buf,
        )?;

        // Kitty graphics: structured image management with IDs and compression.
        // Full-screen mode has no row offset (issue #206).
        self.kitty_mgr
            .flush(&mut self.stdout, &self.current.kitty_placements, 0)?;

        // Generic raw passthrough sequences (non-sprixel) — simple diff.
        flush_raw_sequences(&mut self.stdout, &self.current, &self.previous, 0)?;

        // Sprixels (sixel / iTerm2) — per-cell damage-tracked re-blit (#265).
        flush_sprixels(&mut self.stdout, &self.current, &self.previous, 0)?;

        if sync_guard {
            queue!(self.stdout, EndSynchronizedUpdate)?;
        }
        flush_cursor(
            &mut self.stdout,
            &mut self.cursor_visible,
            self.current.cursor_pos(),
            0,
            None,
        )?;

        self.stdout.flush()?;

        std::mem::swap(&mut self.current, &mut self.previous);
        if let Some(bg) = self.theme_bg {
            self.current.reset_with_bg(bg);
        } else {
            self.current.reset();
        }
        Ok(())
    }

    /// Re-query the terminal size and resize the front and back buffers
    /// to match. Called from the SIGWINCH handler.
    pub(crate) fn handle_resize(&mut self) -> io::Result<()> {
        let (cols, rows) = terminal::size()?;
        let area = Rect::new(0, 0, cols as u32, rows as u32);
        self.current.resize(area);
        self.previous.resize(area);
        execute!(
            self.stdout,
            terminal::Clear(terminal::ClearType::All),
            cursor::MoveTo(0, 0)
        )?;
        Ok(())
    }
}

#[cfg(any(test, feature = "pty-test"))]
impl Terminal {
    /// Construct a fullscreen [`Terminal`] whose flush pipeline targets an
    /// in-process byte capture instead of stdout.
    ///
    /// Used **only** by the PTY test harness ([`crate::PtyBackend`]): the
    /// production [`Terminal::new`] / [`crate::run`] path is unchanged and
    /// still binds `BufWriter<Stdout>`. No raw mode is entered and no session
    /// escapes are emitted, so this can run on a headless CI runner with no
    /// TTY. The emitted bytes — SGR runs, OSC 8, Sixel, Kitty graphics — flow
    /// through the exact same [`flush_buffer_diff`] / [`apply_style_delta`] /
    /// Sixel / Kitty emitters that a real terminal sees.
    ///
    /// `color_depth` selects the SGR encoding (truecolor vs 256-color etc.)
    /// exercised by the flush, mirroring [`Terminal::new`]'s argument.
    pub(crate) fn with_sink(width: u32, height: u32, color_depth: ColorDepth) -> Self {
        let area = Rect::new(0, 0, width, height);
        Self {
            stdout: Sink::Capture(Vec::new()),
            current: Buffer::empty(area),
            previous: Buffer::empty(area),
            cursor_visible: false,
            session: TerminalSessionGuard {
                mode: TerminalSessionMode::Fullscreen,
                mouse_enabled: false,
                kitty_keyboard: false,
                report_all_keys: false,
                harness: true,
            },
            color_depth,
            theme_bg: None,
            kitty_mgr: KittyImageManager::new(),
            run_buf: String::with_capacity(RUN_BUF_INITIAL_CAPACITY),
        }
    }

    /// Drain and return the bytes captured by a [`with_sink`](Terminal::with_sink)
    /// terminal since the last call, resetting the capture buffer.
    ///
    /// Panics if this terminal is not a captured-sink (harness) terminal.
    pub(crate) fn take_sink_bytes(&mut self) -> Vec<u8> {
        match &mut self.stdout {
            Sink::Capture(v) => std::mem::take(v),
            Sink::Stdout(_) => panic!("take_sink_bytes called on a non-capture Terminal"),
        }
    }
}

impl crate::Backend for Terminal {
    fn size(&self) -> (u32, u32) {
        Terminal::size(self)
    }

    fn buffer_mut(&mut self) -> &mut Buffer {
        Terminal::buffer_mut(self)
    }

    fn flush(&mut self) -> io::Result<()> {
        Terminal::flush(self)
    }
}

impl InlineTerminal {
    /// Construct an inline terminal backend that renders `height` rows
    /// below the current cursor without entering the alternate screen.
    /// Optionally enables mouse capture and the kitty keyboard protocol.
    /// When `report_all_keys` is set (and `kitty_keyboard` is too), bare
    /// modifier presses are reported.
    pub(crate) fn new(
        height: u32,
        mouse: bool,
        kitty_keyboard: bool,
        report_all_keys: bool,
        color_depth: ColorDepth,
    ) -> io::Result<Self> {
        let (cols, _) = terminal::size()?;
        let area = Rect::new(0, 0, cols as u32, height);

        let mut raw = io::stdout();
        let session = TerminalSessionGuard::enter(
            TerminalSessionMode::Inline,
            &mut raw,
            mouse,
            kitty_keyboard,
            report_all_keys,
        )?;

        let (_, cursor_row) = match cursor::position() {
            Ok(pos) => pos,
            Err(err) => {
                session.restore(&mut raw, false);
                return Err(err);
            }
        };
        Ok(Self {
            stdout: Sink::Stdout(BufWriter::with_capacity(65536, raw)),
            current: Buffer::empty(area),
            previous: Buffer::empty(area),
            cursor_visible: false,
            session,
            height,
            start_row: cursor_row,
            reserved: false,
            color_depth,
            theme_bg: None,
            kitty_mgr: KittyImageManager::new(),
            run_buf: String::with_capacity(RUN_BUF_INITIAL_CAPACITY),
        })
    }

    /// Return the inline terminal's current `(cols, rows)`.
    pub(crate) fn size(&self) -> (u32, u32) {
        (self.current.area.width, self.current.area.height)
    }

    /// Mutable access to the back buffer used by the next render pass.
    pub(crate) fn buffer_mut(&mut self) -> &mut Buffer {
        &mut self.current
    }

    /// Diff the back buffer against the front buffer, write changed
    /// cells to stdout under a synchronized-output guard at the
    /// inline rows reserved below the cursor, then swap buffers.
    pub(crate) fn flush(&mut self) -> io::Result<()> {
        if self.current.area.width < self.previous.area.width {
            execute!(self.stdout, terminal::Clear(terminal::ClearType::All))?;
        }

        // Synchronized output (BSU/ESU) is gated on the DECRQM ?2026 probe
        // (v0.21.1); see `Terminal::flush`. Silent / headless keeps emitting.
        let sync_guard = should_emit_synchronized_update();
        if sync_guard {
            queue!(self.stdout, BeginSynchronizedUpdate)?;
        }

        if !self.reserved {
            queue!(self.stdout, cursor::MoveToColumn(0))?;
            for _ in 0..self.height {
                queue!(self.stdout, Print("\n"))?;
            }
            self.reserved = true;

            let (_, rows) = terminal::size()?;
            let bottom = self.start_row.saturating_add(sat_u16(self.height));
            if bottom > rows {
                self.start_row = rows.saturating_sub(sat_u16(self.height));
            }
        }
        let row_offset = self.start_row as u32;
        // Issue #171: refresh per-row digests before the diff so the
        // unchanged-row skip can fire (same call shape as `Terminal::flush`).
        self.current.recompute_line_hashes();
        self.previous.recompute_line_hashes();
        flush_buffer_diff(
            &mut self.stdout,
            &self.current,
            &self.previous,
            self.color_depth,
            row_offset,
            &mut self.run_buf,
        )?;

        // Kitty graphics: structured image management with IDs and compression.
        // Issue #206: pass `row_offset` instead of materializing a translated
        // `Vec<KittyPlacement>` copy — `KittyImageManager::flush` applies the
        // offset arithmetically at point of use and stores post-offset y in
        // `prev_placements` for the next frame's diff.
        self.kitty_mgr
            .flush(&mut self.stdout, &self.current.kitty_placements, row_offset)?;

        // Generic raw passthrough sequences (non-sprixel) — simple diff.
        flush_raw_sequences(&mut self.stdout, &self.current, &self.previous, row_offset)?;

        // Sprixels (sixel / iTerm2) — per-cell damage-tracked re-blit (#265).
        flush_sprixels(&mut self.stdout, &self.current, &self.previous, row_offset)?;

        if sync_guard {
            queue!(self.stdout, EndSynchronizedUpdate)?;
        }
        let fallback_row = row_offset + self.height.saturating_sub(1);
        flush_cursor(
            &mut self.stdout,
            &mut self.cursor_visible,
            self.current.cursor_pos(),
            row_offset,
            Some(fallback_row),
        )?;

        self.stdout.flush()?;

        std::mem::swap(&mut self.current, &mut self.previous);
        reset_current_buffer(&mut self.current, self.theme_bg);
        Ok(())
    }

    /// Re-query the terminal size and resize the inline buffers to match
    /// the new column count, preserving the inline row height.
    pub(crate) fn handle_resize(&mut self) -> io::Result<()> {
        let (cols, _) = terminal::size()?;
        let area = Rect::new(0, 0, cols as u32, self.height);
        self.current.resize(area);
        self.previous.resize(area);
        execute!(
            self.stdout,
            terminal::Clear(terminal::ClearType::All),
            cursor::MoveTo(0, 0)
        )?;
        Ok(())
    }
}

impl crate::Backend for InlineTerminal {
    fn size(&self) -> (u32, u32) {
        InlineTerminal::size(self)
    }

    fn buffer_mut(&mut self) -> &mut Buffer {
        InlineTerminal::buffer_mut(self)
    }

    fn flush(&mut self) -> io::Result<()> {
        InlineTerminal::flush(self)
    }
}

impl Drop for Terminal {
    fn drop(&mut self) {
        // Clean up Kitty images before leaving alternate screen
        let _ = self.kitty_mgr.delete_all(&mut self.stdout);
        let _ = self.stdout.flush();
        self.session.restore(&mut self.stdout, false);
    }
}

impl Drop for InlineTerminal {
    fn drop(&mut self) {
        let _ = self.kitty_mgr.delete_all(&mut self.stdout);
        let _ = self.stdout.flush();
        self.session.restore(&mut self.stdout, self.reserved);
    }
}

mod selection;
pub(crate) use selection::{SelectionState, apply_selection_overlay, extract_selection_text};
#[cfg(test)]
pub(crate) use selection::{find_innermost_rect, normalize_selection};

/// Detected terminal color scheme from OSC 11.
#[non_exhaustive]
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorScheme {
    /// Dark background detected.
    Dark,
    /// Light background detected.
    Light,
    /// Could not determine the scheme.
    Unknown,
}

/// Read an OSC-style reply (BEL- or ST-terminated), hard-bounded by `timeout`.
#[cfg(feature = "crossterm")]
fn read_osc_response(timeout: Duration) -> Option<String> {
    read_stdin_reply(timeout, osc_reply_complete)
}

/// Query the terminal's background color via OSC 11 and return the detected scheme.
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn detect_color_scheme() -> ColorScheme {
    let mut stdout = io::stdout();
    if write!(stdout, "\x1b]11;?\x07").is_err() {
        return ColorScheme::Unknown;
    }
    if stdout.flush().is_err() {
        return ColorScheme::Unknown;
    }

    let Some(response) = read_osc_response(Duration::from_millis(100)) else {
        return ColorScheme::Unknown;
    };

    parse_osc11_response(&response)
}

#[cfg(feature = "crossterm")]
pub(crate) fn parse_osc11_response(response: &str) -> ColorScheme {
    let Some(rgb_pos) = response.find("rgb:") else {
        return ColorScheme::Unknown;
    };

    let payload = &response[rgb_pos + 4..];
    let end = payload
        .find(['\x07', '\x1b', '\r', '\n', ' ', '\t'])
        .unwrap_or(payload.len());
    let rgb = &payload[..end];

    let mut channels = rgb.split('/');
    let (Some(r), Some(g), Some(b), None) = (
        channels.next(),
        channels.next(),
        channels.next(),
        channels.next(),
    ) else {
        return ColorScheme::Unknown;
    };

    fn parse_channel(channel: &str) -> Option<f64> {
        if channel.is_empty() || channel.len() > 4 {
            return None;
        }
        let value = u16::from_str_radix(channel, 16).ok()? as f64;
        let max = ((1u32 << (channel.len() * 4)) - 1) as f64;
        if max <= 0.0 {
            return None;
        }
        Some((value / max).clamp(0.0, 1.0))
    }

    let (Some(r), Some(g), Some(b)) = (parse_channel(r), parse_channel(g), parse_channel(b)) else {
        return ColorScheme::Unknown;
    };

    let luminance = 0.299 * r + 0.587 * g + 0.114 * b;
    if luminance < 0.5 {
        ColorScheme::Dark
    } else {
        ColorScheme::Light
    }
}

pub(crate) fn base64_encode(input: &[u8]) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
        let triple = (b0 << 16) | (b1 << 8) | b2;
        out.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
        out.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
        out.push(if chunk.len() > 1 {
            CHARS[((triple >> 6) & 0x3F) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            CHARS[(triple & 0x3F) as usize] as char
        } else {
            '='
        });
    }
    out
}

pub(crate) fn copy_to_clipboard(w: &mut impl Write, text: &str) -> io::Result<()> {
    let encoded = base64_encode(text.as_bytes());
    write!(w, "\x1b]52;c;{encoded}\x1b\\")?;
    w.flush()
}

#[cfg(feature = "crossterm")]
fn parse_osc52_response(response: &str) -> Option<String> {
    let osc_pos = response.find("]52;")?;
    let body = &response[osc_pos + 4..];
    let semicolon = body.find(';')?;
    let payload = &body[semicolon + 1..];

    let end = payload
        .find("\x1b\\")
        .or_else(|| payload.find('\x07'))
        .unwrap_or(payload.len());
    let encoded = payload[..end].trim();
    if encoded.is_empty() || encoded == "?" {
        return None;
    }

    base64_decode(encoded)
}

/// Read clipboard contents via an OSC 52 terminal query.
///
/// Writes the OSC 52 read request (`ESC ] 52 ; c ; ? BEL`) to stdout, then
/// blocks reading the terminal's reply from stdin for up to ~200 ms. Returns
/// the decoded clipboard text, or `None` if the terminal does not answer, the
/// reply is empty, or it cannot be decoded. Many terminals disable OSC 52 reads
/// by default for security, in which case this always returns `None`.
///
/// # Note
///
/// This call reads the **same stdin** the [`run`](crate::run) event loop polls,
/// **synchronously and outside** the loop's own event dispatch. That creates a
/// typeahead-swallow hazard: during the blocking read window, any bytes the user
/// types — and any other terminal report in flight (mouse, focus, paste, a
/// different OSC reply) — land in this function's byte reader instead of the
/// event queue. Keystrokes consumed here are silently lost, and a foreign report
/// interleaved with the OSC 52 reply can corrupt parsing so the read returns
/// `None`. There is no locking between this reader and the run loop's poll, so
/// calling it concurrently from another thread while the loop is running races
/// on stdin.
///
/// Recommended usage:
///   * Call it from the main thread, **not** from a spawned thread, and never
///     concurrently with a running [`run`](crate::run) loop on another thread.
///   * Trigger it only in direct response to an explicit user action (e.g. a
///     paste keybinding) and keep the window brief, so the typeahead lost to the
///     blocking read is bounded to that moment.
///   * Prefer the OS clipboard via a dedicated crate when reliable, race-free
///     clipboard reads are required; reserve this for the no-dependency,
///     terminal-only fallback.
///   * For *writing* the clipboard there is no such hazard — that path only
///     emits bytes and never reads stdin.
#[cfg(feature = "crossterm")]
#[cfg_attr(docsrs, doc(cfg(feature = "crossterm")))]
pub fn read_clipboard() -> Option<String> {
    let mut stdout = io::stdout();
    write!(stdout, "\x1b]52;c;?\x07").ok()?;
    stdout.flush().ok()?;

    let response = read_osc_response(Duration::from_millis(200))?;
    parse_osc52_response(&response)
}

#[cfg(feature = "crossterm")]
fn base64_decode(input: &str) -> Option<String> {
    let mut filtered: Vec<u8> = input
        .bytes()
        .filter(|b| !matches!(b, b' ' | b'\n' | b'\r' | b'\t'))
        .collect();

    match filtered.len() % 4 {
        0 => {}
        2 => filtered.extend_from_slice(b"=="),
        3 => filtered.push(b'='),
        _ => return None,
    }

    fn decode_val(b: u8) -> Option<u8> {
        match b {
            b'A'..=b'Z' => Some(b - b'A'),
            b'a'..=b'z' => Some(b - b'a' + 26),
            b'0'..=b'9' => Some(b - b'0' + 52),
            b'+' => Some(62),
            b'/' => Some(63),
            _ => None,
        }
    }

    let mut out = Vec::with_capacity((filtered.len() / 4) * 3);
    for chunk in filtered.chunks_exact(4) {
        let p2 = chunk[2] == b'=';
        let p3 = chunk[3] == b'=';
        if p2 && !p3 {
            return None;
        }

        let v0 = decode_val(chunk[0])? as u32;
        let v1 = decode_val(chunk[1])? as u32;
        let v2 = if p2 { 0 } else { decode_val(chunk[2])? as u32 };
        let v3 = if p3 { 0 } else { decode_val(chunk[3])? as u32 };

        let triple = (v0 << 18) | (v1 << 12) | (v2 << 6) | v3;
        out.push(((triple >> 16) & 0xFF) as u8);
        if !p2 {
            out.push(((triple >> 8) & 0xFF) as u8);
        }
        if !p3 {
            out.push((triple & 0xFF) as u8);
        }
    }

    String::from_utf8(out).ok()
}

#[allow(clippy::too_many_arguments)]
#[allow(unused_assignments)]
fn flush_buffer_diff(
    stdout: &mut impl Write,
    current: &Buffer,
    previous: &Buffer,
    color_depth: ColorDepth,
    row_offset: u32,
    run_buf: &mut String,
) -> io::Result<()> {
    // Run-coalescing: consecutive changed cells in the same row that share
    // `Style` + `hyperlink` + contiguous x-coordinates are emitted as a single
    // `Print(run)` after one cursor move and one style delta. This cuts the
    // number of `queue!` calls on a full redraw from O(cells) to
    // O(style-change boundaries), which is the dominant stdout write cost.
    //
    // A run is broken whenever:
    //   * style, hyperlink, or row changes,
    //   * the next cell is not at the expected next column (gap from skipped
    //     cells — unchanged, empty wide-char trailer, or end of row),
    //   * end-of-row (always flushed before descending to the next row).
    let mut last_style = Style::new();
    let mut first_style = true;
    let mut active_link: Option<&str> = None;
    let mut has_updates = false;
    // Where we believe the cursor currently sits — lets us skip a redundant
    // `MoveTo` when a new run starts exactly where the previous one ended
    // (e.g. split only by a style change on otherwise contiguous columns).
    let mut last_cursor: Option<(u32, u32)> = None;

    // Active run state. `run_next_col` is the column the next cell must
    // occupy to extend the run; `run_open` guards the rest of the fields.
    // `run_buf` is hoisted to a caller-owned, reused buffer (issue #269): its
    // backing allocation persists across frames so the hot flush loop performs
    // no per-frame `String` allocation. Start clean but keep capacity.
    run_buf.clear();
    let mut run_abs_y: u32 = 0;
    let mut run_style: Style = Style::new();
    let mut run_link: Option<&str> = None;
    let mut run_next_col: u32 = 0;
    let mut run_open = false;

    // Helper: flush the currently open run, if any. Emits a single `Print`
    // for the entire accumulated buffer; positioning, style, and OSC 8 were
    // already written when the run opened. Updates `last_cursor` to reflect
    // where the cursor ends up after the Print.
    macro_rules! flush_run {
        ($stdout:expr) => {
            if run_open {
                queue!($stdout, Print(&run_buf))?;
                last_cursor = Some((run_next_col, run_abs_y));
                run_buf.clear();
                run_open = false;
            }
        };
    }

    for y in current.area.y..current.area.bottom() {
        // Issue #171: skip the per-cell scan for rows that were not touched
        // since the last hash refresh AND match the previous frame's
        // digest. Both conditions must hold:
        //   * `row_clean` rules out rows that received writes this frame
        //     even if those writes happened to land on identical cells.
        //   * The hash equality is the actual unchanged-row signal.
        // Falling through to the per-cell loop on either failure preserves
        // legacy behavior; the skip is a pure short-circuit.
        if current.row_clean(y)
            && current.row_hash(y).is_some()
            && current.row_hash(y) == previous.row_hash(y)
        {
            continue;
        }
        for x in current.area.x..current.area.right() {
            let cell = current.get(x, y);
            let prev = previous.get(x, y);
            if cell == prev || cell.symbol.is_empty() {
                // Gap — any open run on this row must be flushed.
                flush_run!(stdout);
                continue;
            }

            let abs_y = row_offset + y;
            // Defense-in-depth: `Cell::hyperlink` is a public field that can
            // be written directly. `set_string_linked` pre-sanitizes, but a
            // direct write could still smuggle control bytes into the OSC 8
            // payload. Validate here before flushing to stdout.
            let cell_link = cell
                .hyperlink
                .as_deref()
                .filter(|u| crate::buffer::is_valid_osc8_url(u));

            // Decide whether this cell extends the open run or starts a new one.
            let extends = run_open
                && run_abs_y == abs_y
                && run_next_col == x
                && run_style == cell.style
                && run_link == cell_link;

            if !extends {
                flush_run!(stdout);

                // Begin a new run. Emit positioning + style + OSC 8 header now
                // (before the Print bytes) so the resulting stream is a valid
                // SGR sequence exactly matching the per-cell flush.
                has_updates = true;

                let need_move = last_cursor.is_none_or(|(lx, ly)| lx != x || ly != abs_y);
                if need_move {
                    queue!(stdout, cursor::MoveTo(sat_u16(x), sat_u16(abs_y)))?;
                }

                if cell.style != last_style {
                    if first_style {
                        queue!(stdout, ResetColor, SetAttribute(Attribute::Reset))?;
                        apply_style(stdout, &cell.style, color_depth)?;
                        first_style = false;
                    } else {
                        apply_style_delta(stdout, &last_style, &cell.style, color_depth)?;
                    }
                    last_style = cell.style;
                }

                if cell_link != active_link {
                    if let Some(url) = cell_link {
                        // Emit the OSC 8 open in three borrowed `Print`s instead
                        // of `format!`ing a throwaway `String` per link-state
                        // change (issue #269). The byte stream is identical to
                        // `"\x1b]8;;{url}\x07"`.
                        queue!(stdout, Print("\x1b]8;;"))?;
                        queue!(stdout, Print(url))?;
                        queue!(stdout, Print("\x07"))?;
                    } else {
                        queue!(stdout, Print("\x1b]8;;\x07"))?;
                    }
                    active_link = cell_link;
                }

                run_open = true;
                run_abs_y = abs_y;
                run_style = cell.style;
                run_link = cell_link;
            }

            // Append the cell's grapheme cluster (possibly multi-char when it
            // carries combining marks). Wide chars advance by their column
            // width so subsequent cells line up.
            run_buf.push_str(&cell.symbol);
            let char_width = UnicodeWidthStr::width(cell.symbol.as_str()).max(1) as u32;
            if char_width > 1 && cell.symbol.chars().any(|c| c == '\u{FE0F}') {
                // Emoji variation selector — terminal renders 2 cols but the
                // glyph often measures as 1; pad so the cursor ends up where
                // the next cell is drawn.
                run_buf.push(' ');
            }
            run_next_col = x + char_width;
        }

        // End of row: flush whatever is buffered before moving to the next row.
        flush_run!(stdout);
    }

    if has_updates {
        if active_link.is_some() {
            queue!(stdout, Print("\x1b]8;;\x07"))?;
        }
        queue!(stdout, ResetColor, SetAttribute(Attribute::Reset))?;
    }

    Ok(())
}

/// Benchmark-only entry point for the per-frame buffer flush.
///
/// Exposed so criterion benches under `benches/` (an external crate) can
/// measure the stdout-emit cost of the per-frame flush against a hermetic
/// `Vec<u8>` (or any `Write`) sink, without constructing a real terminal.
///
/// Not part of the stable API. Do not depend on this in application code —
/// prefer the real terminal backend ([`crate::run`]) or
/// [`TestBackend`](crate::TestBackend).
#[doc(hidden)]
pub fn __bench_flush_buffer_diff<W: Write>(
    w: &mut W,
    current: &Buffer,
    previous: &Buffer,
    color_depth: ColorDepth,
) -> io::Result<()> {
    // Own a local run buffer to keep the public bench signature stable
    // (issue #269); the real backends pass a reused field instead.
    let mut run_buf = String::with_capacity(RUN_BUF_INITIAL_CAPACITY);
    flush_buffer_diff(w, current, previous, color_depth, 0, &mut run_buf)
}

/// Mutable-buffer variant of [`__bench_flush_buffer_diff`] (issue #171).
///
/// Refreshes per-row digests on both buffers before invoking
/// `flush_buffer_diff`, matching what the real `Terminal::flush` and
/// `InlineTerminal::flush` paths do. Benches that want to measure the
/// flush including the hash-refresh cost should use this entry point;
/// the immutable variant is preserved for backwards compatibility with
/// existing benches that own only `&Buffer`.
#[doc(hidden)]
pub fn __bench_flush_buffer_diff_mut<W: Write>(
    w: &mut W,
    current: &mut Buffer,
    previous: &mut Buffer,
    color_depth: ColorDepth,
) -> io::Result<()> {
    // Own a local run buffer to keep the public bench signature stable
    // (issue #269). Use `__bench_flush_buffer_diff_mut_with_buf` to exercise
    // cross-frame buffer reuse explicitly.
    let mut run_buf = String::with_capacity(RUN_BUF_INITIAL_CAPACITY);
    __bench_flush_buffer_diff_mut_with_buf(w, current, previous, color_depth, &mut run_buf)
}

/// Reuse-aware variant of [`__bench_flush_buffer_diff_mut`] that threads a
/// caller-owned `run_buf` (issue #269), mirroring how the real backends carry
/// the buffer across frames. Refreshes per-row digests before the diff.
///
/// Not part of the stable API.
///
/// ```no_run
/// # use slt::{Buffer, Rect, ColorDepth, Style};
/// let area = Rect::new(0, 0, 8, 2);
/// let mut current = Buffer::empty(area);
/// let mut previous = Buffer::empty(area);
/// current.set_string(0, 0, "hi", Style::new());
/// let mut sink: Vec<u8> = Vec::new();
/// // The same `run_buf` can be passed across frames — its capacity persists.
/// let mut run_buf = String::with_capacity(4096);
/// slt::__bench_flush_buffer_diff_mut_with_buf(
///     &mut sink,
///     &mut current,
///     &mut previous,
///     ColorDepth::TrueColor,
///     &mut run_buf,
/// )
/// .unwrap();
/// ```
#[doc(hidden)]
pub fn __bench_flush_buffer_diff_mut_with_buf<W: Write>(
    w: &mut W,
    current: &mut Buffer,
    previous: &mut Buffer,
    color_depth: ColorDepth,
    run_buf: &mut String,
) -> io::Result<()> {
    current.recompute_line_hashes();
    previous.recompute_line_hashes();
    flush_buffer_diff(w, current, previous, color_depth, 0, run_buf)
}

/// Opaque test fixture wrapping `KittyImageManager` + a placements list.
///
/// Returned by [`__bench_new_kitty_fixture`]. Internal types stay
/// `pub(crate)` — only the opaque struct crosses the crate boundary.
#[doc(hidden)]
pub struct __BenchKittyFixture {
    mgr: KittyImageManager,
    placements: Vec<KittyPlacement>,
}

/// Build a self-contained kitty-flush fixture for the perf alloc suite
/// (issue #206). `n` is the number of distinct images.
#[doc(hidden)]
pub fn __bench_new_kitty_fixture(n: usize) -> __BenchKittyFixture {
    let mut placements = Vec::with_capacity(n);
    for i in 0..n {
        // 8x8 RGBA: 64 px * 4 bytes = 256 bytes.
        let mut rgba = vec![0u8; 256];
        // Vary contents per placement to give each a unique content_hash.
        rgba[0] = i as u8;
        let content_hash = crate::buffer::hash_rgba(&rgba);
        placements.push(KittyPlacement {
            content_hash,
            rgba: std::sync::Arc::new(rgba),
            src_width: 8,
            src_height: 8,
            x: (i as u32) * 4,
            y: (i as u32) * 2,
            cols: 4,
            rows: 2,
            crop_y: 0,
            crop_h: 0,
        });
    }
    __BenchKittyFixture {
        mgr: KittyImageManager::new(),
        placements,
    }
}

impl __BenchKittyFixture {
    /// Strong-count snapshot of the inner `Arc<Vec<u8>>` for each placement.
    /// Used by the alloc-budget tests to confirm no extra Arc clones leak
    /// past the manager's stored `prev_placements`.
    #[doc(hidden)]
    pub fn rgba_strong_counts(&self) -> Vec<usize> {
        self.placements
            .iter()
            .map(|p| std::sync::Arc::strong_count(&p.rgba))
            .collect()
    }

    /// Run the inline-mode flush path with the given row offset. Writes
    /// terminal escapes into `sink` and updates the internal manager state.
    #[doc(hidden)]
    pub fn flush_inline<W: Write>(&mut self, sink: &mut W, row_offset: u32) -> io::Result<()> {
        self.mgr.flush(sink, &self.placements, row_offset)
    }

    /// Number of placements in this fixture.
    #[doc(hidden)]
    pub fn len(&self) -> usize {
        self.placements.len()
    }

    /// Whether this fixture has zero placements.
    #[doc(hidden)]
    pub fn is_empty(&self) -> bool {
        self.placements.is_empty()
    }
}

/// Benchmark-only entry point for the Kitty image flush path.
///
/// Builds an `n`-image fixture and runs [`KittyImageManager::flush`] once into
/// the supplied sink at `row_offset`, mirroring the [`__bench_flush_buffer_diff`]
/// free-function style. `KittyPlacement` / `KittyImageManager` are `pub(crate)`,
/// so an external bench crate cannot construct them directly — this wrapper owns
/// the construction and only the `Write` sink crosses the crate boundary.
///
/// Not part of the stable API.
#[doc(hidden)]
pub fn __bench_flush_kitty<W: Write>(sink: &mut W, n: usize, row_offset: u32) -> io::Result<()> {
    let mut fixture = __bench_new_kitty_fixture(n);
    fixture.flush_inline(sink, row_offset)
}

/// Opaque test/bench fixture wrapping two `Buffer`s populated with structurally
/// identical sprixel placements, used to drive the [`flush_sprixels`] re-blit
/// path. `SprixelPlacement` is `pub(crate)`, so this fixture owns construction
/// and exposes only `Write`-based flush entry points across the crate boundary.
///
/// Returned by [`__bench_new_sprixel_fixture`].
#[doc(hidden)]
pub struct __BenchSprixelFixture {
    current: Buffer,
    previous: Buffer,
}

/// Build a self-contained sprixel-reblit fixture for the perf suite (v0.21.1).
///
/// Creates `n` opaque sprixel placements laid out down the buffer and mirrors
/// them into both the current and previous frame so the steady-state flush
/// re-blits nothing. Per-row digests are refreshed (as the real `flush` does)
/// so the per-row clean+hash shortcut in [`sprixel_needs_reblit`] is exercised.
///
/// Not part of the stable API.
#[doc(hidden)]
pub fn __bench_new_sprixel_fixture(n: usize) -> __BenchSprixelFixture {
    use crate::buffer::{SprixelCell, SprixelPlacement};

    // A buffer tall enough to stack `n` 2-row sprixels with a 1-row gap.
    let height = (n as u32 * 3).max(1);
    let area = Rect::new(0, 0, 8, height);
    let mut current = Buffer::empty(area);
    let mut previous = Buffer::empty(area);

    for i in 0..n {
        let placement = SprixelPlacement {
            content_hash: 0x5000 + i as u64,
            seq: "<SIXEL>".to_string(),
            x: 0,
            y: i as u32 * 3,
            cols: 4,
            rows: 2,
            cells: vec![SprixelCell::Opaque; 8],
        };
        current.sprixels.push(placement.clone());
        previous.sprixels.push(placement);
    }

    // Refresh digests so the per-row shortcut can fire, matching the real
    // `Terminal::flush` ordering (recompute happens before `flush_sprixels`).
    current.recompute_line_hashes();
    previous.recompute_line_hashes();

    __BenchSprixelFixture { current, previous }
}

// The bench fixture's inherent methods are reachable only once the crate root
// re-exports `__BenchSprixelFixture` (an integrator step listed in the release
// notes); until then the lib-target dead-code lint flags them, exactly as it
// would the already-shipped `__BenchKittyFixture` methods without their
// `lib.rs` re-export. They are also exercised by the in-crate tests below.
// Suppress the lint on the impl rather than gating the items behind `cfg(test)`,
// which would make them invisible to the external `benches/` crate they exist
// to serve.
#[allow(dead_code)]
impl __BenchSprixelFixture {
    /// Run [`flush_sprixels`] once, writing any re-blitted graphics into `sink`.
    /// A steady-state fixture emits nothing; this measures the no-damage scan
    /// cost (hash-set build + per-row shortcut) on the hot path.
    #[doc(hidden)]
    pub fn flush<W: Write>(&self, sink: &mut W, row_offset: u32) -> io::Result<()> {
        flush_sprixels(sink, &self.current, &self.previous, row_offset)
    }

    /// Number of sprixel placements in this fixture.
    #[doc(hidden)]
    pub fn len(&self) -> usize {
        self.current.sprixels.len()
    }

    /// Whether this fixture has zero placements.
    #[doc(hidden)]
    pub fn is_empty(&self) -> bool {
        self.current.sprixels.is_empty()
    }
}

/// Benchmark-only entry point for the optimized sprixel re-blit scan (v0.21.1).
///
/// Builds an `n`-placement steady-state fixture and runs [`flush_sprixels`] once
/// into `sink` at `row_offset`, mirroring the [`__bench_flush_buffer_diff`]
/// free-function style. A steady frame re-blits nothing, so this measures the
/// no-damage scan cost (hashed-key build + per-row clean/hash shortcut). When
/// the fixture is empty the early-out fires and no work is done.
///
/// Not part of the stable API.
#[doc(hidden)]
pub fn __bench_flush_sprixels<W: Write>(sink: &mut W, n: usize, row_offset: u32) -> io::Result<()> {
    let fixture = __bench_new_sprixel_fixture(n);
    if fixture.is_empty() {
        return Ok(());
    }
    debug_assert_eq!(fixture.len(), n);
    fixture.flush(sink, row_offset)
}

fn flush_raw_sequences(
    stdout: &mut impl Write,
    current: &Buffer,
    previous: &Buffer,
    row_offset: u32,
) -> io::Result<()> {
    if current.raw_sequences == previous.raw_sequences {
        return Ok(());
    }

    for (x, y, seq) in &current.raw_sequences {
        queue!(
            stdout,
            cursor::MoveTo(sat_u16(*x), sat_u16(row_offset + *y)),
            Print(seq)
        )?;
    }

    Ok(())
}

/// Structural identity key for a [`crate::buffer::SprixelPlacement`], matching
/// its [`PartialEq`] contract (`content_hash`/`x`/`y`/`cols`/`rows`, damage
/// matrix excluded). Hashing this lets [`flush_sprixels`] answer "did an equal
/// placement exist last frame?" in O(1) instead of an O(n·m) linear scan.
type SprixelKey = (u64, u32, u32, u32, u32);

/// Build the structural identity key for a placement.
#[inline]
fn sprixel_key(p: &crate::buffer::SprixelPlacement) -> SprixelKey {
    (p.content_hash, p.x, p.y, p.cols, p.rows)
}

/// Decide whether a sprixel placement must be re-blitted this frame, applying
/// the per-cell damage matrix (issue #265).
///
/// Returns `true` when:
///   * the placement is new or its `(x, y, content_hash, cols, rows)` changed
///     (its key is absent from `prev_keys`, the precomputed set of last frame's
///     placement keys), OR
///   * a text cell inside the footprint was overwritten this frame *and* the
///     footprint marks that cell as covering graphic ink
///     ([`SprixelCell::Opaque`] / [`SprixelCell::Mixed`]) — i.e. the cell is
///     [`SprixelCell::Annihilated`].
///
/// A pure text edit landing on a [`SprixelCell::Transparent`] cell never marks
/// damage, so the graphic is not re-emitted.
///
/// The footprint scan short-circuits an entire footprint row when that row was
/// untouched this frame *and* hashes identically to the previous frame
/// (`current.row_clean(y) && current.row_hash(y) == previous.row_hash(y)`):
/// no cell in such a row can have changed, so no ink can have been annihilated.
/// On the headless / direct-call path (where `recompute_line_hashes` was not
/// run) every row reports dirty, so the shortcut never fires and the per-cell
/// scan runs exactly as before — preserving correctness.
fn sprixel_needs_reblit(
    placement: &crate::buffer::SprixelPlacement,
    current: &Buffer,
    previous: &Buffer,
    prev_keys: &std::collections::HashSet<SprixelKey>,
) -> bool {
    use crate::buffer::SprixelCell;

    // Position / content change: re-blit if no equal placement existed last
    // frame. The key mirrors `SprixelPlacement: PartialEq` (content_hash/x/y/
    // cols/rows; damage matrix excluded), so a moved or recolored image
    // re-blits. O(1) lookup vs the former O(n·m) `iter().any(..)` scan.
    if !prev_keys.contains(&sprixel_key(placement)) {
        return true;
    }

    // Annihilation scan: a covered text cell that changed since last frame and
    // now shows ink forces a re-blit. `Transparent` cells are skipped so free
    // text edits in graphic gaps emit zero sprixel bytes.
    for row in 0..placement.rows {
        let y = placement.y + row;
        // Per-row shortcut: a row that was not touched this frame and whose
        // cached digest matches the previous frame's cannot contain a changed
        // cell, so the whole footprint row is skipped without per-cell work.
        if current.row_clean(y) && current.row_hash(y) == previous.row_hash(y) {
            continue;
        }
        for col in 0..placement.cols {
            let idx = (row * placement.cols + col) as usize;
            match placement.cells.get(idx) {
                Some(SprixelCell::Opaque) | Some(SprixelCell::Mixed) => {}
                // Transparent / Annihilated / out-of-range: not ink-covering,
                // so a text write here does not damage the graphic.
                _ => continue,
            }
            let x = placement.x + col;
            // A footprint can extend past the buffer edge (a clipped placement,
            // or `iterm_image_fit` reserving rows beyond the viewport). Use
            // `try_get` so an out-of-bounds footprint cell is simply skipped
            // rather than panicking — there is no text there to annihilate it.
            let (Some(cell), Some(prev)) = (current.try_get(x, y), previous.try_get(x, y)) else {
                continue;
            };
            // Mirror `flush_buffer_diff`'s write predicate exactly: a cell is
            // emitted (and thus overwrites graphic ink) iff it changed since
            // last frame and carries a non-empty symbol. Matching the predicate
            // keeps the damage matrix in lockstep with what the cell diff
            // actually paints over the graphic.
            if cell != prev && !cell.symbol.is_empty() {
                return true;
            }
        }
    }

    false
}

/// Flush the sprixel (Sixel / iTerm2) layer with per-cell damage tracking.
///
/// Unlike [`flush_raw_sequences`]' all-or-nothing guard, this re-emits each
/// pixel graphic **only** when [`sprixel_needs_reblit`] reports damage, so a
/// text edit in a transparent region of a Sixel emits zero passthrough bytes
/// (issue #265).
///
/// The previous frame's placement keys are hashed once up front so the
/// position/content change check is O(1) per placement (vs the former O(n·m)
/// linear scan), and the per-row clean+hash shortcut inside
/// [`sprixel_needs_reblit`] skips untouched footprint rows entirely.
fn flush_sprixels(
    stdout: &mut impl Write,
    current: &Buffer,
    previous: &Buffer,
    row_offset: u32,
) -> io::Result<()> {
    // Early out: no graphics to emit. Avoids building the key set on the
    // common text-only frame.
    if current.sprixels.is_empty() {
        return Ok(());
    }

    let prev_keys: std::collections::HashSet<SprixelKey> =
        previous.sprixels.iter().map(sprixel_key).collect();

    for placement in &current.sprixels {
        if sprixel_needs_reblit(placement, current, previous, &prev_keys) {
            queue!(
                stdout,
                cursor::MoveTo(sat_u16(placement.x), sat_u16(row_offset + placement.y)),
                Print(&placement.seq)
            )?;
        }
    }
    Ok(())
}

fn flush_cursor(
    stdout: &mut impl Write,
    cursor_visible: &mut bool,
    cursor_pos: Option<(u32, u32)>,
    row_offset: u32,
    fallback_row: Option<u32>,
) -> io::Result<()> {
    match cursor_pos {
        Some((cx, cy)) => {
            if !*cursor_visible {
                queue!(stdout, cursor::Show)?;
                *cursor_visible = true;
            }
            queue!(
                stdout,
                cursor::MoveTo(sat_u16(cx), sat_u16(row_offset + cy))
            )?;
        }
        None => {
            if *cursor_visible {
                queue!(stdout, cursor::Hide)?;
                *cursor_visible = false;
            }
            if let Some(row) = fallback_row {
                queue!(stdout, cursor::MoveTo(0, sat_u16(row)))?;
            }
        }
    }

    Ok(())
}

fn apply_style_delta(
    w: &mut impl Write,
    old: &Style,
    new: &Style,
    depth: ColorDepth,
) -> io::Result<()> {
    if old.fg != new.fg {
        match new.fg {
            Some(fg) => queue!(w, SetForegroundColor(to_crossterm_color(fg, depth)))?,
            None => queue!(w, SetForegroundColor(CtColor::Reset))?,
        }
    }
    if old.bg != new.bg {
        match new.bg {
            Some(bg) => queue!(w, SetBackgroundColor(to_crossterm_color(bg, depth)))?,
            None => queue!(w, SetBackgroundColor(CtColor::Reset))?,
        }
    }
    let removed = Modifiers(old.modifiers.0 & !new.modifiers.0);
    let added = Modifiers(new.modifiers.0 & !old.modifiers.0);
    if removed.contains(Modifiers::BOLD) || removed.contains(Modifiers::DIM) {
        queue!(w, SetAttribute(Attribute::NormalIntensity))?;
        if new.modifiers.contains(Modifiers::BOLD) {
            queue!(w, SetAttribute(Attribute::Bold))?;
        }
        if new.modifiers.contains(Modifiers::DIM) {
            queue!(w, SetAttribute(Attribute::Dim))?;
        }
    } else {
        if added.contains(Modifiers::BOLD) {
            queue!(w, SetAttribute(Attribute::Bold))?;
        }
        if added.contains(Modifiers::DIM) {
            queue!(w, SetAttribute(Attribute::Dim))?;
        }
    }
    if removed.contains(Modifiers::ITALIC) {
        queue!(w, SetAttribute(Attribute::NoItalic))?;
    }
    if added.contains(Modifiers::ITALIC) {
        queue!(w, SetAttribute(Attribute::Italic))?;
    }
    if removed.contains(Modifiers::UNDERLINE) {
        queue!(w, SetAttribute(Attribute::NoUnderline))?;
    }
    if added.contains(Modifiers::UNDERLINE) {
        queue!(w, SetAttribute(Attribute::Underlined))?;
    }
    if removed.contains(Modifiers::REVERSED) {
        queue!(w, SetAttribute(Attribute::NoReverse))?;
    }
    if added.contains(Modifiers::REVERSED) {
        queue!(w, SetAttribute(Attribute::Reverse))?;
    }
    if removed.contains(Modifiers::STRIKETHROUGH) {
        queue!(w, SetAttribute(Attribute::NotCrossedOut))?;
    }
    if added.contains(Modifiers::STRIKETHROUGH) {
        queue!(w, SetAttribute(Attribute::CrossedOut))?;
    }
    if removed.contains(Modifiers::BLINK) {
        queue!(w, SetAttribute(Attribute::NoBlink))?;
    }
    if added.contains(Modifiers::BLINK) {
        queue!(w, SetAttribute(Attribute::SlowBlink))?;
    }
    if removed.contains(Modifiers::OVERLINE) {
        queue!(w, SetAttribute(Attribute::NotOverLined))?;
    }
    if added.contains(Modifiers::OVERLINE) {
        queue!(w, SetAttribute(Attribute::OverLined))?;
    }
    // Underline style and color use raw escapes: crossterm 0.28 cannot
    // express the `CSI 4:Nm` subparameters or the `SGR 58`/`59` underline
    // color reliably (its discriminants collide on these terminals).
    if old.underline_style != new.underline_style {
        write!(w, "\x1b[4:{}m", underline_style_param(new.underline_style))?;
    }
    if old.underline_color != new.underline_color {
        emit_underline_color(w, new.underline_color, depth)?;
    }
    Ok(())
}

/// Map an [`UnderlineStyle`] to its `CSI 4:Nm` subparameter value.
fn underline_style_param(style: UnderlineStyle) -> u8 {
    match style {
        UnderlineStyle::Straight => 1,
        UnderlineStyle::Double => 2,
        UnderlineStyle::Curly => 3,
        UnderlineStyle::Dotted => 4,
        UnderlineStyle::Dashed => 5,
    }
}

/// Emit the raw `SGR 58` underline-color sequence (or `SGR 59` to reset).
///
/// `None` resets the underline color to the foreground (`\x1b[59m`). Otherwise
/// the color is downsampled to the terminal's depth: true-color emits
/// `\x1b[58:2::r:g:bm`, while indexed/named colors emit `\x1b[58:5:im`.
fn emit_underline_color(
    w: &mut impl Write,
    color: Option<Color>,
    depth: ColorDepth,
) -> io::Result<()> {
    match color {
        None => write!(w, "\x1b[59m"),
        Some(c) => match c.downsampled(depth) {
            Color::Reset => write!(w, "\x1b[59m"),
            Color::Rgb(r, g, b) => write!(w, "\x1b[58:2::{r}:{g}:{b}m"),
            Color::Indexed(i) => write!(w, "\x1b[58:5:{i}m"),
            // Named colors have no direct SGR-58 form; resolve them to their
            // RGB equivalent and emit a true-color underline sequence.
            named => {
                let (r, g, b) = named.to_rgb();
                write!(w, "\x1b[58:2::{r}:{g}:{b}m")
            }
        },
    }
}

fn apply_style(w: &mut impl Write, style: &Style, depth: ColorDepth) -> io::Result<()> {
    if let Some(fg) = style.fg {
        queue!(w, SetForegroundColor(to_crossterm_color(fg, depth)))?;
    }
    if let Some(bg) = style.bg {
        queue!(w, SetBackgroundColor(to_crossterm_color(bg, depth)))?;
    }
    let m = style.modifiers;
    if m.contains(Modifiers::BOLD) {
        queue!(w, SetAttribute(Attribute::Bold))?;
    }
    if m.contains(Modifiers::DIM) {
        queue!(w, SetAttribute(Attribute::Dim))?;
    }
    if m.contains(Modifiers::ITALIC) {
        queue!(w, SetAttribute(Attribute::Italic))?;
    }
    if m.contains(Modifiers::UNDERLINE) {
        queue!(w, SetAttribute(Attribute::Underlined))?;
    }
    if m.contains(Modifiers::REVERSED) {
        queue!(w, SetAttribute(Attribute::Reverse))?;
    }
    if m.contains(Modifiers::STRIKETHROUGH) {
        queue!(w, SetAttribute(Attribute::CrossedOut))?;
    }
    if m.contains(Modifiers::BLINK) {
        queue!(w, SetAttribute(Attribute::SlowBlink))?;
    }
    if m.contains(Modifiers::OVERLINE) {
        queue!(w, SetAttribute(Attribute::OverLined))?;
    }
    if style.underline_style != UnderlineStyle::Straight {
        write!(
            w,
            "\x1b[4:{}m",
            underline_style_param(style.underline_style)
        )?;
    }
    if style.underline_color.is_some() {
        emit_underline_color(w, style.underline_color, depth)?;
    }
    Ok(())
}

fn to_crossterm_color(color: Color, depth: ColorDepth) -> CtColor {
    let color = color.downsampled(depth);
    match color {
        Color::Reset => CtColor::Reset,
        Color::Black => CtColor::Black,
        Color::Red => CtColor::DarkRed,
        Color::Green => CtColor::DarkGreen,
        Color::Yellow => CtColor::DarkYellow,
        Color::Blue => CtColor::DarkBlue,
        Color::Magenta => CtColor::DarkMagenta,
        Color::Cyan => CtColor::DarkCyan,
        Color::White => CtColor::White,
        Color::DarkGray => CtColor::DarkGrey,
        Color::LightRed => CtColor::Red,
        Color::LightGreen => CtColor::Green,
        Color::LightYellow => CtColor::Yellow,
        Color::LightBlue => CtColor::Blue,
        Color::LightMagenta => CtColor::Magenta,
        Color::LightCyan => CtColor::Cyan,
        Color::LightWhite => CtColor::White,
        Color::Rgb(r, g, b) => CtColor::Rgb { r, g, b },
        Color::Indexed(i) => CtColor::AnsiValue(i),
    }
}

fn reset_current_buffer(buffer: &mut Buffer, theme_bg: Option<Color>) {
    if let Some(bg) = theme_bg {
        buffer.reset_with_bg(bg);
    } else {
        buffer.reset();
    }
}

fn write_session_enter(stdout: &mut impl Write, session: &TerminalSessionGuard) -> io::Result<()> {
    match session.mode {
        TerminalSessionMode::Fullscreen => {
            execute!(
                stdout,
                terminal::EnterAlternateScreen,
                cursor::Hide,
                EnableBracketedPaste
            )?;
        }
        TerminalSessionMode::Inline => {
            execute!(stdout, cursor::Hide, EnableBracketedPaste)?;
        }
    }

    // Focus-change reporting is independent of mouse capture — callers
    // routinely pause animations or clear hover state on focus loss even
    // without mouse support. Enabling it unconditionally matches modern
    // TUI conventions (zellij, helix, yazi) and the cost is one extra SGR
    // per session.
    execute!(stdout, EnableFocusChange)?;
    if session.mouse_enabled {
        execute!(stdout, EnableMouseCapture)?;
    }
    if session.kitty_keyboard {
        use crossterm::event::PushKeyboardEnhancementFlags;
        let _ = execute!(
            stdout,
            PushKeyboardEnhancementFlags(kitty_flags(session.report_all_keys))
        );
    }

    Ok(())
}

/// Assemble the Kitty keyboard enhancement flags to push.
///
/// Always sets `DISAMBIGUATE_ESCAPE_CODES | REPORT_EVENT_TYPES`. When
/// `report_all_keys` is `true`, also OR-es in
/// `REPORT_ALL_KEYS_AS_ESCAPE_CODES`, which is the only mechanism by which a
/// spec-compliant terminal emits a bare modifier as a key event.
///
/// This is a pure helper so the flag assembly can be unit-tested without
/// touching stdout.
fn kitty_flags(report_all_keys: bool) -> crossterm::event::KeyboardEnhancementFlags {
    use crossterm::event::KeyboardEnhancementFlags;
    let mut flags = KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
        | KeyboardEnhancementFlags::REPORT_EVENT_TYPES;
    if report_all_keys {
        flags |= KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES;
    }
    flags
}

fn write_session_cleanup(
    stdout: &mut impl Write,
    mode: TerminalSessionMode,
    inline_reserved: bool,
) -> io::Result<()> {
    execute!(
        stdout,
        ResetColor,
        SetAttribute(Attribute::Reset),
        cursor::Show,
        DisableBracketedPaste
    )?;

    match mode {
        TerminalSessionMode::Fullscreen => {
            execute!(stdout, terminal::LeaveAlternateScreen)?;
        }
        TerminalSessionMode::Inline => {
            if inline_reserved {
                execute!(
                    stdout,
                    cursor::MoveToColumn(0),
                    cursor::MoveDown(1),
                    cursor::MoveToColumn(0),
                    Print("\n")
                )?;
            } else {
                execute!(stdout, Print("\n"))?;
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Unix job-control suspend/resume (Ctrl+Z / `fg`) — issue #263
// ---------------------------------------------------------------------------
//
// On Unix, SIGTSTP stops the process in kernel space with no Rust code on the
// stack, so neither `Drop` nor the panic hook can restore the terminal. The
// run loops install a `signal-hook` background thread that, on SIGTSTP, runs
// the same teardown the session guard would (`disable_raw_mode`, leave alt
// screen, show cursor, disable paste/focus/mouse/kitty) and then re-raises
// SIGTSTP to genuinely stop; on SIGCONT it re-enters the session and flags a
// full redraw. The whole feature is `#[cfg(unix)]` and uses only signal-hook's
// safe API, preserving `#![forbid(unsafe_code)]`.

/// Immutable snapshot of the active terminal session used by the unix
/// suspend/resume handler to restore and re-enter the terminal across a
/// Ctrl+Z / `fg` cycle without owning the `Terminal`/`InlineTerminal`.
#[cfg(unix)]
#[derive(Debug, Clone, Copy)]
pub(crate) struct SessionSnapshot {
    mode: TerminalSessionMode,
    mouse_enabled: bool,
    kitty_keyboard: bool,
    report_all_keys: bool,
}

/// Set by the SIGCONT handler and consumed once at the top of each run-loop
/// iteration to force a full clear + repaint after resuming from suspend.
#[cfg(unix)]
pub(crate) static NEEDS_FULL_REDRAW: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

#[cfg(unix)]
impl Terminal {
    /// Capture the session state the suspend/resume handler needs to restore
    /// and re-enter this fullscreen terminal across Ctrl+Z / `fg`.
    pub(crate) fn session_snapshot(&self) -> SessionSnapshot {
        SessionSnapshot {
            mode: self.session.mode,
            mouse_enabled: self.session.mouse_enabled,
            kitty_keyboard: self.session.kitty_keyboard,
            report_all_keys: self.session.report_all_keys,
        }
    }
}

#[cfg(unix)]
impl InlineTerminal {
    /// Capture the session state the suspend/resume handler needs to restore
    /// and re-enter this inline terminal across Ctrl+Z / `fg`.
    pub(crate) fn session_snapshot(&self) -> SessionSnapshot {
        SessionSnapshot {
            mode: self.session.mode,
            mouse_enabled: self.session.mouse_enabled,
            kitty_keyboard: self.session.kitty_keyboard,
            report_all_keys: self.session.report_all_keys,
        }
    }
}

/// Write the escape sequences that tear down the TUI session in preparation
/// for SIGTSTP (the inverse of [`write_session_enter`]).
///
/// `inline_reserved` is passed `false` to [`write_session_cleanup`] to avoid
/// emitting the inline trailing-newline dance mid-session; the reserved region
/// is repainted on resume via the forced full redraw. Pure byte output, no
/// raw-mode toggle — split out so it can be unit-tested against a `Vec<u8>`.
#[cfg(unix)]
fn write_suspend_sequence(stdout: &mut impl Write, snapshot: &SessionSnapshot) -> io::Result<()> {
    if snapshot.kitty_keyboard {
        use crossterm::event::PopKeyboardEnhancementFlags;
        execute!(stdout, PopKeyboardEnhancementFlags)?;
    }
    if snapshot.mouse_enabled {
        execute!(stdout, DisableMouseCapture)?;
    }
    execute!(stdout, DisableFocusChange)?;
    write_session_cleanup(stdout, snapshot.mode, false)
}

/// Restore the terminal to cooked/non-TUI state in preparation for the process
/// being stopped by SIGTSTP.
///
/// Mirrors [`TerminalSessionGuard::restore`] but writes directly to
/// `io::stdout()` (the handler runs on a background thread that does not own
/// the buffered terminal stdout).
#[cfg(unix)]
pub(crate) fn suspend_to_shell(snapshot: &SessionSnapshot) {
    let mut out = io::stdout();
    let _ = write_suspend_sequence(&mut out, snapshot);
    let _ = terminal::disable_raw_mode();
    let _ = out.flush();
}

/// Re-enter the TUI session after a SIGCONT (resume via `fg`), matching the
/// original [`SessionSnapshot`], and flag a full redraw for the next frame.
///
/// Mirrors [`TerminalSessionGuard::enter`] but writes directly to
/// `io::stdout()`. Sets [`NEEDS_FULL_REDRAW`] so the next loop iteration clears
/// the front buffer and repaints every cell.
#[cfg(unix)]
pub(crate) fn resume_from_shell(snapshot: &SessionSnapshot) {
    let mut out = io::stdout();
    let _ = terminal::enable_raw_mode();
    let guard = TerminalSessionGuard {
        mode: snapshot.mode,
        mouse_enabled: snapshot.mouse_enabled,
        kitty_keyboard: snapshot.kitty_keyboard,
        report_all_keys: snapshot.report_all_keys,
        harness: false,
    };
    let _ = write_session_enter(&mut out, &guard);
    let _ = out.flush();
    NEEDS_FULL_REDRAW.store(true, std::sync::atomic::Ordering::SeqCst);
}

/// Construct a [`SessionSnapshot`] for tests without a live terminal.
#[cfg(all(unix, test))]
fn test_snapshot(mode: TerminalSessionMode, mouse: bool, kitty: bool) -> SessionSnapshot {
    SessionSnapshot {
        mode,
        mouse_enabled: mouse,
        kitty_keyboard: kitty,
        report_all_keys: false,
    }
}

/// Construct a fullscreen [`SessionSnapshot`] for crate-level tests that drive
/// the suspend handler without a live terminal (issue #263).
#[cfg(all(unix, test))]
pub(crate) fn test_session_snapshot() -> SessionSnapshot {
    SessionSnapshot {
        mode: TerminalSessionMode::Fullscreen,
        mouse_enabled: false,
        kitty_keyboard: false,
        report_all_keys: false,
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    use super::*;

    /// Feed `bytes` to a channel from a helper thread after `delay`, then run
    /// [`collect_reply`] against it with the given budget and predicate.
    fn collect_with_feed(
        bytes: &'static [u8],
        delay: Duration,
        budget: Duration,
        is_complete: &mut dyn FnMut(&[u8]) -> bool,
    ) -> (Vec<u8>, Duration) {
        let (tx, rx) = std::sync::mpsc::channel::<u8>();
        std::thread::spawn(move || {
            std::thread::sleep(delay);
            for &b in bytes {
                if tx.send(b).is_err() {
                    return;
                }
            }
            // Keep the sender alive past the collector's budget: the real
            // pump thread only drops its sender on stdin EOF, so dropping it
            // here right after the payload would disconnect the channel and
            // end the wait early, masking deadline behavior.
            std::thread::sleep(Duration::from_secs(3));
        });
        let start = Instant::now();
        let out = collect_reply(&rx, start + budget, is_complete);
        (out, start.elapsed())
    }

    #[test]
    fn collect_reply_osc_bel_terminator_completes_early() {
        let reply = b"\x1b]11;rgb:0000/0000/0000\x07";
        let (out, elapsed) = collect_with_feed(
            reply,
            Duration::ZERO,
            Duration::from_secs(2),
            &mut osc_reply_complete,
        );
        assert_eq!(out, reply);
        assert!(
            elapsed < Duration::from_secs(1),
            "should not wait out the budget"
        );
    }

    #[test]
    fn collect_reply_osc_st_terminator_completes_early() {
        let reply = b"\x1bP>|tmux 3.5a\x1b\\";
        let (out, elapsed) = collect_with_feed(
            reply,
            Duration::ZERO,
            Duration::from_secs(2),
            &mut osc_reply_complete,
        );
        assert_eq!(out, reply);
        assert!(elapsed < Duration::from_secs(1));
    }

    #[test]
    fn collect_reply_silence_returns_empty_at_deadline() {
        // The silent-host case that used to deadlock startup: no bytes ever
        // arrive. The collector must give up at the deadline, not block.
        let budget = Duration::from_millis(150);
        let (out, elapsed) =
            collect_with_feed(b"", Duration::from_secs(5), budget, &mut osc_reply_complete);
        assert!(out.is_empty());
        assert!(elapsed >= budget);
        assert!(
            elapsed < Duration::from_secs(2),
            "must not block past the budget"
        );
    }

    #[test]
    fn collect_reply_da_drains_two_replies() {
        let reply = b"\x1b[?62;4c\x1b[>1;10;0c";
        let (out, elapsed) = collect_with_feed(
            reply,
            Duration::ZERO,
            Duration::from_secs(2),
            &mut da_reply_complete(),
        );
        assert_eq!(out, reply);
        assert!(elapsed < Duration::from_secs(1));
    }

    #[test]
    fn collect_reply_da_lone_reply_returns_partial_at_deadline() {
        // A terminal that answers DA1 but ignores DA2: the collector waits out
        // the budget, then hands back the partial reply for best-effort parse
        // (pre-pump behavior, preserved).
        let budget = Duration::from_millis(150);
        let (out, elapsed) = collect_with_feed(
            b"\x1b[?62;4c",
            Duration::ZERO,
            budget,
            &mut da_reply_complete(),
        );
        assert_eq!(out, b"\x1b[?62;4c");
        assert!(elapsed >= budget);
    }

    #[test]
    fn collect_reply_unterminated_caps_at_4096_bytes() {
        static BIG: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
        let big = BIG.get_or_init(|| vec![b'x'; 5000]).as_slice();
        let (tx, rx) = std::sync::mpsc::channel::<u8>();
        for &b in big {
            tx.send(b).unwrap();
        }
        let out = collect_reply(
            &rx,
            Instant::now() + Duration::from_secs(2),
            &mut osc_reply_complete,
        );
        assert_eq!(out.len(), 4096);
    }

    #[test]
    fn decrpm_predicate_terminates_on_y() {
        let reply = b"\x1b[?2026;1$y";
        let (out, _) = collect_with_feed(
            reply,
            Duration::ZERO,
            Duration::from_secs(2),
            &mut decrpm_reply_complete,
        );
        assert_eq!(out, reply);
    }

    #[test]
    fn reset_current_buffer_applies_theme_background() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 2, 1));

        reset_current_buffer(&mut buffer, Some(Color::Rgb(10, 20, 30)));
        assert_eq!(buffer.get(0, 0).style.bg, Some(Color::Rgb(10, 20, 30)));

        reset_current_buffer(&mut buffer, None);
        assert_eq!(buffer.get(0, 0).style.bg, None);
    }

    #[test]
    fn fullscreen_session_enter_writes_alt_screen_sequence() {
        let session = TerminalSessionGuard {
            mode: TerminalSessionMode::Fullscreen,
            mouse_enabled: false,
            kitty_keyboard: false,
            report_all_keys: false,
            harness: false,
        };
        let mut out = Vec::new();
        write_session_enter(&mut out, &session).unwrap();
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("\u{1b}[?1049h"));
        assert!(output.contains("\u{1b}[?25l"));
        assert!(output.contains("\u{1b}[?2004h"));
    }

    #[test]
    fn inline_session_enter_skips_alt_screen_sequence() {
        let session = TerminalSessionGuard {
            mode: TerminalSessionMode::Inline,
            mouse_enabled: false,
            kitty_keyboard: false,
            report_all_keys: false,
            harness: false,
        };
        let mut out = Vec::new();
        write_session_enter(&mut out, &session).unwrap();
        let output = String::from_utf8(out).unwrap();
        assert!(!output.contains("\u{1b}[?1049h"));
        assert!(output.contains("\u{1b}[?25l"));
        assert!(output.contains("\u{1b}[?2004h"));
    }

    #[test]
    fn fullscreen_session_cleanup_leaves_alt_screen() {
        let mut out = Vec::new();
        write_session_cleanup(&mut out, TerminalSessionMode::Fullscreen, false).unwrap();
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("\u{1b}[?1049l"));
        assert!(output.contains("\u{1b}[?25h"));
        assert!(output.contains("\u{1b}[?2004l"));
    }

    #[test]
    fn inline_session_cleanup_keeps_normal_screen() {
        let mut out = Vec::new();
        write_session_cleanup(&mut out, TerminalSessionMode::Inline, false).unwrap();
        let output = String::from_utf8(out).unwrap();
        assert!(!output.contains("\u{1b}[?1049l"));
        assert!(output.ends_with('\n'));
        assert!(output.contains("\u{1b}[?25h"));
        assert!(output.contains("\u{1b}[?2004l"));
    }

    // ── Unix suspend/resume sequence tests (issue #263) ──────────────────

    #[cfg(unix)]
    #[test]
    fn suspend_sequence_fullscreen_leaves_alt_screen() {
        let snapshot = test_snapshot(TerminalSessionMode::Fullscreen, false, false);
        let mut out = Vec::new();
        write_suspend_sequence(&mut out, &snapshot).unwrap();
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("\u{1b}[?1049l"), "leaves alt screen");
        assert!(output.contains("\u{1b}[?25h"), "shows cursor");
        assert!(output.contains("\u{1b}[?2004l"), "disables bracketed paste");
    }

    #[cfg(unix)]
    #[test]
    fn suspend_sequence_inline_keeps_normal_screen() {
        let snapshot = test_snapshot(TerminalSessionMode::Inline, false, false);
        let mut out = Vec::new();
        write_suspend_sequence(&mut out, &snapshot).unwrap();
        let output = String::from_utf8(out).unwrap();
        assert!(
            !output.contains("\u{1b}[?1049l"),
            "inline must not leave alt screen"
        );
        assert!(output.contains("\u{1b}[?25h"), "shows cursor");
        assert!(output.contains("\u{1b}[?2004l"), "disables bracketed paste");
    }

    #[cfg(unix)]
    #[test]
    fn suspend_sequence_disables_mouse_and_kitty_when_enabled() {
        let snapshot = test_snapshot(TerminalSessionMode::Fullscreen, true, true);
        let mut out = Vec::new();
        write_suspend_sequence(&mut out, &snapshot).unwrap();
        // DisableMouseCapture emits the SGR-mouse disable (?1006l) among others.
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("\u{1b}[?1006l"), "disables SGR mouse mode");
    }

    #[cfg(unix)]
    #[test]
    fn resume_sequence_fullscreen_round_trips_enter_and_flags_redraw() {
        let snapshot = test_snapshot(TerminalSessionMode::Fullscreen, false, false);

        // The resume path re-enters the same byte state as the initial enter.
        let guard = TerminalSessionGuard {
            mode: snapshot.mode,
            mouse_enabled: snapshot.mouse_enabled,
            kitty_keyboard: snapshot.kitty_keyboard,
            report_all_keys: snapshot.report_all_keys,
            harness: false,
        };
        let mut enter_bytes = Vec::new();
        write_session_enter(&mut enter_bytes, &guard).unwrap();
        let enter = String::from_utf8(enter_bytes).unwrap();
        assert!(enter.contains("\u{1b}[?1049h"));
        assert!(enter.contains("\u{1b}[?25l"));
        assert!(enter.contains("\u{1b}[?2004h"));

        // Drive the public resume entry point and assert the redraw flag flips.
        NEEDS_FULL_REDRAW.store(false, std::sync::atomic::Ordering::SeqCst);
        resume_from_shell(&snapshot);
        assert!(
            NEEDS_FULL_REDRAW.swap(false, std::sync::atomic::Ordering::SeqCst),
            "resume must request a full redraw exactly once"
        );
        assert!(
            !NEEDS_FULL_REDRAW.swap(false, std::sync::atomic::Ordering::SeqCst),
            "the redraw flag is consumed by the first swap (idempotent)"
        );
    }

    #[cfg(unix)]
    #[test]
    fn needs_full_redraw_swaps_true_once() {
        NEEDS_FULL_REDRAW.store(true, std::sync::atomic::Ordering::SeqCst);
        assert!(NEEDS_FULL_REDRAW.swap(false, std::sync::atomic::Ordering::SeqCst));
        assert!(!NEEDS_FULL_REDRAW.swap(false, std::sync::atomic::Ordering::SeqCst));
    }

    #[test]
    fn kitty_flags_base_set_excludes_report_all_keys() {
        use crossterm::event::KeyboardEnhancementFlags;
        let flags = kitty_flags(false);
        assert!(flags.contains(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES));
        assert!(flags.contains(KeyboardEnhancementFlags::REPORT_EVENT_TYPES));
        assert!(!flags.contains(KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES));
    }

    #[test]
    fn kitty_flags_report_all_keys_sets_flag() {
        use crossterm::event::KeyboardEnhancementFlags;
        let flags = kitty_flags(true);
        assert!(flags.contains(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES));
        assert!(flags.contains(KeyboardEnhancementFlags::REPORT_EVENT_TYPES));
        assert!(flags.contains(KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES));
    }

    #[test]
    fn base64_encode_empty() {
        assert_eq!(base64_encode(b""), "");
    }

    #[test]
    fn base64_encode_hello() {
        assert_eq!(base64_encode(b"Hello"), "SGVsbG8=");
    }

    #[test]
    fn base64_encode_padding() {
        assert_eq!(base64_encode(b"a"), "YQ==");
        assert_eq!(base64_encode(b"ab"), "YWI=");
        assert_eq!(base64_encode(b"abc"), "YWJj");
    }

    #[test]
    fn base64_encode_unicode() {
        assert_eq!(base64_encode("한글".as_bytes()), "7ZWc6riA");
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_osc11_response_dark_and_light() {
        assert_eq!(
            parse_osc11_response("\x1b]11;rgb:0000/0000/0000\x1b\\"),
            ColorScheme::Dark
        );
        assert_eq!(
            parse_osc11_response("\x1b]11;rgb:ffff/ffff/ffff\x07"),
            ColorScheme::Light
        );
    }

    // ---- Capability probe / blitter ladder (issue #264) ----

    #[test]
    fn blitter_support_default_is_conservative() {
        let b = BlitterSupport::default();
        assert!(b.half);
        assert!(b.quad);
        assert!(!b.sextant);
    }

    #[test]
    fn capabilities_default_is_all_false_but_half_block() {
        let c = Capabilities::default();
        assert!(!c.truecolor);
        assert!(!c.sixel);
        assert!(!c.iterm2);
        assert!(!c.kitty_graphics);
        assert!(!c.kitty_keyboard);
        assert!(!c.sync_output);
        // With nothing negotiated the ladder must still resolve to half-block.
        assert_eq!(c.best_blitter(), Blitter::HalfBlock);
    }

    #[test]
    fn best_blitter_ladder_table() {
        let kitty = Capabilities {
            kitty_graphics: true,
            ..Default::default()
        };
        assert_eq!(kitty.best_blitter(), Blitter::Kitty);

        let sixel = Capabilities {
            sixel: true,
            ..Default::default()
        };
        assert_eq!(sixel.best_blitter(), Blitter::Sixel);

        let iterm2 = Capabilities {
            iterm2: true,
            ..Default::default()
        };
        assert_eq!(iterm2.best_blitter(), Blitter::Iterm2);

        // iTerm2 sits below Sixel: a host advertising both prefers Sixel.
        let sixel_and_iterm2 = Capabilities {
            sixel: true,
            iterm2: true,
            ..Default::default()
        };
        assert_eq!(sixel_and_iterm2.best_blitter(), Blitter::Sixel);

        let sextant = Capabilities {
            blitters: BlitterSupport {
                sextant: true,
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(sextant.best_blitter(), Blitter::Sextant);

        assert_eq!(Capabilities::default().best_blitter(), Blitter::HalfBlock);
    }

    #[test]
    fn best_blitter_precedence_kitty_over_everything() {
        let all = Capabilities {
            kitty_graphics: true,
            sixel: true,
            blitters: BlitterSupport {
                sextant: true,
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(all.best_blitter(), Blitter::Kitty);

        let sixel_and_sextant = Capabilities {
            sixel: true,
            blitters: BlitterSupport {
                sextant: true,
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(sixel_and_sextant.best_blitter(), Blitter::Sixel);
    }

    #[test]
    fn best_blitter_never_picks_unsupported_protocol() {
        // Exhaustive sweep over field combinations: the resolver must never
        // return Kitty without kitty_graphics, nor Sixel without sixel, etc.
        for kitty in [false, true] {
            for sixel in [false, true] {
                for iterm2 in [false, true] {
                    for sextant in [false, true] {
                        let caps = Capabilities {
                            kitty_graphics: kitty,
                            sixel,
                            iterm2,
                            blitters: BlitterSupport {
                                sextant,
                                ..Default::default()
                            },
                            ..Default::default()
                        };
                        match caps.best_blitter() {
                            Blitter::Kitty => assert!(kitty),
                            Blitter::Sixel => assert!(sixel && !kitty),
                            Blitter::Iterm2 => assert!(iterm2 && !sixel && !kitty),
                            Blitter::Sextant => {
                                assert!(sextant && !iterm2 && !sixel && !kitty)
                            }
                            Blitter::HalfBlock => {
                                assert!(!kitty && !sixel && !iterm2 && !sextant)
                            }
                        }
                    }
                }
            }
        }
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_da1_attribute_4_sets_sixel() {
        let mut caps = Capabilities::default();
        parse_da1("\x1b[?62;4;6c", &mut caps);
        assert!(caps.sixel);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_da1_without_4_leaves_sixel_false() {
        let mut caps = Capabilities::default();
        parse_da1("\x1b[?62;1;6c", &mut caps);
        assert!(!caps.sixel);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_da1_ignores_da2_segment_in_same_string() {
        // DA1 (no `4`) followed by DA2 — DA2 must not be mistaken for DA1.
        let mut caps = Capabilities::default();
        parse_da1("\x1b[?62;1c\x1b[>0;276;0c", &mut caps);
        assert!(!caps.sixel);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_da2_no_panic_on_garbage() {
        let mut caps = Capabilities::default();
        // Must not panic and must not set kitty_graphics on an unknown id.
        parse_da2("\x1b[>99;1;0c", &mut caps);
        assert!(!caps.kitty_graphics);
        parse_da2("not a da2 reply", &mut caps);
        assert!(!caps.kitty_graphics);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_da2_kitty_id_sets_kitty_graphics() {
        let mut caps = Capabilities::default();
        // Kitty reports DA2 primary id 41.
        parse_da2("\x1b[>41;4000;0c", &mut caps);
        assert!(caps.kitty_graphics);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_da2_identity_extracts_id_and_version() {
        assert_eq!(parse_da2_identity("\x1b[>0;276;0c"), Some((0, 276)));
        assert_eq!(parse_da2_identity("\x1b[>41;4000;0c"), Some((41, 4000)));
        assert_eq!(parse_da2_identity("no reply here"), None);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_kitty_graphics_ack_ok_sets_flag() {
        let mut caps = Capabilities::default();
        parse_kitty_graphics_ack("\x1b_Gi=31;OK\x1b\\", &mut caps);
        assert!(caps.kitty_graphics);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_kitty_graphics_ack_error_or_wrong_id_leaves_flag() {
        let mut caps = Capabilities::default();
        // Error status must not flag support.
        parse_kitty_graphics_ack("\x1b_Gi=31;ENOENT:bad\x1b\\", &mut caps);
        assert!(!caps.kitty_graphics);
        // A different image id is not our query.
        parse_kitty_graphics_ack("\x1b_Gi=99;OK\x1b\\", &mut caps);
        assert!(!caps.kitty_graphics);
        // No APC at all.
        parse_kitty_graphics_ack("garbage", &mut caps);
        assert!(!caps.kitty_graphics);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_decrpm_sync_output_recognized_states_are_supported() {
        // Ps = 1 (set), 2 (reset), 3 (perm set), 4 (perm reset) all mean the
        // mode is recognized → supported.
        assert_eq!(parse_decrpm_sync_output("\x1b[?2026;1$y"), Some(true));
        assert_eq!(parse_decrpm_sync_output("\x1b[?2026;2$y"), Some(true));
        assert_eq!(parse_decrpm_sync_output("\x1b[?2026;3$y"), Some(true));
        assert_eq!(parse_decrpm_sync_output("\x1b[?2026;4$y"), Some(true));
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_decrpm_sync_output_ps0_is_unsupported() {
        // Ps = 0 → mode not recognized.
        assert_eq!(parse_decrpm_sync_output("\x1b[?2026;0$y"), Some(false));
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_decrpm_sync_output_garbage_is_none() {
        // No DECRPM reply for mode 2026 in the string → inconclusive.
        assert_eq!(parse_decrpm_sync_output("not a decrpm reply"), None);
        // A reply for a *different* mode must not match.
        assert_eq!(parse_decrpm_sync_output("\x1b[?2004;1$y"), None);
        // Truncated reply (missing `$y` terminator) → None, not a panic.
        assert_eq!(parse_decrpm_sync_output("\x1b[?2026;1"), None);
        // Non-numeric Ps → None.
        assert_eq!(parse_decrpm_sync_output("\x1b[?2026;x$y"), None);
    }

    #[test]
    fn sync_output_gate_defaults_to_emit() {
        // With the probe never having run (the unit-test process never enters a
        // real terminal session), the resolution stays `Unknown`, so the gate
        // must keep emitting BSU/ESU — preserving the historic always-emit
        // behavior on headless / non-answering hosts.
        assert!(should_emit_synchronized_update());
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_xtgettcap_tc_sets_truecolor() {
        let mut caps = Capabilities::default();
        // DCS 1 + r 5463 (=Tc) ST → truecolor present.
        parse_xtgettcap_truecolor("\x1bP1+r5463=\x1b\\", &mut caps);
        assert!(caps.truecolor);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn parse_xtgettcap_invalid_leaves_truecolor_false() {
        let mut caps = Capabilities::default();
        // DCS 0 + r (capability NOT present) must not set the flag.
        parse_xtgettcap_truecolor("\x1bP0+r5463\x1b\\", &mut caps);
        assert!(!caps.truecolor);
        // Wrong capname hex must not match.
        parse_xtgettcap_truecolor("\x1bP1+r1234=\x1b\\", &mut caps);
        assert!(!caps.truecolor);
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn base64_decode_round_trip_hello() {
        let encoded = base64_encode("hello".as_bytes());
        assert_eq!(base64_decode(&encoded), Some("hello".to_string()));
    }

    #[cfg(feature = "crossterm")]
    #[test]
    fn color_scheme_equality() {
        assert_eq!(ColorScheme::Dark, ColorScheme::Dark);
        assert_ne!(ColorScheme::Dark, ColorScheme::Light);
        assert_eq!(ColorScheme::Unknown, ColorScheme::Unknown);
    }

    fn pair(r: Rect) -> (Rect, Rect) {
        (r, r)
    }

    #[test]
    fn find_innermost_rect_picks_smallest() {
        let rects = vec![
            pair(Rect::new(0, 0, 80, 24)),
            pair(Rect::new(5, 2, 30, 10)),
            pair(Rect::new(10, 4, 10, 5)),
        ];
        let result = find_innermost_rect(&rects, 12, 5);
        assert_eq!(result, Some(Rect::new(10, 4, 10, 5)));
    }

    #[test]
    fn find_innermost_rect_no_match() {
        let rects = vec![pair(Rect::new(10, 10, 5, 5))];
        assert_eq!(find_innermost_rect(&rects, 0, 0), None);
    }

    #[test]
    fn find_innermost_rect_empty() {
        assert_eq!(find_innermost_rect(&[], 5, 5), None);
    }

    #[test]
    fn find_innermost_rect_returns_content_rect() {
        let rects = vec![
            (Rect::new(0, 0, 80, 24), Rect::new(1, 1, 78, 22)),
            (Rect::new(5, 2, 30, 10), Rect::new(6, 3, 28, 8)),
        ];
        let result = find_innermost_rect(&rects, 10, 5);
        assert_eq!(result, Some(Rect::new(6, 3, 28, 8)));
    }

    #[test]
    fn normalize_selection_already_ordered() {
        let (s, e) = normalize_selection((2, 1), (5, 3));
        assert_eq!(s, (2, 1));
        assert_eq!(e, (5, 3));
    }

    #[test]
    fn normalize_selection_reversed() {
        let (s, e) = normalize_selection((5, 3), (2, 1));
        assert_eq!(s, (2, 1));
        assert_eq!(e, (5, 3));
    }

    #[test]
    fn normalize_selection_same_row() {
        let (s, e) = normalize_selection((10, 5), (3, 5));
        assert_eq!(s, (3, 5));
        assert_eq!(e, (10, 5));
    }

    #[test]
    fn selection_state_mouse_down_finds_rect() {
        let hit_map = vec![pair(Rect::new(0, 0, 80, 24)), pair(Rect::new(5, 2, 20, 10))];
        let mut sel = SelectionState::default();
        sel.mouse_down(10, 5, &hit_map);
        assert_eq!(sel.anchor, Some((10, 5)));
        assert_eq!(sel.current, Some((10, 5)));
        assert_eq!(sel.widget_rect, Some(Rect::new(5, 2, 20, 10)));
        assert!(!sel.active);
    }

    #[test]
    fn selection_state_drag_activates() {
        let hit_map = vec![pair(Rect::new(0, 0, 80, 24))];
        let mut sel = SelectionState {
            anchor: Some((10, 5)),
            current: Some((10, 5)),
            widget_rect: Some(Rect::new(0, 0, 80, 24)),
            ..Default::default()
        };
        sel.mouse_drag(10, 5, &hit_map);
        assert!(!sel.active, "no movement = not active");
        sel.mouse_drag(11, 5, &hit_map);
        assert!(!sel.active, "1 cell horizontal = not active yet");
        sel.mouse_drag(13, 5, &hit_map);
        assert!(sel.active, ">1 cell horizontal = active");
    }

    #[test]
    fn selection_state_drag_vertical_activates() {
        let hit_map = vec![pair(Rect::new(0, 0, 80, 24))];
        let mut sel = SelectionState {
            anchor: Some((10, 5)),
            current: Some((10, 5)),
            widget_rect: Some(Rect::new(0, 0, 80, 24)),
            ..Default::default()
        };
        sel.mouse_drag(10, 6, &hit_map);
        assert!(sel.active, "any vertical movement = active");
    }

    #[test]
    fn selection_state_drag_expands_widget_rect() {
        let hit_map = vec![
            pair(Rect::new(0, 0, 80, 24)),
            pair(Rect::new(5, 2, 30, 10)),
            pair(Rect::new(5, 2, 30, 3)),
        ];
        let mut sel = SelectionState {
            anchor: Some((10, 3)),
            current: Some((10, 3)),
            widget_rect: Some(Rect::new(5, 2, 30, 3)),
            ..Default::default()
        };
        sel.mouse_drag(10, 6, &hit_map);
        assert_eq!(sel.widget_rect, Some(Rect::new(5, 2, 30, 10)));
    }

    #[test]
    fn selection_state_clear_resets() {
        let mut sel = SelectionState {
            anchor: Some((1, 2)),
            current: Some((3, 4)),
            widget_rect: Some(Rect::new(0, 0, 10, 10)),
            active: true,
        };
        sel.clear();
        assert_eq!(sel.anchor, None);
        assert_eq!(sel.current, None);
        assert_eq!(sel.widget_rect, None);
        assert!(!sel.active);
    }

    #[test]
    fn extract_selection_text_single_line() {
        let area = Rect::new(0, 0, 20, 5);
        let mut buf = Buffer::empty(area);
        buf.set_string(0, 0, "Hello World", Style::default());
        let sel = SelectionState {
            anchor: Some((0, 0)),
            current: Some((4, 0)),
            widget_rect: Some(area),
            active: true,
        };
        let text = extract_selection_text(&buf, &sel, &[]);
        assert_eq!(text, "Hello");
    }

    #[test]
    fn extract_selection_text_multi_line() {
        let area = Rect::new(0, 0, 20, 5);
        let mut buf = Buffer::empty(area);
        buf.set_string(0, 0, "Line one", Style::default());
        buf.set_string(0, 1, "Line two", Style::default());
        buf.set_string(0, 2, "Line three", Style::default());
        let sel = SelectionState {
            anchor: Some((5, 0)),
            current: Some((3, 2)),
            widget_rect: Some(area),
            active: true,
        };
        let text = extract_selection_text(&buf, &sel, &[]);
        assert_eq!(text, "one\nLine two\nLine");
    }

    #[test]
    fn extract_selection_text_clamped_to_widget() {
        let area = Rect::new(0, 0, 40, 10);
        let widget = Rect::new(5, 2, 10, 3);
        let mut buf = Buffer::empty(area);
        buf.set_string(5, 2, "ABCDEFGHIJ", Style::default());
        buf.set_string(5, 3, "KLMNOPQRST", Style::default());
        let sel = SelectionState {
            anchor: Some((3, 1)),
            current: Some((20, 5)),
            widget_rect: Some(widget),
            active: true,
        };
        let text = extract_selection_text(&buf, &sel, &[]);
        assert_eq!(text, "ABCDEFGHIJ\nKLMNOPQRST");
    }

    #[test]
    fn extract_selection_text_inactive_returns_empty() {
        let area = Rect::new(0, 0, 10, 5);
        let buf = Buffer::empty(area);
        let sel = SelectionState {
            anchor: Some((0, 0)),
            current: Some((5, 2)),
            widget_rect: Some(area),
            active: false,
        };
        assert_eq!(extract_selection_text(&buf, &sel, &[]), "");
    }

    #[test]
    fn apply_selection_overlay_reverses_cells() {
        let area = Rect::new(0, 0, 10, 3);
        let mut buf = Buffer::empty(area);
        buf.set_string(0, 0, "ABCDE", Style::default());
        let sel = SelectionState {
            anchor: Some((1, 0)),
            current: Some((3, 0)),
            widget_rect: Some(area),
            active: true,
        };
        apply_selection_overlay(&mut buf, &sel, &[]);
        assert!(!buf.get(0, 0).style.modifiers.contains(Modifiers::REVERSED));
        assert!(buf.get(1, 0).style.modifiers.contains(Modifiers::REVERSED));
        assert!(buf.get(2, 0).style.modifiers.contains(Modifiers::REVERSED));
        assert!(buf.get(3, 0).style.modifiers.contains(Modifiers::REVERSED));
        assert!(!buf.get(4, 0).style.modifiers.contains(Modifiers::REVERSED));
    }

    #[test]
    fn extract_selection_text_skips_border_cells() {
        // Simulate two bordered columns side by side:
        // Col1: full=(0,0,20,5) content=(1,1,18,3)
        // Col2: full=(20,0,20,5) content=(21,1,18,3)
        // Parent widget_rect covers both: (0,0,40,5)
        let area = Rect::new(0, 0, 40, 5);
        let mut buf = Buffer::empty(area);
        // Col1 border characters
        buf.set_string(0, 0, "", Style::default());
        buf.set_string(0, 1, "", Style::default());
        buf.set_string(0, 2, "", Style::default());
        buf.set_string(0, 3, "", Style::default());
        buf.set_string(0, 4, "", Style::default());
        buf.set_string(19, 0, "", Style::default());
        buf.set_string(19, 1, "", Style::default());
        buf.set_string(19, 2, "", Style::default());
        buf.set_string(19, 3, "", Style::default());
        buf.set_string(19, 4, "", Style::default());
        // Col2 border characters
        buf.set_string(20, 0, "", Style::default());
        buf.set_string(20, 1, "", Style::default());
        buf.set_string(20, 2, "", Style::default());
        buf.set_string(20, 3, "", Style::default());
        buf.set_string(20, 4, "", Style::default());
        buf.set_string(39, 0, "", Style::default());
        buf.set_string(39, 1, "", Style::default());
        buf.set_string(39, 2, "", Style::default());
        buf.set_string(39, 3, "", Style::default());
        buf.set_string(39, 4, "", Style::default());
        // Content inside Col1
        buf.set_string(1, 1, "Hello Col1", Style::default());
        buf.set_string(1, 2, "Line2 Col1", Style::default());
        // Content inside Col2
        buf.set_string(21, 1, "Hello Col2", Style::default());
        buf.set_string(21, 2, "Line2 Col2", Style::default());

        let content_map = vec![
            (Rect::new(0, 0, 20, 5), Rect::new(1, 1, 18, 3)),
            (Rect::new(20, 0, 20, 5), Rect::new(21, 1, 18, 3)),
        ];

        // Select across both columns, rows 1-2
        let sel = SelectionState {
            anchor: Some((0, 1)),
            current: Some((39, 2)),
            widget_rect: Some(area),
            active: true,
        };
        let text = extract_selection_text(&buf, &sel, &content_map);
        // Should NOT contain border characters (│, ╭, ╮, etc.)
        assert!(!text.contains(''), "Border char │ found in: {text}");
        assert!(!text.contains(''), "Border char ╭ found in: {text}");
        assert!(!text.contains(''), "Border char ╮ found in: {text}");
        // Should contain actual content
        assert!(
            text.contains("Hello Col1"),
            "Missing Col1 content in: {text}"
        );
        assert!(
            text.contains("Hello Col2"),
            "Missing Col2 content in: {text}"
        );
        assert!(text.contains("Line2 Col1"), "Missing Col1 line2 in: {text}");
        assert!(text.contains("Line2 Col2"), "Missing Col2 line2 in: {text}");
    }

    #[test]
    fn apply_selection_overlay_skips_border_cells() {
        let area = Rect::new(0, 0, 20, 3);
        let mut buf = Buffer::empty(area);
        buf.set_string(0, 0, "", Style::default());
        buf.set_string(1, 0, "ABC", Style::default());
        buf.set_string(19, 0, "", Style::default());

        let content_map = vec![(Rect::new(0, 0, 20, 3), Rect::new(1, 0, 18, 3))];
        let sel = SelectionState {
            anchor: Some((0, 0)),
            current: Some((19, 0)),
            widget_rect: Some(area),
            active: true,
        };
        apply_selection_overlay(&mut buf, &sel, &content_map);
        // Border cells at x=0 and x=19 should NOT be reversed
        assert!(
            !buf.get(0, 0).style.modifiers.contains(Modifiers::REVERSED),
            "Left border cell should not be reversed"
        );
        assert!(
            !buf.get(19, 0).style.modifiers.contains(Modifiers::REVERSED),
            "Right border cell should not be reversed"
        );
        // Content cells should be reversed
        assert!(buf.get(1, 0).style.modifiers.contains(Modifiers::REVERSED));
        assert!(buf.get(2, 0).style.modifiers.contains(Modifiers::REVERSED));
        assert!(buf.get(3, 0).style.modifiers.contains(Modifiers::REVERSED));
    }

    #[test]
    fn copy_to_clipboard_writes_osc52() {
        let mut output: Vec<u8> = Vec::new();
        copy_to_clipboard(&mut output, "test").unwrap();
        let s = String::from_utf8(output).unwrap();
        assert!(s.starts_with("\x1b]52;c;"));
        assert!(s.ends_with("\x1b\\"));
        assert!(s.contains(&base64_encode(b"test")));
    }

    // Count occurrences of CSI cursor-move (`ESC [ ... H`) in flush output.
    fn count_move_tos(s: &str) -> usize {
        let bytes = s.as_bytes();
        let mut count = 0;
        let mut i = 0;
        while i + 1 < bytes.len() {
            if bytes[i] == 0x1b && bytes[i + 1] == b'[' {
                // Scan to the terminator — final byte in 0x40..=0x7e.
                let mut j = i + 2;
                while j < bytes.len() && !(0x40..=0x7e).contains(&bytes[j]) {
                    j += 1;
                }
                if j < bytes.len() && bytes[j] == b'H' {
                    count += 1;
                }
                i = j + 1;
            } else {
                i += 1;
            }
        }
        count
    }

    #[test]
    fn flush_coalesces_consecutive_same_style_cells_into_one_run() {
        // 10 cells, identical Style, contiguous columns -> 1 MoveTo + 1 Print.
        let area = Rect::new(0, 0, 20, 1);
        let mut current = Buffer::empty(area);
        let previous = Buffer::empty(area);
        let style = Style::new().fg(Color::Red);
        for x in 0..10u32 {
            let cell = current.get_mut(x, 0);
            cell.set_char('X');
            cell.set_style(style);
        }

        let mut out: Vec<u8> = Vec::new();
        flush_buffer_diff(
            &mut out,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();
        let s = String::from_utf8(out).unwrap();

        // Exactly one cursor move for the whole run.
        assert_eq!(
            count_move_tos(&s),
            1,
            "expected 1 MoveTo for a coalesced run, got {} in {:?}",
            count_move_tos(&s),
            s
        );
        // The 10 glyphs are emitted contiguously as a single run.
        assert!(
            s.contains("XXXXXXXXXX"),
            "expected contiguous run 'XXXXXXXXXX' in {:?}",
            s
        );
    }

    #[test]
    fn flush_breaks_run_on_style_change() {
        // 5 red cells + 5 blue cells in the same row -> 2 MoveTo calls not 10.
        let area = Rect::new(0, 0, 20, 1);
        let mut current = Buffer::empty(area);
        let previous = Buffer::empty(area);
        let red = Style::new().fg(Color::Red);
        let blue = Style::new().fg(Color::Blue);
        for x in 0..5u32 {
            let cell = current.get_mut(x, 0);
            cell.set_char('R');
            cell.set_style(red);
        }
        for x in 5..10u32 {
            let cell = current.get_mut(x, 0);
            cell.set_char('B');
            cell.set_style(blue);
        }

        let mut out: Vec<u8> = Vec::new();
        flush_buffer_diff(
            &mut out,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();
        let s = String::from_utf8(out).unwrap();

        // First run needs a MoveTo; the second run starts exactly where the
        // cursor already is, so `last_cursor` suppresses a redundant MoveTo.
        // Either way, we should see at most 2 MoveTos and far fewer than 10.
        let moves = count_move_tos(&s);
        assert!(
            moves <= 2,
            "expected at most 2 MoveTos across a style boundary, got {} in {:?}",
            moves,
            s
        );
        assert!(s.contains("RRRRR"), "missing 'RRRRR' run in {:?}", s);
        assert!(s.contains("BBBBB"), "missing 'BBBBB' run in {:?}", s);
    }

    #[test]
    fn flush_breaks_run_on_column_gap() {
        // Cells at x=0..3 and x=6..9; gap at x=3,4,5 must split runs.
        let area = Rect::new(0, 0, 20, 1);
        let mut current = Buffer::empty(area);
        let previous = Buffer::empty(area);
        let style = Style::new().fg(Color::Green);
        for x in 0..3u32 {
            current.get_mut(x, 0).set_char('A').set_style(style);
        }
        for x in 6..9u32 {
            current.get_mut(x, 0).set_char('B').set_style(style);
        }

        let mut out: Vec<u8> = Vec::new();
        flush_buffer_diff(
            &mut out,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();
        let s = String::from_utf8(out).unwrap();

        // Two separate runs means two MoveTo commands.
        assert_eq!(
            count_move_tos(&s),
            2,
            "expected 2 MoveTos across a column gap, got {} in {:?}",
            count_move_tos(&s),
            s
        );
        assert!(s.contains("AAA"), "missing 'AAA' run in {:?}", s);
        assert!(s.contains("BBB"), "missing 'BBB' run in {:?}", s);
    }

    /// Verifies that `flush_buffer_diff` produces identical ANSI output whether the
    /// destination is a plain `Vec<u8>` or a `BufWriter<Vec<u8>>`. This ensures the
    /// BufWriter wrapper introduced for stdout does not alter the byte stream.
    #[test]
    fn bufwriter_output_identical_to_direct_write() {
        let area = Rect::new(0, 0, 5, 1);
        let mut current = Buffer::empty(area);
        let previous = Buffer::empty(area);
        let style = Style::new().fg(Color::Rgb(255, 128, 0));
        for x in 0..5u32 {
            current.get_mut(x, 0).set_char('X').set_style(style);
        }

        let mut direct: Vec<u8> = Vec::new();
        flush_buffer_diff(
            &mut direct,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();

        let mut buffered: BufWriter<Vec<u8>> = BufWriter::with_capacity(65536, Vec::new());
        flush_buffer_diff(
            &mut buffered,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();
        buffered.flush().unwrap();
        let via_buf = buffered.into_inner().unwrap();

        assert_eq!(
            direct, via_buf,
            "BufWriter output must be byte-for-byte identical to direct write"
        );
    }

    /// Verifies that a `BufWriter<Vec<u8>>` sink accumulates all writes and only
    /// issues a single underlying `write` call to the inner sink when flushed.
    /// This is a proxy for the syscall-reduction guarantee on the real stdout.
    #[test]
    fn bufwriter_coalesces_writes_into_single_flush() {
        #[derive(Debug)]
        struct CountingWriter {
            buf: Vec<u8>,
            write_call_count: usize,
        }
        impl Write for CountingWriter {
            fn write(&mut self, data: &[u8]) -> io::Result<usize> {
                self.write_call_count += 1;
                self.buf.extend_from_slice(data);
                Ok(data.len())
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        let area = Rect::new(0, 0, 10, 1);
        let mut current = Buffer::empty(area);
        let previous = Buffer::empty(area);
        // Alternate styles on every cell to maximise queue! calls inside flush_buffer_diff.
        for x in 0..10u32 {
            let color = if x % 2 == 0 {
                Color::Rgb(255, 0, 0)
            } else {
                Color::Rgb(0, 255, 0)
            };
            current
                .get_mut(x, 0)
                .set_char('Z')
                .set_style(Style::new().fg(color));
        }

        let sink = CountingWriter {
            buf: Vec::new(),
            write_call_count: 0,
        };
        let mut bw = BufWriter::with_capacity(65536, sink);
        flush_buffer_diff(
            &mut bw,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();
        bw.flush().unwrap();
        let inner = bw.into_inner().unwrap();

        // BufWriter should have batched everything into 1 write call to the sink.
        assert_eq!(
            inner.write_call_count, 1,
            "expected 1 write syscall to sink, got {}",
            inner.write_call_count
        );
    }

    /// Issue #171 regression: identical buffers must produce no flush
    /// output once both have refreshed line hashes. Validates that the
    /// per-row skip path is correctness-preserving — a skipped row
    /// emits zero bytes, exactly like the per-cell path would for an
    /// unchanged row.
    #[test]
    fn flush_skips_unchanged_rows_when_hashes_match() {
        let area = Rect::new(0, 0, 20, 4);
        let mut current = Buffer::empty(area);
        let mut previous = Buffer::empty(area);
        // Populate both buffers with identical content.
        for y in 0..4u32 {
            current.set_string(0, y, "identical-row-content", Style::new());
            previous.set_string(0, y, "identical-row-content", Style::new());
        }
        current.recompute_line_hashes();
        previous.recompute_line_hashes();

        let mut out: Vec<u8> = Vec::new();
        flush_buffer_diff(
            &mut out,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();
        assert!(
            out.is_empty(),
            "identical buffers must emit zero flush bytes; got {} bytes: {:?}",
            out.len(),
            out
        );
    }

    /// Issue #171 regression: when only some rows match, only those rows
    /// are skipped. The differing row must still drive its full per-cell
    /// flush path so the terminal sees the correct glyphs.
    #[test]
    fn flush_skips_only_matching_rows_in_mixed_diff() {
        let area = Rect::new(0, 0, 6, 3);
        let mut current = Buffer::empty(area);
        let mut previous = Buffer::empty(area);
        current.set_string(0, 0, "abcdef", Style::new());
        previous.set_string(0, 0, "abcdef", Style::new());
        current.set_string(0, 1, "xxxxxx", Style::new());
        previous.set_string(0, 1, "yyyyyy", Style::new());
        current.set_string(0, 2, "zzzzzz", Style::new());
        previous.set_string(0, 2, "zzzzzz", Style::new());
        current.recompute_line_hashes();
        previous.recompute_line_hashes();

        let mut out: Vec<u8> = Vec::new();
        flush_buffer_diff(
            &mut out,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();
        let s = String::from_utf8_lossy(&out);
        // The mismatched row's new content must appear; matching rows'
        // glyphs must not (they share content with `previous`).
        assert!(s.contains("xxxxxx"), "differing row must flush: {s:?}");
        assert!(
            !s.contains("abcdef"),
            "matching row 0 must not flush: {s:?}"
        );
        assert!(
            !s.contains("zzzzzz"),
            "matching row 2 must not flush: {s:?}"
        );
    }

    fn delta_bytes(old: &Style, new: &Style) -> Vec<u8> {
        let mut out = Vec::new();
        apply_style_delta(&mut out, old, new, ColorDepth::TrueColor).unwrap();
        out
    }

    fn contains_seq(haystack: &[u8], needle: &[u8]) -> bool {
        haystack.windows(needle.len()).any(|w| w == needle)
    }

    #[test]
    fn apply_style_delta_emits_blink_set_and_reset() {
        let on = delta_bytes(&Style::new(), &Style::new().blink());
        // SGR 5 = SlowBlink.
        assert!(contains_seq(&on, b"\x1b[5m"), "blink set: {on:?}");
        let off = delta_bytes(&Style::new().blink(), &Style::new());
        // SGR 25 = NoBlink.
        assert!(contains_seq(&off, b"\x1b[25m"), "blink reset: {off:?}");
    }

    #[test]
    fn apply_style_delta_emits_overline_set_and_reset() {
        let on = delta_bytes(&Style::new(), &Style::new().overline());
        // SGR 53 = OverLined.
        assert!(contains_seq(&on, b"\x1b[53m"), "overline set: {on:?}");
        let off = delta_bytes(&Style::new().overline(), &Style::new());
        // SGR 55 = NotOverLined.
        assert!(contains_seq(&off, b"\x1b[55m"), "overline reset: {off:?}");
    }

    #[test]
    fn apply_style_delta_emits_curly_underline_subparameter() {
        let out = delta_bytes(
            &Style::new(),
            &Style::new().underline_style(UnderlineStyle::Curly),
        );
        assert!(contains_seq(&out, b"\x1b[4:3m"), "curly underline: {out:?}");
    }

    #[test]
    fn apply_style_delta_emits_underline_color_and_reset() {
        let set = delta_bytes(
            &Style::new(),
            &Style::new().underline_color(Color::Rgb(255, 0, 0)),
        );
        assert!(
            contains_seq(&set, b"\x1b[58:2::255:0:0m"),
            "underline color set: {set:?}"
        );
        let clear = delta_bytes(
            &Style::new().underline_color(Color::Rgb(255, 0, 0)),
            &Style::new(),
        );
        assert!(
            contains_seq(&clear, b"\x1b[59m"),
            "underline color reset: {clear:?}"
        );
    }

    #[test]
    fn apply_style_delta_underline_color_indexed_uses_sgr_58_5() {
        let out = delta_bytes(
            &Style::new(),
            &Style::new().underline_color(Color::Indexed(42)),
        );
        assert!(
            contains_seq(&out, b"\x1b[58:5:42m"),
            "indexed underline: {out:?}"
        );
    }

    #[test]
    fn apply_style_full_emits_blink_overline_and_underline() {
        let mut out = Vec::new();
        let style = Style::new()
            .blink()
            .overline()
            .underline_style(UnderlineStyle::Dotted)
            .underline_color(Color::Rgb(0, 0, 255));
        apply_style(&mut out, &style, ColorDepth::TrueColor).unwrap();
        assert!(contains_seq(&out, b"\x1b[5m"), "blink: {out:?}");
        assert!(contains_seq(&out, b"\x1b[53m"), "overline: {out:?}");
        assert!(
            contains_seq(&out, b"\x1b[4:4m"),
            "dotted underline: {out:?}"
        );
        assert!(
            contains_seq(&out, b"\x1b[58:2::0:0:255m"),
            "underline color: {out:?}"
        );
    }
    /// Issue #274: a captured-sink `Terminal` routes a styled cell through the
    /// real flush pipeline into the in-process byte sink, and dropping it does
    /// not emit teardown escapes (no raw mode was entered).
    #[test]
    fn with_sink_captures_flush_bytes_and_drops_clean() {
        let mut term = Terminal::with_sink(10, 1, ColorDepth::TrueColor);
        term.buffer_mut()
            .set_string(0, 0, "Z", Style::new().fg(Color::Rgb(200, 50, 50)));
        term.flush().unwrap();
        let bytes = term.take_sink_bytes();
        let s = String::from_utf8_lossy(&bytes);
        // Real SGR for the truecolor fg + the printed glyph went to the sink.
        assert!(s.contains("\u{1b}[38;2;200;50;50m"), "missing SGR: {s:?}");
        assert!(s.contains('Z'), "missing glyph: {s:?}");
        // A second take after no flush yields nothing (capture was drained).
        assert!(term.take_sink_bytes().is_empty());
        // Dropping the harness terminal must not panic or emit teardown.
        drop(term);
    }

    /// Issue #269: hoisting `run_buf` to a reused, caller-owned buffer must not
    /// change the emitted bytes. Re-running the diff twice through the *same*
    /// `run_buf` (which `clear()`s but keeps capacity at the top of each call)
    /// produces the same output as a single fresh-buffer run.
    #[test]
    fn reused_run_buf_byte_identical_across_frames() {
        let area = Rect::new(0, 0, 12, 2);
        // `Buffer` is not `Clone`, so rebuild the frame pair on demand.
        let make_frame = || {
            let mut current = Buffer::empty(area);
            let previous = Buffer::empty(area);
            current.set_string(0, 0, "hello world", Style::new().fg(Color::Rgb(1, 2, 3)));
            current.set_string(0, 1, "second line", Style::new().fg(Color::Rgb(4, 5, 6)));
            (current, previous)
        };

        // Baseline: a fresh run_buf per call.
        let mut baseline: Vec<u8> = Vec::new();
        {
            let (mut a, mut b) = make_frame();
            __bench_flush_buffer_diff_mut_with_buf(
                &mut baseline,
                &mut a,
                &mut b,
                ColorDepth::TrueColor,
                &mut String::with_capacity(RUN_BUF_INITIAL_CAPACITY),
            )
            .unwrap();
        }

        // Reuse: run a throwaway frame first, then the real frame through the
        // SAME run_buf (now carrying leftover capacity, freshly cleared).
        let mut shared = String::with_capacity(RUN_BUF_INITIAL_CAPACITY);
        {
            let mut warm: Vec<u8> = Vec::new();
            let (mut a, mut b) = make_frame();
            __bench_flush_buffer_diff_mut_with_buf(
                &mut warm,
                &mut a,
                &mut b,
                ColorDepth::TrueColor,
                &mut shared,
            )
            .unwrap();
        }
        let cap_after_warm = shared.capacity();

        let mut reused: Vec<u8> = Vec::new();
        let (mut current, mut previous) = make_frame();
        __bench_flush_buffer_diff_mut_with_buf(
            &mut reused,
            &mut current,
            &mut previous,
            ColorDepth::TrueColor,
            &mut shared,
        )
        .unwrap();

        assert_eq!(
            baseline, reused,
            "reused run_buf must emit byte-identical output"
        );
        // The reuse path keeps capacity across frames (never re-grows below the
        // initial reservation) — the whole point of the hoist.
        assert!(
            shared.capacity() >= cap_after_warm,
            "run_buf capacity must persist across frames"
        );
    }

    /// Issue #269: the OSC 8 hyperlink open, rewritten from `format!` to three
    /// borrowed `Print`s, must still emit the exact `\x1b]8;;<url>\x07 ...
    /// \x1b]8;;\x07` sequence.
    #[test]
    fn osc8_hyperlink_emitted_verbatim_after_write_rewrite() {
        let area = Rect::new(0, 0, 8, 1);
        let mut current = Buffer::empty(area);
        let previous = Buffer::empty(area);
        let url = "https://example.com/x";
        // `set_string_linked` sanitizes + attaches the hyperlink to each cell.
        current.set_string_linked(0, 0, "link", Style::new(), url);

        let mut out: Vec<u8> = Vec::new();
        flush_buffer_diff(
            &mut out,
            &current,
            &previous,
            ColorDepth::TrueColor,
            0,
            &mut String::new(),
        )
        .unwrap();

        let open = format!("\x1b]8;;{url}\x07");
        assert!(
            contains_seq(&out, open.as_bytes()),
            "OSC 8 open must appear verbatim: {:?}",
            String::from_utf8_lossy(&out)
        );
        assert!(
            contains_seq(&out, b"\x1b]8;;\x07"),
            "OSC 8 close must appear: {:?}",
            String::from_utf8_lossy(&out)
        );
    }

    /// Build `n` distinct 8x8 RGBA placements for kitty-flush golden tests.
    fn kitty_placements(n: usize) -> Vec<KittyPlacement> {
        (0..n)
            .map(|i| {
                let mut rgba = vec![0u8; 256];
                rgba[0] = i as u8;
                let content_hash = crate::buffer::hash_rgba(&rgba);
                KittyPlacement {
                    content_hash,
                    rgba: std::sync::Arc::new(rgba),
                    src_width: 8,
                    src_height: 8,
                    x: (i as u32) * 4,
                    y: (i as u32) * 2,
                    cols: 4,
                    rows: 2,
                    crop_y: 0,
                    crop_h: 0,
                }
            })
            .collect()
    }

    /// Issue #269: replacing the two per-frame `HashSet`s in
    /// `KittyImageManager::flush` with reused `SmallVec` dedup scratch must not
    /// change the emitted escape stream for the small placement counts (0, 1, 5)
    /// the path actually sees. We assert structural invariants of the byte
    /// stream rather than an opaque golden blob so the test documents intent.
    #[test]
    fn kitty_flush_smallvec_dedup_matches_for_small_n() {
        for n in [0usize, 1, 5] {
            let placements = kitty_placements(n);
            let mut mgr = KittyImageManager::new();

            // Frame 1: nothing previously placed → upload + place each image.
            let mut frame1: Vec<u8> = Vec::new();
            mgr.flush(&mut frame1, &placements, 0).unwrap();
            let s1 = String::from_utf8_lossy(&frame1);
            // One transmit (`a=t`) and one placement (`a=p`) per image.
            assert_eq!(
                s1.matches("a=t,").count(),
                n,
                "n={n}: expected {n} uploads in frame 1: {s1:?}"
            );
            assert_eq!(
                s1.matches("a=p,").count(),
                n,
                "n={n}: expected {n} placements in frame 1: {s1:?}"
            );

            // Frame 2: identical placements → fast path, zero output.
            let mut frame2: Vec<u8> = Vec::new();
            mgr.flush(&mut frame2, &placements, 0).unwrap();
            assert!(
                frame2.is_empty(),
                "n={n}: identical frame must hit the kitty fast path, got {} bytes",
                frame2.len()
            );

            // Frame 3: clear all placements → one delete (`a=d,d=i`) per image,
            // deduped by the reused SmallVec, plus image-data cleanup
            // (`a=d,d=I`) for every now-unused upload.
            let mut frame3: Vec<u8> = Vec::new();
            mgr.flush(&mut frame3, &[], 0).unwrap();
            let s3 = String::from_utf8_lossy(&frame3);
            assert_eq!(
                s3.matches("a=d,d=i,").count(),
                n,
                "n={n}: expected {n} placement deletes in frame 3: {s3:?}"
            );
            assert_eq!(
                s3.matches("a=d,d=I,").count(),
                n,
                "n={n}: expected {n} image-data deletes in frame 3: {s3:?}"
            );
        }
    }

    // ---- #265 sprixel damage matrix ----------------------------------------

    use crate::buffer::{SprixelCell, SprixelPlacement};

    /// Build a 2×2-cell sprixel at (1, 1) with the given footprint states.
    fn make_sprixel(cells: Vec<SprixelCell>) -> SprixelPlacement {
        SprixelPlacement {
            content_hash: 0xABCD,
            seq: "<SIXEL>".to_string(),
            x: 1,
            y: 1,
            cols: 2,
            rows: 2,
            cells,
        }
    }

    #[test]
    fn sprixel_no_text_change_emits_zero_bytes() {
        // A frame identical to the previous one must emit no sprixel bytes.
        let area = Rect::new(0, 0, 10, 5);
        let placement = make_sprixel(vec![SprixelCell::Opaque; 4]);

        let mut current = Buffer::empty(area);
        current.sprixels.push(placement.clone());
        let mut previous = Buffer::empty(area);
        previous.sprixels.push(placement);

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        assert!(out.is_empty(), "stable frame should emit no sprixel bytes");
    }

    #[test]
    fn sprixel_first_frame_blits_once() {
        // No previous placement -> the graphic must be emitted exactly once.
        let area = Rect::new(0, 0, 10, 5);
        let mut current = Buffer::empty(area);
        current
            .sprixels
            .push(make_sprixel(vec![SprixelCell::Opaque; 4]));
        let previous = Buffer::empty(area);

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        let s = String::from_utf8(out).unwrap();
        assert_eq!(s.matches("<SIXEL>").count(), 1);
    }

    #[test]
    fn sprixel_text_in_opaque_cell_reblits_once() {
        // A text write over an opaque footprint cell annihilates the graphic.
        let area = Rect::new(0, 0, 10, 5);
        let placement = make_sprixel(vec![SprixelCell::Opaque; 4]);

        let mut current = Buffer::empty(area);
        current.sprixels.push(placement.clone());
        // Write a glyph over the top-left footprint cell (1, 1).
        current.set_char(1, 1, 'X', Style::new());

        let mut previous = Buffer::empty(area);
        previous.sprixels.push(placement);

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        let s = String::from_utf8(out).unwrap();
        assert_eq!(
            s.matches("<SIXEL>").count(),
            1,
            "opaque-cell text write must re-blit the graphic exactly once"
        );
    }

    #[test]
    fn sprixel_text_in_transparent_cell_does_not_reblit() {
        // The footprint marks (1, 1) transparent; a text write there must NOT
        // re-blit the graphic (the core #265 win).
        let area = Rect::new(0, 0, 10, 5);
        let cells = vec![
            SprixelCell::Transparent, // (1, 1)
            SprixelCell::Opaque,      // (2, 1)
            SprixelCell::Opaque,      // (1, 2)
            SprixelCell::Opaque,      // (2, 2)
        ];
        let placement = make_sprixel(cells);

        let mut current = Buffer::empty(area);
        current.sprixels.push(placement.clone());
        current.set_char(1, 1, 'X', Style::new());

        let mut previous = Buffer::empty(area);
        previous.sprixels.push(placement);

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        assert!(
            out.is_empty(),
            "text in a transparent footprint cell must emit zero sprixel bytes"
        );
    }

    #[test]
    fn sprixel_text_outside_footprint_does_not_reblit() {
        // A text write adjacent to (but outside) the footprint is free.
        let area = Rect::new(0, 0, 10, 5);
        let placement = make_sprixel(vec![SprixelCell::Opaque; 4]);

        let mut current = Buffer::empty(area);
        current.sprixels.push(placement.clone());
        // (5, 0) is well outside the (1,1)-(2,2) footprint.
        current.set_char(5, 0, 'Z', Style::new());

        let mut previous = Buffer::empty(area);
        previous.sprixels.push(placement);

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        assert!(
            out.is_empty(),
            "text outside the footprint must not re-blit the graphic"
        );
    }

    #[test]
    fn sprixel_position_change_reblits() {
        // Moving the graphic (same content, new x/y) must re-blit.
        let area = Rect::new(0, 0, 10, 5);
        let mut moved = make_sprixel(vec![SprixelCell::Opaque; 4]);
        let original = moved.clone();
        moved.x = 4;

        let mut current = Buffer::empty(area);
        current.sprixels.push(moved);
        let mut previous = Buffer::empty(area);
        previous.sprixels.push(original);

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        let s = String::from_utf8(out).unwrap();
        assert_eq!(s.matches("<SIXEL>").count(), 1);
    }

    #[test]
    fn sprixel_content_change_reblits() {
        // Same position, different content hash -> re-blit.
        let area = Rect::new(0, 0, 10, 5);
        let mut recolored = make_sprixel(vec![SprixelCell::Opaque; 4]);
        let original = recolored.clone();
        recolored.content_hash = 0x1234;
        recolored.seq = "<SIXEL2>".to_string();

        let mut current = Buffer::empty(area);
        current.sprixels.push(recolored);
        let mut previous = Buffer::empty(area);
        previous.sprixels.push(original);

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        let s = String::from_utf8(out).unwrap();
        assert_eq!(s.matches("<SIXEL2>").count(), 1);
    }

    #[test]
    fn sprixel_reblit_count_invariant_over_single_cell_writes() {
        // Invariant (issue #265 proptest spirit, exhaustive here): for a write
        // to a single footprint cell, the number of re-emitted sprixels is 0
        // iff that cell is Transparent, else 1.
        let area = Rect::new(0, 0, 10, 5);
        for (idx, (col, row)) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1)]
            .into_iter()
            .enumerate()
        {
            for state in [
                SprixelCell::Opaque,
                SprixelCell::Mixed,
                SprixelCell::Transparent,
            ] {
                let mut cells = vec![SprixelCell::Opaque; 4];
                cells[idx] = state;
                let placement = make_sprixel(cells);

                let mut current = Buffer::empty(area);
                current.sprixels.push(placement.clone());
                current.set_char(1 + col, 1 + row, 'A', Style::new());

                let mut previous = Buffer::empty(area);
                previous.sprixels.push(placement);

                let mut out: Vec<u8> = Vec::new();
                flush_sprixels(&mut out, &current, &previous, 0).unwrap();
                let count = String::from_utf8(out).unwrap().matches("<SIXEL>").count();
                let expected = if matches!(state, SprixelCell::Transparent) {
                    0
                } else {
                    1
                };
                assert_eq!(
                    count, expected,
                    "cell ({col},{row}) state {state:?}: expected {expected} re-blits"
                );
            }
        }
    }

    // ---- v0.21.1 sprixel reblit-scan optimization regression ---------------
    //
    // These drive the hashed-key position lookup and the per-row clean+hash
    // shortcut with `recompute_line_hashes` engaged (the real `flush` ordering),
    // proving the optimization preserves the exact #265 re-blit semantics.

    #[test]
    fn sprixel_unchanged_with_hashes_engaged_emits_zero_bytes() {
        // Regression: a steady frame (identical to previous) with per-row
        // digests refreshed must NOT re-blit. This exercises the per-row
        // clean+hash shortcut: every footprint row is clean and hash-matched, so
        // the per-cell scan is skipped and nothing is emitted.
        let area = Rect::new(0, 0, 10, 5);
        let placement = make_sprixel(vec![SprixelCell::Opaque; 4]);

        let mut current = Buffer::empty(area);
        current.sprixels.push(placement.clone());
        let mut previous = Buffer::empty(area);
        previous.sprixels.push(placement);

        // Match `Terminal::flush`: refresh digests before the sprixel pass.
        current.recompute_line_hashes();
        previous.recompute_line_hashes();
        // Sanity: the footprint rows are clean and hash-identical, so the
        // shortcut is the path actually taken.
        assert!(current.row_clean(1) && current.row_clean(2));
        assert_eq!(current.row_hash(1), previous.row_hash(1));

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        assert!(
            out.is_empty(),
            "unchanged sprixel must not be re-blitted (per-row shortcut)"
        );
    }

    #[test]
    fn sprixel_changed_text_with_hashes_engaged_reblits_once() {
        // Regression: a text write over an opaque footprint cell must still
        // re-blit exactly once even with digests refreshed. The touched row is
        // dirty (or hash-mismatched), so the shortcut correctly does NOT skip it
        // and the per-cell annihilation scan fires.
        let area = Rect::new(0, 0, 10, 5);
        let placement = make_sprixel(vec![SprixelCell::Opaque; 4]);

        let mut current = Buffer::empty(area);
        current.sprixels.push(placement.clone());
        current.set_char(1, 1, 'X', Style::new());
        let mut previous = Buffer::empty(area);
        previous.sprixels.push(placement);

        current.recompute_line_hashes();
        previous.recompute_line_hashes();
        // The footprint's top row differs from the previous frame.
        assert_ne!(current.row_hash(1), previous.row_hash(1));

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        let s = String::from_utf8(out).unwrap();
        assert_eq!(
            s.matches("<SIXEL>").count(),
            1,
            "annihilating text write must re-blit exactly once"
        );
    }

    #[test]
    fn sprixel_changed_text_in_transparent_cell_with_hashes_does_not_reblit() {
        // Regression edge case: even though the touched row is dirty/hash-mismatched
        // (so the per-row shortcut does NOT skip it), a write landing only on a
        // Transparent footprint cell must still emit zero bytes — the per-cell
        // damage matrix governs, exactly as in the unoptimized path.
        let area = Rect::new(0, 0, 10, 5);
        let cells = vec![
            SprixelCell::Transparent, // (1, 1)
            SprixelCell::Opaque,      // (2, 1)
            SprixelCell::Opaque,      // (1, 2)
            SprixelCell::Opaque,      // (2, 2)
        ];
        let placement = make_sprixel(cells);

        let mut current = Buffer::empty(area);
        current.sprixels.push(placement.clone());
        current.set_char(1, 1, 'X', Style::new());
        let mut previous = Buffer::empty(area);
        previous.sprixels.push(placement);

        current.recompute_line_hashes();
        previous.recompute_line_hashes();

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        assert!(
            out.is_empty(),
            "transparent-cell text write must not re-blit even with hashes engaged"
        );
    }

    #[test]
    fn sprixel_key_matches_partial_eq_contract() {
        // The hashed identity key must agree with `SprixelPlacement: PartialEq`:
        // equal placements share a key; any field the PartialEq compares
        // produces a distinct key.
        let base = make_sprixel(vec![SprixelCell::Opaque; 4]);
        assert_eq!(sprixel_key(&base), sprixel_key(&base.clone()));

        let mut moved = base.clone();
        moved.x = 7;
        assert_ne!(sprixel_key(&base), sprixel_key(&moved));

        let mut recolored = base.clone();
        recolored.content_hash = 0x9999;
        assert_ne!(sprixel_key(&base), sprixel_key(&recolored));

        // The damage matrix is excluded from both PartialEq and the key.
        let mut annihilated = base.clone();
        annihilated.cells = vec![SprixelCell::Annihilated; 4];
        assert_eq!(sprixel_key(&base), sprixel_key(&annihilated));
        assert_eq!(base, annihilated);
    }

    #[test]
    fn sprixel_multi_placement_only_changed_one_reblits() {
        // With several stacked sprixels, moving one must re-blit only that one;
        // the others (clean, hash-matched) stay silent. Exercises the hash-set
        // position lookup across multiple placements.
        let area = Rect::new(0, 0, 10, 9);
        let mut current = Buffer::empty(area);
        let mut previous = Buffer::empty(area);
        for i in 0..3u32 {
            let p = SprixelPlacement {
                content_hash: 0x100 + i as u64,
                seq: format!("<S{i}>"),
                x: 0,
                y: i * 3,
                cols: 2,
                rows: 2,
                cells: vec![SprixelCell::Opaque; 4],
            };
            current.sprixels.push(p.clone());
            previous.sprixels.push(p);
        }
        // Move only the middle sprixel.
        current.sprixels[1].x = 5;

        current.recompute_line_hashes();
        previous.recompute_line_hashes();

        let mut out: Vec<u8> = Vec::new();
        flush_sprixels(&mut out, &current, &previous, 0).unwrap();
        let s = String::from_utf8(out).unwrap();
        assert_eq!(s.matches("<S0>").count(), 0);
        assert_eq!(
            s.matches("<S1>").count(),
            1,
            "only the moved sprixel reblits"
        );
        assert_eq!(s.matches("<S2>").count(), 0);
    }

    #[test]
    fn bench_sprixel_fixture_steady_state_emits_nothing() {
        // The bench fixture must represent a steady frame (no re-blit) so it
        // measures the no-damage scan cost. Guards against the wrapper silently
        // emitting work.
        let fixture = __bench_new_sprixel_fixture(4);
        assert_eq!(fixture.len(), 4);
        assert!(!fixture.is_empty());
        let mut out: Vec<u8> = Vec::new();
        fixture.flush(&mut out, 0).unwrap();
        assert!(
            out.is_empty(),
            "steady-state bench fixture re-blits nothing"
        );
    }
}