blit-remote 0.32.1

Remote blit protocol, frame state, and callback DOM renderer
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
use std::collections::BTreeMap;

use lz4_flex::{compress_prepend_size, decompress_size_prepended};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

pub const CELL_SIZE: usize = 12;
const TITLE_PRESENT: u16 = 1 << 15;
const OPS_PRESENT: u16 = 1 << 14;
const STRINGS_PRESENT: u16 = 1 << 13;
const LINE_FLAGS_PRESENT: u16 = 1 << 12;
const TITLE_LEN_MASK: u16 = LINE_FLAGS_PRESENT - 1;

/// Per-row flag: this row's content continues on the next row (line wrap).
pub const ROW_FLAG_WRAPPED: u8 = 1 << 0;

/// Sentinel value for content_len indicating the cell's text lives in the
/// overflow string table.  Bytes 8-11 then hold an FNV-1a hash of the full
/// UTF-8 string (for diff correctness), and the actual string is stored in
/// `FrameState::overflow` keyed by cell index.
const CONTENT_OVERFLOW: u8 = 7;

const ENABLE_SCROLL_OPS: bool = true;
const MODE_ECHO: u16 = 1 << 9;
const MODE_ICANON: u16 = 1 << 10;

const OP_COPY_RECT: u8 = 0x01;
const OP_FILL_RECT: u8 = 0x02;
const OP_PATCH_CELLS: u8 = 0x03;

pub const C2S_INPUT: u8 = 0x00;
/// Desired viewport size(s): [0x01][pty_id:2][rows:2][cols:2]...
/// Clients may batch multiple PTY resize entries in one message. The server
/// mediates these per-client desired sizes into each PTY's effective size.
/// A `rows, cols` pair of `0, 0` clears this client's desired size for that PTY.
pub const C2S_RESIZE: u8 = 0x01;
pub const C2S_SCROLL: u8 = 0x02;
pub const C2S_ACK: u8 = 0x03;
pub const C2S_DISPLAY_RATE: u8 = 0x04;
pub const C2S_CLIENT_METRICS: u8 = 0x05;
/// Application-level keepalive: [0x08].  No payload.
/// Sent periodically by the client; the server treats it as a no-op
/// (but its arrival resets any server-side receive timeout).
pub const C2S_PING: u8 = 0x08;
/// Mouse event: [0x06][pty_id:2][type:1][button:1][col:2][row:2]
/// type: 0=down, 1=up, 2=move
/// button: 0=left, 1=mid, 2=right, 3=release, 64=wheel_up, 65=wheel_down
/// The server generates the correct escape sequence based on mouse_mode and mouse_encoding.
pub const C2S_MOUSE: u8 = 0x06;
/// Restart an exited PTY: [0x07][pty_id:2]
/// Server spawns a new shell in the same PTY slot, preserving the pty_id.
pub const C2S_RESTART: u8 = 0x07;
pub const C2S_CREATE: u8 = 0x10;
pub const C2S_FOCUS: u8 = 0x11;
pub const C2S_CLOSE: u8 = 0x12;
pub const C2S_SUBSCRIBE: u8 = 0x13;
pub const C2S_UNSUBSCRIBE: u8 = 0x14;
pub const C2S_SEARCH: u8 = 0x15;
pub const C2S_CREATE_AT: u8 = 0x16;
pub const C2S_CREATE_N: u8 = 0x17;
/// Generic create: [0x18][nonce:2][rows:2][cols:2][features:1][tag_len:2][tag:N][...optional fields]
/// Features: bit 0 = has src_pty_id (2 bytes after tag), bit 1 = has command (remaining bytes after src_pty_id if present)
/// Server responds with S2C_CREATED_N using the same nonce.
pub const C2S_CREATE2: u8 = 0x18;
pub const CREATE2_HAS_SRC_PTY: u8 = 1 << 0;
pub const CREATE2_HAS_COMMAND: u8 = 1 << 1;
/// Read text from a PTY's scrollback + viewport: [0x19][nonce:2][pty_id:2][offset:4][limit:4][flags:1]
/// offset: number of lines to skip from the top (oldest = 0), or from the end if READ_TAIL is set
/// limit: max lines to return (0 = all)
/// flags: bit 0 = include ANSI styling, bit 1 = offset counts from the end
/// Server responds with S2C_TEXT using the same nonce.
pub const C2S_READ: u8 = 0x19;
pub const READ_ANSI: u8 = 1 << 0;
pub const READ_TAIL: u8 = 1 << 1;
/// Copy text from a range of absolute row/col positions in scrollback + viewport:
/// [0x1B][nonce:2][pty_id:2][start_tail:4][start_col:2][end_tail:4][end_col:2][flags:1]
/// start_tail/end_tail: physical row distance from the bottom (0 = last row).
/// start is the earlier position (closer to top), so start_tail >= end_tail.
/// flags: reserved (0 for now).
/// Server responds with S2C_TEXT using the same nonce.
pub const C2S_COPY_RANGE: u8 = 0x1B;
/// Send a signal to a PTY's session leader: [0x1A][pty_id:2][signal:4]
/// signal is a raw libc signal number (e.g. SIGTERM=15, SIGKILL=9).
pub const C2S_KILL: u8 = 0x1A;

/// Keyboard input for a Wayland surface: [0x20][surface_id:2][data:N]
/// data contains evdev keycodes encoded as [keycode:4][pressed:1] sequences.
pub const C2S_SURFACE_INPUT: u8 = 0x20;
/// Pointer motion/button for a Wayland surface: [0x21][surface_id:2][type:1][button:1][x:2][y:2]
/// type: 0=down, 1=up, 2=move
/// x,y: pixel coordinates relative to the surface origin
pub const C2S_SURFACE_POINTER: u8 = 0x21;
/// Pointer axis/scroll for a Wayland surface: [0x22][surface_id:2][axis:1][value_x100:4_signed]
/// axis: 0=vertical, 1=horizontal
/// value_x100: scroll amount * 100 (signed, positive = down/right)
pub const C2S_SURFACE_POINTER_AXIS: u8 = 0x22;
/// Resize a Wayland surface: [0x23][surface_id:2][width:2][height:2][scale_120:2]
/// scale_120: device pixel ratio in 1/120th units (120 = 1×, 240 = 2×).
pub const C2S_SURFACE_RESIZE: u8 = 0x23;
/// Set keyboard/pointer focus to a Wayland surface: [0x24][surface_id:2]
pub const C2S_SURFACE_FOCUS: u8 = 0x24;
/// Set clipboard content:
/// [0x25][mime_len:2][mime:N][data_len:4][data:N]
pub const C2S_CLIPBOARD_SET: u8 = 0x25;
/// Request a list of all compositor surfaces: [0x26]
pub const C2S_SURFACE_LIST: u8 = 0x26;
/// Request a screenshot of a surface:
/// [0x27][surface_id:2]              — legacy (defaults to PNG lossless)
/// [0x27][surface_id:2][format:1][quality:1] — extended
/// format: 0 = PNG, 1 = AVIF.  quality: 0 = lossless, 1–100 = lossy (AVIF only).
pub const C2S_SURFACE_CAPTURE: u8 = 0x27;
pub const CAPTURE_FORMAT_PNG: u8 = 0;
pub const CAPTURE_FORMAT_AVIF: u8 = 1;
/// Subscribe to surface frame updates:
/// [0x28][surface_id:2]                                        — legacy (server defaults)
/// [0x28][surface_id:2][codec:1][quality:1]                    — extended
/// [0x28][surface_id:2][codec:1][quality:1][width:2][height:2] — scaled
///
/// codec: CODEC_SUPPORT_* bitmask restricting which codecs the server may use
///        for this surface.  0 = use connection-level default (from C2S_CLIENT_FEATURES).
///
/// quality: desired compression quality for this surface.
///   0 = server default, 1 = low, 2 = medium, 3 = high, 4 = ultra.
///   10–255 = custom AV1 quantizer (wire value IS the quantizer).
///   See `SURFACE_QUALITY_*` constants.
///
/// width, height: optional fixed target size (in pixels) for this subscription.
///   When both are nonzero, the server encodes this surface at exactly
///   `width × height` for this client by scaling the native frame down
///   server-side, independent of the compositor's surface size.  Such
///   "scaled" subscriptions are excluded from the server's surface-size
///   mediation (they never pull the compositor surface smaller for other
///   viewers).  Both 0 (or fields absent) means the client participates in
///   mediation via C2S_SURFACE_RESIZE like today.
///
/// Re-subscribing to an already-subscribed surface updates the codec/quality
/// preferences and/or scaled size and forces encoder recreation.
pub const C2S_SURFACE_SUBSCRIBE: u8 = 0x28;

/// Quality values for the `quality` byte in C2S_SURFACE_SUBSCRIBE.
/// 0 means "use server default" (from BLIT_SURFACE_QUALITY env var).
pub const SURFACE_QUALITY_DEFAULT: u8 = 0;
pub const SURFACE_QUALITY_LOW: u8 = 1;
pub const SURFACE_QUALITY_MEDIUM: u8 = 2;
pub const SURFACE_QUALITY_HIGH: u8 = 3;
pub const SURFACE_QUALITY_ULTRA: u8 = 4;
/// Unsubscribe from surface frame updates: [0x29][surface_id:2]
pub const C2S_SURFACE_UNSUBSCRIBE: u8 = 0x29;
/// Acknowledge receipt of a surface video frame: [0x2A]
pub const C2S_SURFACE_ACK: u8 = 0x2A;
/// Request close of a Wayland surface (sends xdg_toplevel close event):
/// [0x2B][surface_id:2]
pub const C2S_SURFACE_CLOSE: u8 = 0x2B;
/// Request a list of MIME types available on the clipboard: [0x2C]
/// Server responds with S2C_CLIPBOARD_LIST.
pub const C2S_CLIPBOARD_LIST: u8 = 0x2C;
/// Client feature/capability advertisement: [0x2D][payload:N]
/// Currently defined payload bytes:
///   [0] codec_support — bitmask of CODEC_SUPPORT_* flags the client can
///       decode.  0 = accept anything (legacy).
/// Sent once after connection when capability probing completes.  The
/// message is extensible: the server ignores trailing bytes it doesn't
/// understand, and missing bytes default to 0.
pub const C2S_CLIENT_FEATURES: u8 = 0x2D;
/// Composed text input for a Wayland surface (UTF-8):
/// [0x2F][surface_id:2][text:N]
/// The server synthesises the corresponding evdev key sequences (US-QWERTY)
/// for ASCII characters.  Non-ASCII characters are delivered via
/// zwp_text_input_v3 commit_string when available.
pub const C2S_SURFACE_TEXT: u8 = 0x2F;
/// Read clipboard content for a specific MIME type:
/// [0x2E][mime_len:2][mime:N]
/// Server responds with S2C_CLIPBOARD_CONTENT (0x25) containing the data.
pub const C2S_CLIPBOARD_GET: u8 = 0x2E;
/// Request server shutdown: [0x0F].  No payload.
/// The server broadcasts S2C_QUIT to all connected clients and exits.
pub const C2S_QUIT: u8 = 0x0F;

pub const S2C_UPDATE: u8 = 0x00;
pub const S2C_CREATED: u8 = 0x01;
pub const S2C_CLOSED: u8 = 0x02;
pub const S2C_LIST: u8 = 0x03;
pub const S2C_TITLE: u8 = 0x04;
pub const S2C_SEARCH_RESULTS: u8 = 0x05;
pub const S2C_CREATED_N: u8 = 0x06;
pub const S2C_HELLO: u8 = 0x07;
/// The PTY's subprocess has exited but the terminal state is retained.
/// Clients can still read/scroll the last frame. Send C2S_CLOSE to dismiss.
/// Wire: [0x08][pty_id:2][exit_status:4]
/// exit_status: WEXITSTATUS if normal exit, negative signal number if signalled,
///              EXIT_STATUS_UNKNOWN if not yet collected.
pub const S2C_EXITED: u8 = 0x08;
pub const EXIT_STATUS_UNKNOWN: i32 = i32::MIN;
/// Sent after the initial burst (HELLO, LIST, TITLE*, EXITED*) is complete.
/// Clients can use this to know when the initial state has been fully transmitted.
pub const S2C_READY: u8 = 0x09;
/// Application-level keepalive: [0x0B].  No payload.
/// Sent periodically by the server so clients can detect dead connections
/// even when no other traffic is flowing (e.g. idle terminal, WebRTC).
pub const S2C_PING: u8 = 0x0B;
/// Server is shutting down: [0x0C].  No payload.
/// Broadcast to all connected clients before the server exits.
pub const S2C_QUIT: u8 = 0x0C;
/// Text response: [0x0A][nonce:2][pty_id:2][total_lines:4][offset:4][text:N]
/// nonce: echoed from C2S_READ request
/// total_lines: total available lines (scrollback + viewport rows)
/// offset: the offset that was requested
/// text: UTF-8 text, lines separated by \n
pub const S2C_TEXT: u8 = 0x0A;

/// A new Wayland toplevel surface was created:
/// [0x20][surface_id:2][parent_id:2][width:2][height:2][title_len:2][title:N][app_id_len:2][app_id:N]
/// parent_id: 0 = no parent (top-level), non-zero = dialog/child of that surface
pub const S2C_SURFACE_CREATED: u8 = 0x20;
/// A Wayland surface was destroyed: [0x21][surface_id:2]
pub const S2C_SURFACE_DESTROYED: u8 = 0x21;
/// An encoded video frame for a Wayland surface:
/// [0x22][surface_id:2][timestamp:4][flags:1][width:2][height:2][data:N]
/// flags: bit 0 = keyframe, bits 1-2 = codec (0 = H.264, 1 = AV1).
/// timestamp: milliseconds since compositor session start.
pub const S2C_SURFACE_FRAME: u8 = 0x22;
/// A Wayland surface's title changed: [0x23][surface_id:2][title:N]
pub const S2C_SURFACE_TITLE: u8 = 0x23;
/// A Wayland surface was resized by the app: [0x24][surface_id:2][width:2][height:2]
pub const S2C_SURFACE_RESIZED: u8 = 0x24;
/// A Wayland surface's app_id changed: [0x28][surface_id:2][app_id:N]
pub const S2C_SURFACE_APP_ID: u8 = 0x28;
/// Clipboard content (response to C2S_CLIPBOARD_GET or unsolicited broadcast on change):
/// [0x25][mime_len:2][mime:N][data_len:4][data:N]
pub const S2C_CLIPBOARD_CONTENT: u8 = 0x25;
/// List of all compositor surfaces:
/// [0x26][count:2] repeated{ [surface_id:2][parent_id:2][width:2][height:2][title_len:2][title:N][app_id_len:2][app_id:N] }
pub const S2C_SURFACE_LIST: u8 = 0x26;
/// Screenshot of a surface: [0x27][surface_id:2][width:4][height:4][image_data:N]
/// image_data is PNG or AVIF depending on the request format.
/// If the surface was not found or has no buffer, width=0 and height=0 with empty data.
pub const S2C_SURFACE_CAPTURE: u8 = 0x27;

/// Cursor shape changed for a surface: [0x29][surface_id:2][shape_len:1][shape:N]
/// shape is a CSS cursor keyword (e.g. "default", "pointer", "text").
pub const S2C_SURFACE_CURSOR: u8 = 0x29;

/// Encoder backend for a surface: [0x2A][surface_id:2][name:N]
/// name is a short ASCII string like "h264-nvenc", "h264-vaapi", "h264-software", etc.
/// Sent when a new encoder is created for a surface (initial subscribe or resize).
pub const S2C_SURFACE_ENCODER: u8 = 0x2A;

/// List of MIME types available on the clipboard:
/// [0x2C][count:2] repeated{ [mime_len:2][mime:N] }
pub const S2C_CLIPBOARD_LIST: u8 = 0x2C;

// -- Audio forwarding ---------------------------------------------------

/// Subscribe to audio: [0x30][bitrate_kbps:2]
/// Audio is per-compositor (one mixed stream), not per-surface.
/// The server begins sending S2C_AUDIO_FRAME.
/// bitrate_kbps: 0 = server default.
pub const C2S_AUDIO_SUBSCRIBE: u8 = 0x30;
/// Unsubscribe from audio: [0x31]
pub const C2S_AUDIO_UNSUBSCRIBE: u8 = 0x31;
/// An encoded audio frame (Opus) from the compositor's mixed output:
/// [0x30][timestamp:4][flags:1][data:N]
/// timestamp: sample offset in 48 kHz ticks from an arbitrary epoch.
/// flags: bits 1-2 = codec (0 = Opus). Other bits reserved.
pub const S2C_AUDIO_FRAME: u8 = 0x30;

pub const AUDIO_FRAME_CODEC_MASK: u8 = 0b110;
pub const AUDIO_FRAME_CODEC_OPUS: u8 = 0 << 1;

/// A fragment of a larger S2C message: [0x2B][flags:1][chunk:N]
///
/// Large bulk messages (video keyframes, terminal snapshots) are split
/// into multiple fragments so audio frames can be written between them
/// on the same stream.  Without this the writer task would hold the
/// socket for the full duration of a multi-hundred-KB write, starving
/// audio delivery and producing audible gaps on the client.
///
/// Flags:
///   bit 0 (FRAGMENT_FLAG_LAST) — this is the last fragment; the receiver
///     should concatenate all fragments of this message (in order) and
///     dispatch the reassembled buffer as if it were a single message.
///
/// Fragments of different messages do NOT interleave: TCP preserves
/// order and the server only splits one message at a time, so the
/// receiver can use a single pending-reassembly buffer with no fragment
/// id or sequence number.  S2C_AUDIO_FRAME messages may appear between
/// fragments and are handled normally — they don't contribute to the
/// reassembly buffer.
pub const S2C_FRAGMENT: u8 = 0x2B;
pub const FRAGMENT_FLAG_LAST: u8 = 1 << 0;

pub const SURFACE_FRAME_FLAG_KEYFRAME: u8 = 1 << 0;
pub const SURFACE_FRAME_CODEC_MASK: u8 = 0b110;
pub const SURFACE_FRAME_CODEC_H264: u8 = 0 << 1;
pub const SURFACE_FRAME_CODEC_AV1: u8 = 1 << 1;
pub const SURFACE_FRAME_CODEC_PNG: u8 = 2 << 1;

/// Bitmask for client-supported codecs in C2S_CLIENT_FEATURES and
/// C2S_SURFACE_SUBSCRIBE.  0 means "accept anything".
pub const CODEC_SUPPORT_H264: u8 = 1 << 0;
pub const CODEC_SUPPORT_AV1: u8 = 1 << 1;
pub const CODEC_SUPPORT_H264_444: u8 = 1 << 2;
pub const CODEC_SUPPORT_AV1_444: u8 = 1 << 3;

pub const FEATURE_CREATE_NONCE: u32 = 1 << 0;
pub const FEATURE_RESTART: u32 = 1 << 1;
pub const FEATURE_RESIZE_BATCH: u32 = 1 << 2;
pub const FEATURE_COPY_RANGE: u32 = 1 << 3;
pub const FEATURE_COMPOSITOR: u32 = 1 << 4;
pub const FEATURE_AUDIO: u32 = 1 << 5;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Color {
    #[default]
    Default,
    Indexed(u8),
    Rgb(u8, u8, u8),
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CellStyle {
    pub fg: Color,
    pub bg: Color,
    pub bold: bool,
    pub dim: bool,
    pub italic: bool,
    pub underline: bool,
    pub inverse: bool,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rect {
    pub row: u16,
    pub col: u16,
    pub rows: u16,
    pub cols: u16,
}

impl Rect {
    pub const fn new(row: u16, col: u16, rows: u16, cols: u16) -> Self {
        Self {
            row,
            col,
            rows,
            cols,
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FrameState {
    rows: u16,
    cols: u16,
    cells: Vec<u8>,
    cursor_row: u16,
    cursor_col: u16,
    mode: u16,
    title: String,
    /// Overflow strings for cells whose content exceeds 4 bytes.
    /// Keyed by flat cell index (row * cols + col).
    overflow: BTreeMap<usize, String>,
    /// Per-row flags. `ROW_FLAG_WRAPPED` means the row continues on the next.
    line_flags: Vec<u8>,
    /// Total scrollback lines available for this PTY.
    scrollback_lines: u32,
}

impl FrameState {
    pub fn new(rows: u16, cols: u16) -> Self {
        let total = rows as usize * cols as usize;
        Self {
            rows,
            cols,
            cells: vec![0; total * CELL_SIZE],
            cursor_row: 0,
            cursor_col: 0,
            mode: 0,
            title: String::new(),
            overflow: BTreeMap::new(),
            line_flags: vec![0; rows as usize],
            scrollback_lines: 0,
        }
    }

    pub fn from_parts(
        rows: u16,
        cols: u16,
        cursor_row: u16,
        cursor_col: u16,
        mode: u16,
        title: impl Into<String>,
        cells: Vec<u8>,
    ) -> Self {
        let mut state = Self::new(rows, cols);
        if cells.len() == state.cells.len() {
            state.cells = cells;
        }
        state.cursor_row = cursor_row;
        state.cursor_col = cursor_col;
        state.mode = mode;
        state.title = title.into();
        state
    }

    pub fn rows(&self) -> u16 {
        self.rows
    }

    pub fn cols(&self) -> u16 {
        self.cols
    }

    pub fn cursor_row(&self) -> u16 {
        self.cursor_row
    }

    pub fn cursor_col(&self) -> u16 {
        self.cursor_col
    }

    pub fn mode(&self) -> u16 {
        self.mode
    }

    pub fn title(&self) -> &str {
        &self.title
    }

    pub fn cells(&self) -> &[u8] {
        &self.cells
    }

    pub fn cells_mut(&mut self) -> &mut [u8] {
        &mut self.cells
    }

    pub fn overflow(&self) -> &BTreeMap<usize, String> {
        &self.overflow
    }

    pub fn overflow_mut(&mut self) -> &mut BTreeMap<usize, String> {
        &mut self.overflow
    }

    pub fn line_flags(&self) -> &[u8] {
        &self.line_flags
    }

    pub fn line_flags_mut(&mut self) -> &mut Vec<u8> {
        &mut self.line_flags
    }

    pub fn scrollback_lines(&self) -> u32 {
        self.scrollback_lines
    }

    pub fn set_scrollback_lines(&mut self, lines: u32) {
        self.scrollback_lines = lines;
    }

    pub fn is_wrapped(&self, row: u16) -> bool {
        self.line_flags.get(row as usize).copied().unwrap_or(0) & ROW_FLAG_WRAPPED != 0
    }

    pub fn set_wrapped(&mut self, row: u16, wrapped: bool) {
        if let Some(flags) = self.line_flags.get_mut(row as usize) {
            if wrapped {
                *flags |= ROW_FLAG_WRAPPED;
            } else {
                *flags &= !ROW_FLAG_WRAPPED;
            }
        }
    }

    /// Returns the text content of a cell, resolving overflow if needed.
    pub fn cell_content(&self, row: u16, col: u16) -> &str {
        if row >= self.rows || col >= self.cols {
            return "";
        }
        let flat = row as usize * self.cols as usize + col as usize;
        let idx = flat * CELL_SIZE;
        let f1 = self.cells[idx + 1];
        if f1 & 4 != 0 {
            return ""; // wide continuation
        }
        let content_len = ((f1 >> 3) & 7) as usize;
        if content_len == CONTENT_OVERFLOW as usize {
            if let Some(s) = self.overflow.get(&flat) {
                return s.as_str();
            }
            return "";
        }
        if content_len == 0 {
            return " ";
        }
        std::str::from_utf8(&self.cells[idx + 8..idx + 8 + content_len]).unwrap_or(" ")
    }

    pub fn resize(&mut self, rows: u16, cols: u16) {
        if rows == self.rows && cols == self.cols {
            return;
        }
        self.rows = rows;
        self.cols = cols;
        self.cells = vec![0; rows as usize * cols as usize * CELL_SIZE];
        self.overflow.clear();
        self.line_flags = vec![0; rows as usize];
        self.cursor_row = self.cursor_row.min(rows.saturating_sub(1));
        self.cursor_col = self.cursor_col.min(cols.saturating_sub(1));
    }

    pub fn set_cursor(&mut self, row: u16, col: u16) {
        self.cursor_row = row.min(self.rows.saturating_sub(1));
        self.cursor_col = col.min(self.cols.saturating_sub(1));
    }

    pub fn set_mode(&mut self, mode: u16) {
        self.mode = mode;
    }

    pub fn set_title(&mut self, title: impl Into<String>) -> bool {
        let title = title.into();
        if self.title == title {
            return false;
        }
        self.title = title;
        true
    }

    pub fn clear(&mut self, style: CellStyle) {
        for row in 0..self.rows {
            for col in 0..self.cols {
                self.set_blank_cell(row, col, style);
            }
        }
    }

    pub fn fill_rect(&mut self, rect: Rect, ch: char, style: CellStyle) {
        let row_end = rect.row.saturating_add(rect.rows).min(self.rows);
        let col_end = rect.col.saturating_add(rect.cols).min(self.cols);
        for row in rect.row..row_end {
            let mut col = rect.col;
            while col < col_end {
                let width = self.set_cell(row, col, ch, style);
                if width == 0 {
                    break;
                }
                col = col.saturating_add(width);
            }
        }
    }

    pub fn write_text(&mut self, row: u16, col: u16, text: &str, style: CellStyle) -> u16 {
        if row >= self.rows || col >= self.cols {
            return col;
        }
        let mut cur_col = col;
        for ch in text.chars() {
            if cur_col >= self.cols {
                break;
            }
            let width = self.set_cell(row, cur_col, ch, style);
            if width == 0 {
                continue;
            }
            cur_col = cur_col.saturating_add(width);
        }
        cur_col
    }

    pub fn write_wrapped_text(&mut self, rect: Rect, text: &str, style: CellStyle) -> usize {
        if rect.rows == 0 || rect.cols == 0 {
            return 0;
        }
        let lines = wrap_text_lines(text, rect.cols as usize);
        let max_rows = rect.rows.min(self.rows.saturating_sub(rect.row));
        for (idx, line) in lines.iter().take(max_rows as usize).enumerate() {
            let row = rect.row + idx as u16;
            self.write_text(row, rect.col, line, style);
        }
        lines.len()
    }

    pub fn write_scrolling_text<S: AsRef<str>>(
        &mut self,
        rect: Rect,
        lines: &[S],
        offset_from_bottom: usize,
        style: CellStyle,
    ) {
        if rect.rows == 0 || rect.cols == 0 {
            return;
        }
        let mut wrapped = Vec::with_capacity(lines.len());
        for line in lines {
            let line = line.as_ref();
            let out = wrap_text_lines(line, rect.cols as usize);
            if out.is_empty() {
                wrapped.push(String::new());
            } else {
                wrapped.extend(out);
            }
        }
        let visible = rect.rows as usize;
        let end = wrapped.len().saturating_sub(offset_from_bottom);
        let start = end.saturating_sub(visible);
        for row in 0..rect.rows {
            self.fill_rect(
                Rect::new(rect.row + row, rect.col, 1, rect.cols),
                ' ',
                style,
            );
        }
        for (idx, line) in wrapped[start..end].iter().enumerate() {
            self.write_text(rect.row + idx as u16, rect.col, line, style);
        }
    }

    pub fn get_text(&self, start_row: u16, start_col: u16, end_row: u16, end_col: u16) -> String {
        let mut result = String::new();
        if self.rows == 0 || self.cols == 0 {
            return result;
        }
        for row in start_row..=end_row.min(self.rows.saturating_sub(1)) {
            let c0 = if row == start_row { start_col } else { 0 };
            let c1 = if row == end_row {
                end_col
            } else {
                self.cols - 1
            };
            let mut line = String::new();
            let mut col = c0;
            while col <= c1.min(self.cols - 1) {
                line.push_str(self.cell_content(row, col));
                col += 1;
            }
            result.push_str(line.trim_end());
            if row < end_row.min(self.rows.saturating_sub(1)) && !self.is_wrapped(row) {
                result.push('\n');
            }
        }
        result
    }

    pub fn get_all_text(&self) -> String {
        if self.rows == 0 || self.cols == 0 {
            return String::new();
        }
        self.get_text(0, 0, self.rows - 1, self.cols - 1)
    }

    fn cell_style(&self, row: u16, col: u16) -> CellStyle {
        if row >= self.rows || col >= self.cols {
            return CellStyle::default();
        }
        let idx = self.cell_offset(row, col);
        let f0 = self.cells[idx];
        let f1 = self.cells[idx + 1];
        let fg_type = f0 & 3;
        let bg_type = (f0 >> 2) & 3;
        let fg = match fg_type {
            1 => Color::Indexed(self.cells[idx + 2]),
            2 => Color::Rgb(
                self.cells[idx + 2],
                self.cells[idx + 3],
                self.cells[idx + 4],
            ),
            _ => Color::Default,
        };
        let bg = match bg_type {
            1 => Color::Indexed(self.cells[idx + 5]),
            2 => Color::Rgb(
                self.cells[idx + 5],
                self.cells[idx + 6],
                self.cells[idx + 7],
            ),
            _ => Color::Default,
        };
        CellStyle {
            fg,
            bg,
            bold: (f0 >> 4) & 1 != 0,
            dim: (f0 >> 5) & 1 != 0,
            italic: (f0 >> 6) & 1 != 0,
            underline: (f0 >> 7) & 1 != 0,
            inverse: f1 & 1 != 0,
        }
    }

    pub fn get_ansi_text(&self) -> String {
        if self.rows == 0 || self.cols == 0 {
            return String::new();
        }
        let mut result = String::new();
        let mut cur_style = CellStyle::default();
        for row in 0..self.rows {
            let mut line = String::new();
            let mut col = 0u16;
            while col < self.cols {
                let style = self.cell_style(row, col);
                if style != cur_style {
                    push_sgr(&mut line, &style);
                    cur_style = style;
                }
                line.push_str(self.cell_content(row, col));
                col += 1;
            }
            let trimmed = line.trim_end();
            result.push_str(trimmed);
            if cur_style != CellStyle::default() {
                result.push_str("\x1b[0m");
                cur_style = CellStyle::default();
            }
            if row < self.rows - 1 {
                result.push('\n');
            }
        }
        result
    }

    pub fn get_cell(&self, row: u16, col: u16) -> Vec<u8> {
        if row >= self.rows || col >= self.cols {
            return Vec::new();
        }
        let idx = self.cell_offset(row, col);
        self.cells[idx..idx + CELL_SIZE].to_vec()
    }

    fn cell_offset(&self, row: u16, col: u16) -> usize {
        (row as usize * self.cols as usize + col as usize) * CELL_SIZE
    }

    fn set_cell(&mut self, row: u16, col: u16, ch: char, style: CellStyle) -> u16 {
        if row >= self.rows || col >= self.cols {
            return 0;
        }
        let raw_width = UnicodeWidthChar::width(ch).unwrap_or(0);
        if raw_width == 0 {
            return 0;
        }
        let width = if raw_width > 1 && col + 1 < self.cols {
            2
        } else {
            1
        };
        let idx = self.cell_offset(row, col);
        encode_cell(
            &mut self.cells[idx..idx + CELL_SIZE],
            Some(ch),
            style,
            width == 2,
            false,
        );
        if width == 2 {
            let cont_idx = self.cell_offset(row, col + 1);
            encode_cell(
                &mut self.cells[cont_idx..cont_idx + CELL_SIZE],
                None,
                style,
                false,
                true,
            );
        }
        width
    }

    fn set_blank_cell(&mut self, row: u16, col: u16, style: CellStyle) {
        if row >= self.rows || col >= self.cols {
            return;
        }
        let idx = self.cell_offset(row, col);
        encode_cell(
            &mut self.cells[idx..idx + CELL_SIZE],
            None,
            style,
            false,
            false,
        );
    }
}

#[derive(Clone, Debug)]
pub struct TerminalState {
    frame: FrameState,
}

impl TerminalState {
    pub fn new(rows: u16, cols: u16) -> Self {
        let frame = FrameState::new(rows, cols);
        Self { frame }
    }

    pub fn frame(&self) -> &FrameState {
        &self.frame
    }

    pub fn frame_mut(&mut self) -> &mut FrameState {
        &mut self.frame
    }

    pub fn title(&self) -> &str {
        self.frame.title()
    }

    pub fn rows(&self) -> u16 {
        self.frame.rows()
    }

    pub fn cols(&self) -> u16 {
        self.frame.cols()
    }

    pub fn is_wrapped(&self, row: u16) -> bool {
        self.frame.is_wrapped(row)
    }

    pub fn cursor_row(&self) -> u16 {
        self.frame.cursor_row()
    }

    pub fn cursor_col(&self) -> u16 {
        self.frame.cursor_col()
    }

    pub fn mode(&self) -> u16 {
        self.frame.mode()
    }

    pub fn cells(&self) -> &[u8] {
        self.frame.cells()
    }

    pub fn set_title(&mut self, title: &str) -> bool {
        self.frame.set_title(title.to_owned())
    }

    pub fn get_text(&self, start_row: u16, start_col: u16, end_row: u16, end_col: u16) -> String {
        self.frame.get_text(start_row, start_col, end_row, end_col)
    }

    pub fn get_all_text(&self) -> String {
        self.frame.get_all_text()
    }

    pub fn get_ansi_text(&self) -> String {
        self.frame.get_ansi_text()
    }

    pub fn get_cell(&self, row: u16, col: u16) -> Vec<u8> {
        self.frame.get_cell(row, col)
    }

    /// Maximum decompressed frame size (50 MiB). Prevents LZ4 decompression
    /// bombs where a tiny compressed payload claims a multi-GiB output size.
    const MAX_DECOMPRESSED_SIZE: usize = 50 * 1024 * 1024;

    /// Read the LZ4 prepended uncompressed size without allocating, and reject
    /// payloads that claim to decompress beyond `MAX_DECOMPRESSED_SIZE`.
    fn safe_decompress(data: &[u8]) -> Result<Vec<u8>, ()> {
        if data.len() < 4 {
            return Err(());
        }
        let claimed = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
        if claimed > Self::MAX_DECOMPRESSED_SIZE {
            return Err(());
        }
        decompress_size_prepended(data).map_err(|_| ())
    }

    pub fn feed_compressed(&mut self, data: &[u8]) -> bool {
        let payload = match Self::safe_decompress(data) {
            Ok(d) => d,
            Err(_) => return false,
        };
        self.apply_payload(&payload)
    }

    pub fn feed_compressed_batch(&mut self, batch: &[u8]) -> bool {
        let mut changed = false;
        let mut off = 0usize;
        while off + 4 <= batch.len() {
            let len =
                u32::from_le_bytes([batch[off], batch[off + 1], batch[off + 2], batch[off + 3]])
                    as usize;
            off += 4;
            if len == 0 {
                break;
            }
            if off + len > batch.len() {
                break;
            }
            if let Ok(payload) = Self::safe_decompress(&batch[off..off + len]) {
                changed |= self.apply_payload(&payload);
            }
            off += len;
        }
        changed
    }

    /// Maximum total cell count allowed in a single frame (rows * cols).
    /// 500 rows x 1000 cols = 500,000 cells x 12 bytes = 6 MB — generous for
    /// any real terminal while preventing 48 GiB allocations from malicious
    /// frames claiming rows=65535, cols=65535.
    const MAX_CELL_COUNT: usize = 500_000;

    fn apply_payload(&mut self, payload: &[u8]) -> bool {
        if payload.len() < 12 {
            return false;
        }

        let new_rows = u16::from_le_bytes([payload[0], payload[1]]);
        let new_cols = u16::from_le_bytes([payload[2], payload[3]]);

        // Reject absurd dimensions that would cause multi-GiB allocations.
        if (new_rows as usize) * (new_cols as usize) > Self::MAX_CELL_COUNT {
            return false;
        }
        let new_cursor_row = u16::from_le_bytes([payload[4], payload[5]]);
        let new_cursor_col = u16::from_le_bytes([payload[6], payload[7]]);
        let new_mode = u16::from_le_bytes([payload[8], payload[9]]);
        let title_field = u16::from_le_bytes([payload[10], payload[11]]);
        let title_present = title_field & TITLE_PRESENT != 0;
        let ops_present = title_field & OPS_PRESENT != 0;
        let strings_present = title_field & STRINGS_PRESENT != 0;
        let line_flags_present = title_field & LINE_FLAGS_PRESENT != 0;
        let title_len = (title_field & TITLE_LEN_MASK) as usize;

        let title_start = 12usize;
        let title_end = title_start.saturating_add(title_len);
        if payload.len() < title_end {
            return false;
        }
        let title_changed = if title_present {
            let title = String::from_utf8_lossy(&payload[title_start..title_end]).into_owned();
            self.frame.set_title(title)
        } else {
            false
        };

        let resized = new_rows != self.frame.rows || new_cols != self.frame.cols;
        if resized {
            self.frame.resize(new_rows, new_cols);
        }

        let old_cursor_row = self.frame.cursor_row;
        let old_cursor_col = self.frame.cursor_col;
        let old_mode = self.frame.mode;

        let (content_changed, ops_end) = if ops_present {
            let ops_start = title_end;
            if payload.len() < ops_start + 2 {
                return false;
            }
            let (changed, consumed) = self
                .apply_ops_payload(&payload[ops_start..])
                .unwrap_or((false, 0));
            (changed, ops_start + consumed)
        } else {
            let (changed, consumed) = self
                .apply_legacy_patch_payload(&payload[title_end..])
                .unwrap_or((false, 0));
            (changed, title_end + consumed)
        };

        let mut after_strings = ops_end;
        if strings_present {
            after_strings = self.apply_overflow_strings(&payload[ops_end..]);
            after_strings += ops_end;
        }

        let (line_flags_changed, after_line_flags) = if line_flags_present {
            let lf_start = after_strings;
            let lf_end = lf_start + new_rows as usize;
            if payload.len() >= lf_end {
                let new_flags = &payload[lf_start..lf_end];
                let changed = self.frame.line_flags != new_flags;
                self.frame.line_flags.clear();
                self.frame.line_flags.extend_from_slice(new_flags);
                (changed, lf_end)
            } else {
                (false, after_strings)
            }
        } else {
            (false, after_strings)
        };

        // Trailing scrollback count (backward-compatible extension).
        if payload.len() >= after_line_flags + 4 {
            self.frame.scrollback_lines = u32::from_le_bytes([
                payload[after_line_flags],
                payload[after_line_flags + 1],
                payload[after_line_flags + 2],
                payload[after_line_flags + 3],
            ]);
        }

        self.frame.cursor_row = new_cursor_row.min(self.frame.rows.saturating_sub(1));
        self.frame.cursor_col = new_cursor_col.min(self.frame.cols.saturating_sub(1));
        self.frame.mode = new_mode;
        resized
            || title_changed
            || content_changed
            || line_flags_changed
            || new_cursor_row != old_cursor_row
            || new_cursor_col != old_cursor_col
            || new_mode != old_mode
    }

    fn apply_legacy_patch_payload(&mut self, payload: &[u8]) -> Option<(bool, usize)> {
        let total_cells = self.frame.rows as usize * self.frame.cols as usize;
        let bitmask_len = total_cells.div_ceil(8);
        if payload.len() < bitmask_len {
            return None;
        }
        let bitmask = &payload[..bitmask_len];
        let dirty_count = (0..total_cells)
            .filter(|&i| bitmask[i / 8] & (1 << (i % 8)) != 0)
            .count();
        let data = &payload[bitmask_len..];
        if data.len() < dirty_count * CELL_SIZE {
            return None;
        }
        self.apply_patch_cells(bitmask, &data[..dirty_count * CELL_SIZE], dirty_count);
        Some((dirty_count > 0, bitmask_len + dirty_count * CELL_SIZE))
    }

    fn apply_ops_payload(&mut self, payload: &[u8]) -> Option<(bool, usize)> {
        if payload.len() < 2 {
            return None;
        }
        let op_count = u16::from_le_bytes([payload[0], payload[1]]) as usize;
        let total_cells = self.frame.rows as usize * self.frame.cols as usize;
        let bitmask_len = total_cells.div_ceil(8);
        let mut off = 2usize;
        let mut changed = false;

        for _ in 0..op_count {
            if off >= payload.len() {
                return None;
            }
            let op = payload[off];
            off += 1;
            match op {
                OP_COPY_RECT => {
                    if payload.len() < off + 12 {
                        return None;
                    }
                    let src_row = u16::from_le_bytes([payload[off], payload[off + 1]]);
                    let src_col = u16::from_le_bytes([payload[off + 2], payload[off + 3]]);
                    let dst_row = u16::from_le_bytes([payload[off + 4], payload[off + 5]]);
                    let dst_col = u16::from_le_bytes([payload[off + 6], payload[off + 7]]);
                    let rows = u16::from_le_bytes([payload[off + 8], payload[off + 9]]);
                    let cols = u16::from_le_bytes([payload[off + 10], payload[off + 11]]);
                    off += 12;
                    changed |= self.apply_copy_rect(src_row, src_col, dst_row, dst_col, rows, cols);
                }
                OP_FILL_RECT => {
                    if payload.len() < off + 8 + CELL_SIZE {
                        return None;
                    }
                    let row = u16::from_le_bytes([payload[off], payload[off + 1]]);
                    let col = u16::from_le_bytes([payload[off + 2], payload[off + 3]]);
                    let rows = u16::from_le_bytes([payload[off + 4], payload[off + 5]]);
                    let cols = u16::from_le_bytes([payload[off + 6], payload[off + 7]]);
                    off += 8;
                    let mut cell = [0u8; CELL_SIZE];
                    cell.copy_from_slice(&payload[off..off + CELL_SIZE]);
                    off += CELL_SIZE;
                    changed |= self.apply_fill_rect(row, col, rows, cols, &cell);
                }
                OP_PATCH_CELLS => {
                    if payload.len() < off + bitmask_len {
                        return None;
                    }
                    let bitmask = &payload[off..off + bitmask_len];
                    off += bitmask_len;
                    let dirty_count = (0..total_cells)
                        .filter(|&i| bitmask[i / 8] & (1 << (i % 8)) != 0)
                        .count();
                    if payload.len() < off + dirty_count * CELL_SIZE {
                        return None;
                    }
                    self.apply_patch_cells(
                        bitmask,
                        &payload[off..off + dirty_count * CELL_SIZE],
                        dirty_count,
                    );
                    off += dirty_count * CELL_SIZE;
                    changed |= dirty_count > 0;
                }
                _ => return None,
            }
        }

        Some((changed, off))
    }

    fn apply_patch_cells(&mut self, bitmask: &[u8], data: &[u8], dirty_count: usize) {
        let total_cells = self.frame.rows as usize * self.frame.cols as usize;
        let mut dirty_idx = 0usize;
        for i in 0..total_cells {
            if bitmask[i / 8] & (1 << (i % 8)) == 0 {
                continue;
            }
            let cell_idx = i * CELL_SIZE;
            for byte_pos in 0..CELL_SIZE {
                self.frame.cells[cell_idx + byte_pos] = data[byte_pos * dirty_count + dirty_idx];
            }
            // Remove stale overflow entry when a cell is updated — it may
            // have transitioned from overflow (content_len=7) to inline.
            let new_content_len = (self.frame.cells[cell_idx + 1] >> 3) & 7;
            if new_content_len != CONTENT_OVERFLOW {
                self.frame.overflow.remove(&i);
            }
            dirty_idx += 1;
        }
    }

    fn apply_copy_rect(
        &mut self,
        src_row: u16,
        src_col: u16,
        dst_row: u16,
        dst_col: u16,
        rows: u16,
        cols: u16,
    ) -> bool {
        let rows = rows
            .min(self.frame.rows.saturating_sub(src_row))
            .min(self.frame.rows.saturating_sub(dst_row));
        let cols = cols
            .min(self.frame.cols.saturating_sub(src_col))
            .min(self.frame.cols.saturating_sub(dst_col));
        if rows == 0 || cols == 0 {
            return false;
        }

        let frame_cols = self.frame.cols as usize;

        // Copy overflow strings for the source region.
        let mut overflow_temp: Vec<(usize, String)> = Vec::new();
        for r in 0..rows as usize {
            for c in 0..cols as usize {
                let src_flat = (src_row as usize + r) * frame_cols + src_col as usize + c;
                if let Some(s) = self.frame.overflow.get(&src_flat) {
                    let dst_flat = (dst_row as usize + r) * frame_cols + dst_col as usize + c;
                    overflow_temp.push((dst_flat, s.clone()));
                }
            }
        }

        let mut temp = vec![0u8; rows as usize * cols as usize * CELL_SIZE];
        for r in 0..rows as usize {
            let src_off = self.frame.cell_offset(src_row + r as u16, src_col);
            let src_end = src_off + cols as usize * CELL_SIZE;
            let dst_off = r * cols as usize * CELL_SIZE;
            temp[dst_off..dst_off + cols as usize * CELL_SIZE]
                .copy_from_slice(&self.frame.cells[src_off..src_end]);
        }
        for r in 0..rows as usize {
            let dst_off = self.frame.cell_offset(dst_row + r as u16, dst_col);
            let dst_end = dst_off + cols as usize * CELL_SIZE;
            let src_off = r * cols as usize * CELL_SIZE;
            self.frame.cells[dst_off..dst_end]
                .copy_from_slice(&temp[src_off..src_off + cols as usize * CELL_SIZE]);
        }

        for r in 0..rows as usize {
            for c in 0..cols as usize {
                let dst_flat = (dst_row as usize + r) * frame_cols + dst_col as usize + c;
                self.frame.overflow.remove(&dst_flat);
            }
        }
        for (idx, s) in overflow_temp {
            self.frame.overflow.insert(idx, s);
        }

        true
    }

    fn apply_fill_rect(
        &mut self,
        row: u16,
        col: u16,
        rows: u16,
        cols: u16,
        cell: &[u8; CELL_SIZE],
    ) -> bool {
        let row_end = row.saturating_add(rows).min(self.frame.rows);
        let col_end = col.saturating_add(cols).min(self.frame.cols);
        // Fill cells never have overflow content — clear stale entries.
        let frame_cols = self.frame.cols as usize;
        for r in row..row_end {
            for c in col..col_end {
                self.frame
                    .overflow
                    .remove(&(r as usize * frame_cols + c as usize));
            }
        }
        if row >= row_end || col >= col_end {
            return false;
        }
        for r in row..row_end {
            for c in col..col_end {
                let off = self.frame.cell_offset(r, c);
                self.frame.cells[off..off + CELL_SIZE].copy_from_slice(cell);
            }
        }
        true
    }

    fn apply_overflow_strings(&mut self, data: &[u8]) -> usize {
        if data.len() < 2 {
            return 0;
        }
        let count = u16::from_le_bytes([data[0], data[1]]) as usize;
        let mut off = 2usize;
        for _ in 0..count {
            if off + 6 > data.len() {
                break;
            }
            let cell_idx =
                u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]])
                    as usize;
            let len = u16::from_le_bytes([data[off + 4], data[off + 5]]) as usize;
            off += 6;
            if off + len > data.len() {
                break;
            }
            if let Ok(s) = std::str::from_utf8(&data[off..off + len]) {
                // Only accept indices within the current grid to prevent
                // unbounded BTreeMap growth from malicious wire data.
                let max_idx = self.frame.rows as usize * self.frame.cols as usize;
                if cell_idx < max_idx {
                    self.frame.overflow.insert(cell_idx, s.to_owned());
                }
            }
            off += len;
        }
        off
    }
}

#[derive(Clone, Debug)]
pub enum Node {
    Fill {
        rect: Rect,
        ch: char,
        style: CellStyle,
    },
    Text {
        row: u16,
        col: u16,
        text: String,
        style: CellStyle,
    },
    WrappedText {
        rect: Rect,
        text: String,
        style: CellStyle,
    },
    ScrollingText {
        rect: Rect,
        lines: Vec<String>,
        offset_from_bottom: usize,
        style: CellStyle,
    },
}

#[derive(Clone, Debug, Default)]
pub struct Dom {
    background: CellStyle,
    title: Option<String>,
    nodes: Vec<Node>,
}

impl Dom {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn clear(&mut self) {
        self.title = None;
        self.nodes.clear();
    }

    pub fn set_background(&mut self, style: CellStyle) {
        self.background = style;
    }

    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = Some(title.into());
    }

    pub fn fill(&mut self, rect: Rect, ch: char, style: CellStyle) {
        self.nodes.push(Node::Fill { rect, ch, style });
    }

    pub fn text(&mut self, row: u16, col: u16, text: impl Into<String>, style: CellStyle) {
        self.nodes.push(Node::Text {
            row,
            col,
            text: text.into(),
            style,
        });
    }

    pub fn wrapped_text(&mut self, rect: Rect, text: impl Into<String>, style: CellStyle) {
        self.nodes.push(Node::WrappedText {
            rect,
            text: text.into(),
            style,
        });
    }

    pub fn scrolling_text<S, I>(
        &mut self,
        rect: Rect,
        lines: I,
        offset_from_bottom: usize,
        style: CellStyle,
    ) where
        S: Into<String>,
        I: IntoIterator<Item = S>,
    {
        self.nodes.push(Node::ScrollingText {
            rect,
            lines: lines.into_iter().map(Into::into).collect(),
            offset_from_bottom,
            style,
        });
    }

    pub fn render_to(&self, frame: &mut FrameState) {
        frame.clear(self.background);
        frame.set_title(self.title.clone().unwrap_or_default());
        for node in &self.nodes {
            match node {
                Node::Fill { rect, ch, style } => frame.fill_rect(*rect, *ch, *style),
                Node::Text {
                    row,
                    col,
                    text,
                    style,
                } => {
                    frame.write_text(*row, *col, text, *style);
                }
                Node::WrappedText { rect, text, style } => {
                    frame.write_wrapped_text(*rect, text, *style);
                }
                Node::ScrollingText {
                    rect,
                    lines,
                    offset_from_bottom,
                    style,
                } => {
                    frame.write_scrolling_text(*rect, lines, *offset_from_bottom, *style);
                }
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct CallbackRenderer {
    dom: Dom,
    frame: FrameState,
}

impl CallbackRenderer {
    pub fn new(rows: u16, cols: u16) -> Self {
        Self {
            dom: Dom::new(),
            frame: FrameState::new(rows, cols),
        }
    }

    pub fn resize(&mut self, rows: u16, cols: u16) {
        self.frame.resize(rows, cols);
    }

    pub fn frame(&self) -> &FrameState {
        &self.frame
    }

    pub fn render<F>(&mut self, render: F) -> &FrameState
    where
        F: FnOnce(&mut Dom),
    {
        self.dom.clear();
        render(&mut self.dom);
        self.dom.render_to(&mut self.frame);
        &self.frame
    }
}

pub enum ServerMsg<'a> {
    Hello {
        version: u16,
        features: u32,
    },
    Update {
        pty_id: u16,
        payload: &'a [u8],
    },
    Created {
        pty_id: u16,
        tag: &'a str,
    },
    CreatedN {
        nonce: u16,
        pty_id: u16,
        tag: &'a str,
    },
    Closed {
        pty_id: u16,
    },
    Exited {
        pty_id: u16,
        exit_status: i32,
    },
    List {
        entries: Vec<PtyListEntry<'a>>,
    },
    Title {
        pty_id: u16,
        title: &'a [u8],
    },
    SearchResults {
        request_id: u16,
        results: Vec<SearchResultEntry<'a>>,
    },
    Ready,
    Text {
        nonce: u16,
        pty_id: u16,
        total_lines: u32,
        offset: u32,
        text: &'a str,
    },
    SurfaceCreated {
        surface_id: u16,
        parent_id: u16,
        width: u16,
        height: u16,
        title: &'a str,
        app_id: &'a str,
    },
    SurfaceDestroyed {
        surface_id: u16,
    },
    SurfaceFrame {
        surface_id: u16,
        timestamp: u32,
        flags: u8,
        width: u16,
        height: u16,
        data: &'a [u8],
    },
    SurfaceTitle {
        surface_id: u16,
        title: &'a str,
    },
    SurfaceAppId {
        surface_id: u16,
        app_id: &'a str,
    },
    SurfaceResized {
        surface_id: u16,
        width: u16,
        height: u16,
    },
    ClipboardContent {
        mime_type: &'a str,
        data: &'a [u8],
    },
    SurfaceList {
        entries: Vec<SurfaceListEntry>,
    },
    SurfaceCapture {
        surface_id: u16,
        width: u32,
        height: u32,
        image_data: &'a [u8],
    },
    ClipboardList {
        mime_types: Vec<String>,
    },
    Quit,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PtyListEntry<'a> {
    pub pty_id: u16,
    pub tag: &'a str,
    pub command: &'a str,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SurfaceListEntry {
    pub surface_id: u16,
    pub parent_id: u16,
    pub width: u16,
    pub height: u16,
    pub title: String,
    pub app_id: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SearchResultEntry<'a> {
    pub pty_id: u16,
    pub score: u32,
    pub primary_source: u8,
    pub matched_sources: u8,
    pub scroll_offset: Option<u32>,
    pub context: &'a [u8],
}

pub fn parse_server_msg(data: &[u8]) -> Option<ServerMsg<'_>> {
    if data.is_empty() {
        return None;
    }
    match data[0] {
        S2C_HELLO => {
            if data.len() < 7 {
                return None;
            }
            let version = u16::from_le_bytes([data[1], data[2]]);
            let features = u32::from_le_bytes([data[3], data[4], data[5], data[6]]);
            Some(ServerMsg::Hello { version, features })
        }
        S2C_UPDATE => {
            if data.len() < 3 {
                return None;
            }
            Some(ServerMsg::Update {
                pty_id: u16::from_le_bytes([data[1], data[2]]),
                payload: &data[3..],
            })
        }
        S2C_CREATED => {
            if data.len() < 3 {
                return None;
            }
            let tag = std::str::from_utf8(data.get(3..).unwrap_or_default()).unwrap_or_default();
            Some(ServerMsg::Created {
                pty_id: u16::from_le_bytes([data[1], data[2]]),
                tag,
            })
        }
        S2C_CREATED_N => {
            if data.len() < 5 {
                return None;
            }
            let nonce = u16::from_le_bytes([data[1], data[2]]);
            let pty_id = u16::from_le_bytes([data[3], data[4]]);
            let tag = std::str::from_utf8(data.get(5..).unwrap_or_default()).unwrap_or_default();
            Some(ServerMsg::CreatedN { nonce, pty_id, tag })
        }
        S2C_CLOSED => {
            if data.len() < 3 {
                return None;
            }
            Some(ServerMsg::Closed {
                pty_id: u16::from_le_bytes([data[1], data[2]]),
            })
        }
        S2C_EXITED => {
            if data.len() < 7 {
                return None;
            }
            Some(ServerMsg::Exited {
                pty_id: u16::from_le_bytes([data[1], data[2]]),
                exit_status: i32::from_le_bytes([data[3], data[4], data[5], data[6]]),
            })
        }
        S2C_LIST => {
            if data.len() < 3 {
                return None;
            }
            let count = u16::from_le_bytes([data[1], data[2]]) as usize;
            let mut entries = Vec::with_capacity(count);
            let mut offset = 3;
            for _ in 0..count {
                if offset + 4 > data.len() {
                    break;
                }
                let pty_id = u16::from_le_bytes([data[offset], data[offset + 1]]);
                let tag_len = u16::from_le_bytes([data[offset + 2], data[offset + 3]]) as usize;
                offset += 4;
                if offset + tag_len > data.len() {
                    break;
                }
                let tag = std::str::from_utf8(&data[offset..offset + tag_len]).unwrap_or_default();
                offset += tag_len;
                let command = if offset + 2 <= data.len() {
                    let cmd_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
                    offset += 2;
                    if offset + cmd_len <= data.len() {
                        let cmd = std::str::from_utf8(&data[offset..offset + cmd_len])
                            .unwrap_or_default();
                        offset += cmd_len;
                        cmd
                    } else {
                        // Truncated command — don't advance offset past
                        // available data; stop parsing this entry.
                        offset = data.len();
                        ""
                    }
                } else {
                    ""
                };
                entries.push(PtyListEntry {
                    pty_id,
                    tag,
                    command,
                });
            }
            Some(ServerMsg::List { entries })
        }
        S2C_TITLE => {
            if data.len() < 3 {
                return None;
            }
            Some(ServerMsg::Title {
                pty_id: u16::from_le_bytes([data[1], data[2]]),
                title: &data[3..],
            })
        }
        S2C_SEARCH_RESULTS => {
            if data.len() < 5 {
                return None;
            }
            let request_id = u16::from_le_bytes([data[1], data[2]]);
            let count = u16::from_le_bytes([data[3], data[4]]) as usize;
            let mut results = Vec::with_capacity(count);
            let mut offset = 5usize;
            for _ in 0..count {
                if offset + 14 > data.len() {
                    return None;
                }
                let pty_id = u16::from_le_bytes([data[offset], data[offset + 1]]);
                let score = u32::from_le_bytes([
                    data[offset + 2],
                    data[offset + 3],
                    data[offset + 4],
                    data[offset + 5],
                ]);
                let primary_source = data[offset + 6];
                let matched_sources = data[offset + 7];
                let scroll_offset = u32::from_le_bytes([
                    data[offset + 8],
                    data[offset + 9],
                    data[offset + 10],
                    data[offset + 11],
                ]);
                let context_len =
                    u16::from_le_bytes([data[offset + 12], data[offset + 13]]) as usize;
                offset += 14;
                if offset + context_len > data.len() {
                    return None;
                }
                results.push(SearchResultEntry {
                    pty_id,
                    score,
                    primary_source,
                    matched_sources,
                    scroll_offset: if scroll_offset == u32::MAX {
                        None
                    } else {
                        Some(scroll_offset)
                    },
                    context: &data[offset..offset + context_len],
                });
                offset += context_len;
            }
            Some(ServerMsg::SearchResults {
                request_id,
                results,
            })
        }
        S2C_READY => Some(ServerMsg::Ready),
        S2C_TEXT => {
            if data.len() < 13 {
                return None;
            }
            let nonce = u16::from_le_bytes([data[1], data[2]]);
            let pty_id = u16::from_le_bytes([data[3], data[4]]);
            let total_lines = u32::from_le_bytes([data[5], data[6], data[7], data[8]]);
            let offset = u32::from_le_bytes([data[9], data[10], data[11], data[12]]);
            let text = std::str::from_utf8(data.get(13..).unwrap_or_default()).unwrap_or_default();
            Some(ServerMsg::Text {
                nonce,
                pty_id,
                total_lines,
                offset,
                text,
            })
        }
        S2C_SURFACE_CREATED => {
            if data.len() < 13 {
                return None;
            }
            let surface_id = u16::from_le_bytes([data[1], data[2]]);
            let parent_id = u16::from_le_bytes([data[3], data[4]]);
            let width = u16::from_le_bytes([data[5], data[6]]);
            let height = u16::from_le_bytes([data[7], data[8]]);
            let title_len = u16::from_le_bytes([data[9], data[10]]) as usize;
            let mut off = 11;
            if off + title_len + 2 > data.len() {
                return None;
            }
            let title = std::str::from_utf8(&data[off..off + title_len]).unwrap_or_default();
            off += title_len;
            let app_id_len = u16::from_le_bytes([data[off], data[off + 1]]) as usize;
            off += 2;
            if off + app_id_len > data.len() {
                return None;
            }
            let app_id = std::str::from_utf8(&data[off..off + app_id_len]).unwrap_or_default();
            Some(ServerMsg::SurfaceCreated {
                surface_id,
                parent_id,
                width,
                height,
                title,
                app_id,
            })
        }
        S2C_SURFACE_DESTROYED => {
            if data.len() < 3 {
                return None;
            }
            Some(ServerMsg::SurfaceDestroyed {
                surface_id: u16::from_le_bytes([data[1], data[2]]),
            })
        }
        S2C_SURFACE_FRAME => {
            if data.len() < 12 {
                return None;
            }
            Some(ServerMsg::SurfaceFrame {
                surface_id: u16::from_le_bytes([data[1], data[2]]),
                timestamp: u32::from_le_bytes([data[3], data[4], data[5], data[6]]),
                flags: data[7],
                width: u16::from_le_bytes([data[8], data[9]]),
                height: u16::from_le_bytes([data[10], data[11]]),
                data: data.get(12..).unwrap_or_default(),
            })
        }
        S2C_SURFACE_TITLE => {
            if data.len() < 3 {
                return None;
            }
            let title = std::str::from_utf8(data.get(3..).unwrap_or_default()).unwrap_or_default();
            Some(ServerMsg::SurfaceTitle {
                surface_id: u16::from_le_bytes([data[1], data[2]]),
                title,
            })
        }
        S2C_SURFACE_APP_ID => {
            if data.len() < 3 {
                return None;
            }
            let app_id = std::str::from_utf8(data.get(3..).unwrap_or_default()).unwrap_or_default();
            Some(ServerMsg::SurfaceAppId {
                surface_id: u16::from_le_bytes([data[1], data[2]]),
                app_id,
            })
        }
        S2C_SURFACE_RESIZED => {
            if data.len() < 7 {
                return None;
            }
            Some(ServerMsg::SurfaceResized {
                surface_id: u16::from_le_bytes([data[1], data[2]]),
                width: u16::from_le_bytes([data[3], data[4]]),
                height: u16::from_le_bytes([data[5], data[6]]),
            })
        }
        S2C_CLIPBOARD_CONTENT => {
            if data.len() < 7 {
                return None;
            }
            let mime_len = u16::from_le_bytes([data[1], data[2]]) as usize;
            let mut off = 3;
            if off + mime_len + 4 > data.len() {
                return None;
            }
            let mime_type = std::str::from_utf8(&data[off..off + mime_len]).unwrap_or_default();
            off += mime_len;
            let data_len =
                u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]])
                    as usize;
            off += 4;
            if off + data_len > data.len() {
                return None;
            }
            Some(ServerMsg::ClipboardContent {
                mime_type,
                data: &data[off..off + data_len],
            })
        }
        S2C_SURFACE_LIST => {
            if data.len() < 3 {
                return None;
            }
            let count = u16::from_le_bytes([data[1], data[2]]) as usize;
            let mut entries = Vec::with_capacity(count);
            let mut offset = 3;
            for _ in 0..count {
                if offset + 8 > data.len() {
                    break;
                }
                let surface_id = u16::from_le_bytes([data[offset], data[offset + 1]]);
                let parent_id = u16::from_le_bytes([data[offset + 2], data[offset + 3]]);
                let width = u16::from_le_bytes([data[offset + 4], data[offset + 5]]);
                let height = u16::from_le_bytes([data[offset + 6], data[offset + 7]]);
                offset += 8;
                if offset + 2 > data.len() {
                    break;
                }
                let title_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
                offset += 2;
                if offset + title_len > data.len() {
                    break;
                }
                let title =
                    std::str::from_utf8(&data[offset..offset + title_len]).unwrap_or_default();
                offset += title_len;
                if offset + 2 > data.len() {
                    break;
                }
                let app_id_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
                offset += 2;
                if offset + app_id_len > data.len() {
                    break;
                }
                let app_id =
                    std::str::from_utf8(&data[offset..offset + app_id_len]).unwrap_or_default();
                offset += app_id_len;
                entries.push(SurfaceListEntry {
                    surface_id,
                    parent_id,
                    width,
                    height,
                    title: title.to_string(),
                    app_id: app_id.to_string(),
                });
            }
            Some(ServerMsg::SurfaceList { entries })
        }
        S2C_SURFACE_CAPTURE => {
            if data.len() < 11 {
                return None;
            }
            let surface_id = u16::from_le_bytes([data[1], data[2]]);
            let width = u32::from_le_bytes([data[3], data[4], data[5], data[6]]);
            let height = u32::from_le_bytes([data[7], data[8], data[9], data[10]]);
            let image_data = data.get(11..).unwrap_or_default();
            Some(ServerMsg::SurfaceCapture {
                surface_id,
                width,
                height,
                image_data,
            })
        }
        S2C_CLIPBOARD_LIST => {
            if data.len() < 3 {
                return None;
            }
            let count = u16::from_le_bytes([data[1], data[2]]) as usize;
            let mut mime_types = Vec::with_capacity(count);
            let mut offset = 3;
            for _ in 0..count {
                if offset + 2 > data.len() {
                    break;
                }
                let mime_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
                offset += 2;
                if offset + mime_len > data.len() {
                    break;
                }
                let mime =
                    std::str::from_utf8(&data[offset..offset + mime_len]).unwrap_or_default();
                mime_types.push(mime.to_string());
                offset += mime_len;
            }
            Some(ServerMsg::ClipboardList { mime_types })
        }
        S2C_QUIT => Some(ServerMsg::Quit),
        _ => None,
    }
}

pub fn msg_hello(version: u16, features: u32) -> Vec<u8> {
    let mut msg = Vec::with_capacity(7);
    msg.push(S2C_HELLO);
    msg.extend_from_slice(&version.to_le_bytes());
    msg.extend_from_slice(&features.to_le_bytes());
    msg
}

pub fn msg_create(rows: u16, cols: u16) -> Vec<u8> {
    msg_create_tagged(rows, cols, "")
}

pub fn msg_create_tagged(rows: u16, cols: u16, tag: &str) -> Vec<u8> {
    let tag_bytes = tag.as_bytes();
    let tag_len = tag_bytes.len().min(u16::MAX as usize);
    let mut msg = Vec::with_capacity(7 + tag_len);
    msg.push(C2S_CREATE);
    msg.extend_from_slice(&rows.to_le_bytes());
    msg.extend_from_slice(&cols.to_le_bytes());
    msg.extend_from_slice(&(tag_len as u16).to_le_bytes());
    msg.extend_from_slice(&tag_bytes[..tag_len]);
    msg
}

/// Spawn a new PTY in the same working directory as `src_pty_id`.
pub fn msg_create_at(rows: u16, cols: u16, tag: &str, src_pty_id: u16) -> Vec<u8> {
    let tag_bytes = tag.as_bytes();
    let tag_len = tag_bytes.len().min(u16::MAX as usize);
    let mut msg = Vec::with_capacity(9 + tag_len);
    msg.push(C2S_CREATE_AT);
    msg.extend_from_slice(&rows.to_le_bytes());
    msg.extend_from_slice(&cols.to_le_bytes());
    msg.extend_from_slice(&(tag_len as u16).to_le_bytes());
    msg.extend_from_slice(&tag_bytes[..tag_len]);
    msg.extend_from_slice(&src_pty_id.to_le_bytes());
    msg
}

pub fn msg_create_n(nonce: u16, rows: u16, cols: u16, tag: &str) -> Vec<u8> {
    let tag_bytes = tag.as_bytes();
    let tag_len = tag_bytes.len().min(u16::MAX as usize);
    let mut msg = Vec::with_capacity(9 + tag_len);
    msg.push(C2S_CREATE_N);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.extend_from_slice(&rows.to_le_bytes());
    msg.extend_from_slice(&cols.to_le_bytes());
    msg.extend_from_slice(&(tag_len as u16).to_le_bytes());
    msg.extend_from_slice(&tag_bytes[..tag_len]);
    msg
}

pub fn msg_create_n_command(nonce: u16, rows: u16, cols: u16, tag: &str, command: &str) -> Vec<u8> {
    let mut msg = msg_create_n(nonce, rows, cols, tag);
    msg.extend_from_slice(command.as_bytes());
    msg
}

pub fn msg_create2(
    nonce: u16,
    rows: u16,
    cols: u16,
    tag: &str,
    command: &str,
    features: u8,
) -> Vec<u8> {
    let tag_bytes = tag.as_bytes();
    let cmd_bytes = command.as_bytes();
    let has_cmd = !command.is_empty();
    let feat = features | if has_cmd { CREATE2_HAS_COMMAND } else { 0 };
    let mut msg = Vec::with_capacity(10 + tag_bytes.len() + cmd_bytes.len());
    msg.push(C2S_CREATE2);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.extend_from_slice(&rows.to_le_bytes());
    msg.extend_from_slice(&cols.to_le_bytes());
    msg.push(feat);
    msg.extend_from_slice(&(tag_bytes.len() as u16).to_le_bytes());
    msg.extend_from_slice(tag_bytes);
    if has_cmd {
        msg.extend_from_slice(cmd_bytes);
    }
    msg
}

pub fn msg_create_command(rows: u16, cols: u16, command: &str) -> Vec<u8> {
    msg_create_tagged_command(rows, cols, "", command)
}

pub fn msg_create_tagged_command(rows: u16, cols: u16, tag: &str, command: &str) -> Vec<u8> {
    let mut msg = msg_create_tagged(rows, cols, tag);
    msg.extend_from_slice(command.as_bytes());
    msg
}

pub fn msg_input(pty_id: u16, data: &[u8]) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3 + data.len());
    msg.push(C2S_INPUT);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(data);
    msg
}

pub fn msg_mouse(pty_id: u16, type_: u8, button: u8, col: u16, row: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(9);
    msg.push(C2S_MOUSE);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.push(type_);
    msg.push(button);
    msg.extend_from_slice(&col.to_le_bytes());
    msg.extend_from_slice(&row.to_le_bytes());
    msg
}

pub fn msg_resize(pty_id: u16, rows: u16, cols: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(7);
    msg.push(C2S_RESIZE);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(&rows.to_le_bytes());
    msg.extend_from_slice(&cols.to_le_bytes());
    msg
}

pub fn msg_resize_batch(entries: &[(u16, u16, u16)]) -> Vec<u8> {
    let mut msg = Vec::with_capacity(1 + entries.len() * 6);
    msg.push(C2S_RESIZE);
    for &(pty_id, rows, cols) in entries {
        msg.extend_from_slice(&pty_id.to_le_bytes());
        msg.extend_from_slice(&rows.to_le_bytes());
        msg.extend_from_slice(&cols.to_le_bytes());
    }
    msg
}

pub fn msg_focus(pty_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_FOCUS);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg
}

pub fn msg_close(pty_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_CLOSE);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg
}

pub fn msg_kill(pty_id: u16, signal: i32) -> Vec<u8> {
    let mut msg = Vec::with_capacity(7);
    msg.push(C2S_KILL);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(&signal.to_le_bytes());
    msg
}

pub fn msg_restart(pty_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_RESTART);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg
}

pub fn msg_subscribe(pty_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_SUBSCRIBE);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg
}

pub fn msg_unsubscribe(pty_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_UNSUBSCRIBE);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg
}

pub fn msg_search(request_id: u16, query: &str) -> Vec<u8> {
    let query = query.as_bytes();
    let mut msg = Vec::with_capacity(3 + query.len());
    msg.push(C2S_SEARCH);
    msg.extend_from_slice(&request_id.to_le_bytes());
    msg.extend_from_slice(query);
    msg
}

pub fn msg_ack() -> Vec<u8> {
    vec![C2S_ACK]
}

pub fn msg_scroll(pty_id: u16, offset: u32) -> Vec<u8> {
    let mut msg = Vec::with_capacity(7);
    msg.push(C2S_SCROLL);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(&offset.to_le_bytes());
    msg
}

pub fn msg_display_rate(fps: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_DISPLAY_RATE);
    msg.extend_from_slice(&fps.to_le_bytes());
    msg
}

pub fn msg_client_metrics(backlog: u16, ack_ahead: u16, apply_ms_x10: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(7);
    msg.push(C2S_CLIENT_METRICS);
    msg.extend_from_slice(&backlog.to_le_bytes());
    msg.extend_from_slice(&ack_ahead.to_le_bytes());
    msg.extend_from_slice(&apply_ms_x10.to_le_bytes());
    msg
}

pub fn msg_read(nonce: u16, pty_id: u16, offset: u32, limit: u32, flags: u8) -> Vec<u8> {
    let mut msg = Vec::with_capacity(14);
    msg.push(C2S_READ);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(&offset.to_le_bytes());
    msg.extend_from_slice(&limit.to_le_bytes());
    msg.push(flags);
    msg
}

pub fn msg_copy_range(
    nonce: u16,
    pty_id: u16,
    start_tail: u32,
    start_col: u16,
    end_tail: u32,
    end_col: u16,
    flags: u8,
) -> Vec<u8> {
    let mut msg = Vec::with_capacity(18);
    msg.push(C2S_COPY_RANGE);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(&start_tail.to_le_bytes());
    msg.extend_from_slice(&start_col.to_le_bytes());
    msg.extend_from_slice(&end_tail.to_le_bytes());
    msg.extend_from_slice(&end_col.to_le_bytes());
    msg.push(flags);
    msg
}

pub fn msg_exited(pty_id: u16, exit_status: i32) -> Vec<u8> {
    let mut msg = Vec::with_capacity(7);
    msg.push(S2C_EXITED);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(&exit_status.to_le_bytes());
    msg
}

/// Build a C2S_QUIT message (client requests server shutdown).
pub fn msg_quit() -> Vec<u8> {
    vec![C2S_QUIT]
}

/// Build an S2C_QUIT message (server notifies clients of shutdown).
pub fn msg_s2c_quit() -> Vec<u8> {
    vec![S2C_QUIT]
}

pub fn msg_surface_created(
    surface_id: u16,
    parent_id: u16,
    width: u16,
    height: u16,
    title: &str,
    app_id: &str,
) -> Vec<u8> {
    let title_bytes = title.as_bytes();
    let app_id_bytes = app_id.as_bytes();
    let mut msg = Vec::with_capacity(13 + title_bytes.len() + app_id_bytes.len());
    msg.push(S2C_SURFACE_CREATED);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(&parent_id.to_le_bytes());
    msg.extend_from_slice(&width.to_le_bytes());
    msg.extend_from_slice(&height.to_le_bytes());
    msg.extend_from_slice(&(title_bytes.len() as u16).to_le_bytes());
    msg.extend_from_slice(title_bytes);
    msg.extend_from_slice(&(app_id_bytes.len() as u16).to_le_bytes());
    msg.extend_from_slice(app_id_bytes);
    msg
}

pub fn msg_surface_destroyed(surface_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(S2C_SURFACE_DESTROYED);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg
}

pub fn msg_surface_frame(
    surface_id: u16,
    timestamp: u32,
    flags: u8,
    width: u16,
    height: u16,
    data: &[u8],
) -> Vec<u8> {
    let mut msg = Vec::with_capacity(12 + data.len());
    msg.push(S2C_SURFACE_FRAME);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(&timestamp.to_le_bytes());
    msg.push(flags);
    msg.extend_from_slice(&width.to_le_bytes());
    msg.extend_from_slice(&height.to_le_bytes());
    msg.extend_from_slice(data);
    msg
}

pub fn msg_surface_title(surface_id: u16, title: &str) -> Vec<u8> {
    let title_bytes = title.as_bytes();
    let mut msg = Vec::with_capacity(3 + title_bytes.len());
    msg.push(S2C_SURFACE_TITLE);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(title_bytes);
    msg
}

pub fn msg_surface_app_id(surface_id: u16, app_id: &str) -> Vec<u8> {
    let app_id_bytes = app_id.as_bytes();
    let mut msg = Vec::with_capacity(3 + app_id_bytes.len());
    msg.push(S2C_SURFACE_APP_ID);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(app_id_bytes);
    msg
}

/// Build S2C_SURFACE_ENCODER: `[0x2A][surface_id:2][name\0codec_string]`.
/// The codec_string is the WebCodecs codec string (e.g. "av01.2.05M.08")
/// appended after a NUL separator.  Old clients that don't split on NUL
/// will just display the full string as the encoder name, which is fine.
pub fn msg_surface_encoder(surface_id: u16, encoder_name: &str, codec_string: &str) -> Vec<u8> {
    let name_bytes = encoder_name.as_bytes();
    let codec_bytes = codec_string.as_bytes();
    let mut msg = Vec::with_capacity(3 + name_bytes.len() + 1 + codec_bytes.len());
    msg.push(S2C_SURFACE_ENCODER);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(name_bytes);
    msg.push(0); // NUL separator
    msg.extend_from_slice(codec_bytes);
    msg
}

pub fn msg_surface_resized(surface_id: u16, width: u16, height: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(7);
    msg.push(S2C_SURFACE_RESIZED);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(&width.to_le_bytes());
    msg.extend_from_slice(&height.to_le_bytes());
    msg
}

pub fn msg_s2c_clipboard_content(mime_type: &str, data: &[u8]) -> Vec<u8> {
    let mime_bytes = mime_type.as_bytes();
    let mut msg = Vec::with_capacity(7 + mime_bytes.len() + data.len());
    msg.push(S2C_CLIPBOARD_CONTENT);
    msg.extend_from_slice(&(mime_bytes.len() as u16).to_le_bytes());
    msg.extend_from_slice(mime_bytes);
    msg.extend_from_slice(&(data.len() as u32).to_le_bytes());
    msg.extend_from_slice(data);
    msg
}

pub fn msg_surface_input(surface_id: u16, data: &[u8]) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3 + data.len());
    msg.push(C2S_SURFACE_INPUT);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(data);
    msg
}

pub fn msg_surface_pointer(surface_id: u16, event_type: u8, button: u8, x: u16, y: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(8);
    msg.push(C2S_SURFACE_POINTER);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.push(event_type);
    msg.push(button);
    msg.extend_from_slice(&x.to_le_bytes());
    msg.extend_from_slice(&y.to_le_bytes());
    msg
}

pub fn msg_surface_pointer_axis(surface_id: u16, axis: u8, value_x100: i32) -> Vec<u8> {
    let mut msg = Vec::with_capacity(8);
    msg.push(C2S_SURFACE_POINTER_AXIS);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.push(axis);
    msg.extend_from_slice(&value_x100.to_le_bytes());
    msg
}

/// `scale_120` is the device-pixel-ratio in 1/120th units, matching
/// Wayland's `fractional_scale_v1` convention: 120 = 1×, 180 = 1.5×,
/// 240 = 2×.  A value of 0 means "unspecified" (server defaults to 1×).
pub fn msg_surface_resize(surface_id: u16, width: u16, height: u16, scale_120: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(9);
    msg.push(C2S_SURFACE_RESIZE);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.extend_from_slice(&width.to_le_bytes());
    msg.extend_from_slice(&height.to_le_bytes());
    msg.extend_from_slice(&scale_120.to_le_bytes());
    msg
}

pub fn msg_surface_focus(surface_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_SURFACE_FOCUS);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg
}

pub fn msg_surface_subscribe(surface_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_SURFACE_SUBSCRIBE);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg
}

/// Extended surface subscribe with per-surface codec and quality overrides.
///
/// `codec_support`: CODEC_SUPPORT_* bitmask (0 = use connection default).
/// `quality`: SURFACE_QUALITY_* constant (0 = use server default).
pub fn msg_surface_subscribe_ext(surface_id: u16, codec_support: u8, quality: u8) -> Vec<u8> {
    let mut msg = Vec::with_capacity(5);
    msg.push(C2S_SURFACE_SUBSCRIBE);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.push(codec_support);
    msg.push(quality);
    msg
}

/// Scaled surface subscribe: ask the server to encode this surface at
/// exactly `width × height` for this client, bypassing surface-size
/// mediation.  Intended for side-panel thumbnails and any viewer that
/// wants a fixed-size stream independent of the compositor's native
/// surface size and of other clients' view sizes.
///
/// `width` / `height` in pixels.  Passing `0, 0` is equivalent to
/// `msg_surface_subscribe_ext` (mediated subscription).
pub fn msg_surface_subscribe_scaled(
    surface_id: u16,
    codec_support: u8,
    quality: u8,
    width: u16,
    height: u16,
) -> Vec<u8> {
    let mut msg = Vec::with_capacity(9);
    msg.push(C2S_SURFACE_SUBSCRIBE);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg.push(codec_support);
    msg.push(quality);
    msg.extend_from_slice(&width.to_le_bytes());
    msg.extend_from_slice(&height.to_le_bytes());
    msg
}

pub fn msg_surface_unsubscribe(surface_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_SURFACE_UNSUBSCRIBE);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg
}

pub fn msg_surface_close(surface_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_SURFACE_CLOSE);
    msg.extend_from_slice(&surface_id.to_le_bytes());
    msg
}

/// Build a C2S_CLIPBOARD_LIST message (request available MIME types).
pub fn msg_c2s_clipboard_list() -> Vec<u8> {
    vec![C2S_CLIPBOARD_LIST]
}

/// Build a C2S_CLIPBOARD_GET message (request clipboard content for a specific MIME type).
pub fn msg_c2s_clipboard_get(mime_type: &str) -> Vec<u8> {
    let mime_bytes = mime_type.as_bytes();
    let mut msg = Vec::with_capacity(3 + mime_bytes.len());
    msg.push(C2S_CLIPBOARD_GET);
    msg.extend_from_slice(&(mime_bytes.len() as u16).to_le_bytes());
    msg.extend_from_slice(mime_bytes);
    msg
}

/// Build an S2C_CLIPBOARD_LIST message (response with available MIME types).
pub fn msg_s2c_clipboard_list(mime_types: &[String]) -> Vec<u8> {
    let count = mime_types.len().min(u16::MAX as usize);
    let mut msg = Vec::with_capacity(3 + count * 20);
    msg.push(S2C_CLIPBOARD_LIST);
    msg.extend_from_slice(&(count as u16).to_le_bytes());
    for mime in mime_types.iter().take(count) {
        let bytes = mime.as_bytes();
        msg.extend_from_slice(&(bytes.len() as u16).to_le_bytes());
        msg.extend_from_slice(bytes);
    }
    msg
}

pub fn msg_c2s_clipboard_set(mime_type: &str, data: &[u8]) -> Vec<u8> {
    let mime_bytes = mime_type.as_bytes();
    let mut msg = Vec::with_capacity(7 + mime_bytes.len() + data.len());
    msg.push(C2S_CLIPBOARD_SET);
    msg.extend_from_slice(&(mime_bytes.len() as u16).to_le_bytes());
    msg.extend_from_slice(mime_bytes);
    msg.extend_from_slice(&(data.len() as u32).to_le_bytes());
    msg.extend_from_slice(data);
    msg
}

fn push_sgr(out: &mut String, style: &CellStyle) {
    use std::fmt::Write;
    out.push_str("\x1b[0");
    if style.bold {
        out.push_str(";1");
    }
    if style.dim {
        out.push_str(";2");
    }
    if style.italic {
        out.push_str(";3");
    }
    if style.underline {
        out.push_str(";4");
    }
    if style.inverse {
        out.push_str(";7");
    }
    match style.fg {
        Color::Indexed(n) => {
            let _ = write!(out, ";38;5;{n}");
        }
        Color::Rgb(r, g, b) => {
            let _ = write!(out, ";38;2;{r};{g};{b}");
        }
        Color::Default => {}
    }
    match style.bg {
        Color::Indexed(n) => {
            let _ = write!(out, ";48;5;{n}");
        }
        Color::Rgb(r, g, b) => {
            let _ = write!(out, ";48;2;{r};{g};{b}");
        }
        Color::Default => {}
    }
    out.push('m');
}

const MODE_ALT_SCREEN: u16 = 1 << 11;

fn mode_is_cooked(mode: u16) -> bool {
    mode & MODE_ECHO != 0 && mode & MODE_ICANON != 0 && mode & MODE_ALT_SCREEN == 0
}

pub fn build_update_msg(
    pty_id: u16,
    current: &FrameState,
    previous: &FrameState,
) -> Option<Vec<u8>> {
    let title_changed = current.title != previous.title;
    let same_size = previous.rows == current.rows
        && previous.cols == current.cols
        && previous.cells.len() == current.cells.len();

    // Try scroll-aware ops when dimensions match and content differs.
    let mut ops = Vec::new();
    let mut op_count = 0u16;

    // Scroll-aware ops apply when content is "cooked" (shell output) or when
    // either frame has mode 0 (scrollback frames use mode=0, and their content
    // is always static text that benefits from COPY_RECT).
    let scroll_eligible = (mode_is_cooked(current.mode) && mode_is_cooked(previous.mode))
        || current.mode == 0
        || previous.mode == 0;
    if ENABLE_SCROLL_OPS
        && same_size
        && previous.cells != current.cells
        && scroll_eligible
        && let Some(delta_rows) = detect_vertical_scroll(current, previous)
    {
        let mut basis = previous.clone();
        encode_copy_rect_op(&mut ops, current, delta_rows);
        apply_vertical_scroll_copy(&mut basis, delta_rows);
        op_count += 1;
        append_full_width_fill_ops(current, &mut basis, &mut ops, &mut op_count);
        if let Some(patch_op) = build_patch_op(current, &basis) {
            ops.extend_from_slice(&patch_op);
            op_count += 1;
        }
    }

    // Fallback: bare PATCH_CELLS against previous (or a blank frame on resize).
    if op_count == 0 {
        let basis = if same_size {
            previous
        } else {
            &FrameState::new(current.rows, current.cols)
        };
        if let Some(patch_op) = build_patch_op(current, basis) {
            ops = patch_op;
            op_count = 1;
        }
    }

    if op_count == 0 {
        // No cell changes — still emit a frame if cursor/mode/title changed.
        if !title_changed
            && current.cursor_row == previous.cursor_row
            && current.cursor_col == previous.cursor_col
            && current.mode == previous.mode
        {
            return None;
        }
    }

    // Collect overflow strings that need to be transmitted.
    // We send all overflow entries from the current frame that correspond
    // to cells that changed (are in the dirty set).  For a resize (not
    // same_size), all cells are "dirty", so we send all overflow entries.
    let has_overflow = !current.overflow.is_empty();
    let overflow_section = if has_overflow {
        serialize_overflow_strings(current)
    } else {
        Vec::new()
    };

    let line_flags_changed =
        current.line_flags != previous.line_flags || current.rows != previous.rows;
    let has_line_flags = line_flags_changed && !current.line_flags.iter().all(|&f| f == 0);

    let title_bytes = if title_changed {
        current.title.as_bytes()
    } else {
        &[]
    };
    let title_len = title_bytes.len().min(TITLE_LEN_MASK as usize);
    let title_field = OPS_PRESENT
        | if has_overflow { STRINGS_PRESENT } else { 0 }
        | if has_line_flags {
            LINE_FLAGS_PRESENT
        } else {
            0
        }
        | if title_changed {
            TITLE_PRESENT | title_len as u16
        } else {
            0
        };

    let mut payload = Vec::with_capacity(
        12 + title_len
            + 2
            + ops.len()
            + overflow_section.len()
            + if has_line_flags {
                current.rows as usize
            } else {
                0
            }
            + 4,
    );
    payload.extend_from_slice(&current.rows.to_le_bytes());
    payload.extend_from_slice(&current.cols.to_le_bytes());
    payload.extend_from_slice(&current.cursor_row.to_le_bytes());
    payload.extend_from_slice(&current.cursor_col.to_le_bytes());
    payload.extend_from_slice(&current.mode.to_le_bytes());
    payload.extend_from_slice(&title_field.to_le_bytes());
    if title_changed {
        payload.extend_from_slice(&title_bytes[..title_len]);
    }
    payload.extend_from_slice(&op_count.to_le_bytes());
    payload.extend_from_slice(&ops);
    payload.extend_from_slice(&overflow_section);
    if has_line_flags {
        payload.extend_from_slice(&current.line_flags);
    }
    // Trailing scrollback count — old clients ignore extra bytes.
    payload.extend_from_slice(&current.scrollback_lines.to_le_bytes());

    let compressed = compress_prepend_size(&payload);
    let mut msg = Vec::with_capacity(3 + compressed.len());
    msg.push(S2C_UPDATE);
    msg.extend_from_slice(&pty_id.to_le_bytes());
    msg.extend_from_slice(&compressed);
    Some(msg)
}

/// Serialize overflow strings: [u16 count] [for each: u32 cell_index, u16 len, utf8 bytes]
fn serialize_overflow_strings(frame: &FrameState) -> Vec<u8> {
    let count = frame.overflow.len().min(u16::MAX as usize);
    let mut out = Vec::with_capacity(2 + count * 8);
    out.extend_from_slice(&(count as u16).to_le_bytes());
    for (&cell_idx, s) in frame.overflow.iter().take(count) {
        let bytes = s.as_bytes();
        let len = bytes.len().min(u16::MAX as usize);
        out.extend_from_slice(&(cell_idx as u32).to_le_bytes());
        out.extend_from_slice(&(len as u16).to_le_bytes());
        out.extend_from_slice(&bytes[..len]);
    }
    out
}

fn build_patch_op(current: &FrameState, previous: &FrameState) -> Option<Vec<u8>> {
    let total_cells = current.rows as usize * current.cols as usize;
    let total_bytes = total_cells * CELL_SIZE;
    // Fast path: a single bulk memcmp short-circuits the common idle case
    // where nothing has changed, avoiding both the per-cell loop and the
    // bitmask allocation.
    if current.cells.len() >= total_bytes
        && previous.cells.len() >= total_bytes
        && current.cells[..total_bytes] == previous.cells[..total_bytes]
    {
        return None;
    }
    let bitmask_len = total_cells.div_ceil(8);
    let mut bitmask = vec![0u8; bitmask_len];
    let mut dirty_count = 0usize;
    for i in 0..total_cells {
        let off = i * CELL_SIZE;
        if current.cells[off..off + CELL_SIZE] != previous.cells[off..off + CELL_SIZE] {
            bitmask[i / 8] |= 1 << (i % 8);
            dirty_count += 1;
        }
    }
    if dirty_count == 0 {
        return None;
    }

    let mut op = Vec::with_capacity(1 + bitmask_len + dirty_count * CELL_SIZE);
    op.push(OP_PATCH_CELLS);
    op.extend_from_slice(&bitmask);
    for byte_pos in 0..CELL_SIZE {
        for i in 0..total_cells {
            if bitmask[i / 8] & (1 << (i % 8)) != 0 {
                op.push(current.cells[i * CELL_SIZE + byte_pos]);
            }
        }
    }
    Some(op)
}

fn detect_vertical_scroll(current: &FrameState, previous: &FrameState) -> Option<i16> {
    let rows = current.rows as usize;
    let cols = current.cols as usize;
    if rows < 4 || cols == 0 {
        return None;
    }
    let row_bytes = cols * CELL_SIZE;
    let max_delta = rows.saturating_sub(1).min(8);
    let mut best: Option<(usize, i16)> = None;

    for delta in 1..=max_delta {
        let overlap = rows - delta;
        if overlap < 3 {
            continue;
        }
        for signed_delta in [-(delta as i16), delta as i16] {
            let mut matched = 0usize;
            for row in 0..rows {
                let src_row = row as i32 - signed_delta as i32;
                if src_row < 0 || src_row >= rows as i32 {
                    continue;
                }
                let cur_off = row * row_bytes;
                let prev_off = src_row as usize * row_bytes;
                if current.cells[cur_off..cur_off + row_bytes]
                    == previous.cells[prev_off..prev_off + row_bytes]
                {
                    matched += 1;
                }
            }
            if matched * 5 < overlap * 4 {
                continue;
            }
            let replace = match best {
                None => true,
                Some((best_matched, best_delta)) => {
                    matched > best_matched
                        || (matched == best_matched
                            && signed_delta.unsigned_abs() < best_delta.unsigned_abs())
                }
            };
            if replace {
                best = Some((matched, signed_delta));
            }
        }
    }

    best.map(|(_, delta)| delta)
}

fn encode_copy_rect_op(out: &mut Vec<u8>, current: &FrameState, delta_rows: i16) {
    let rows = current.rows;
    let cols = current.cols;
    let delta = delta_rows.unsigned_abs();
    let (src_row, dst_row, copy_rows) = if delta_rows > 0 {
        (0, delta, rows.saturating_sub(delta))
    } else {
        (delta, 0, rows.saturating_sub(delta))
    };
    out.push(OP_COPY_RECT);
    out.extend_from_slice(&src_row.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&dst_row.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&copy_rows.to_le_bytes());
    out.extend_from_slice(&cols.to_le_bytes());
}

fn apply_vertical_scroll_copy(frame: &mut FrameState, delta_rows: i16) {
    let delta = delta_rows.unsigned_abs();
    if delta == 0 || delta >= frame.rows {
        return;
    }
    let (src_row, dst_row, rows) = if delta_rows > 0 {
        (0, delta, frame.rows - delta)
    } else {
        (delta, 0, frame.rows - delta)
    };
    apply_copy_rect_frame(frame, src_row, 0, dst_row, 0, rows, frame.cols);
}

fn apply_copy_rect_frame(
    frame: &mut FrameState,
    src_row: u16,
    src_col: u16,
    dst_row: u16,
    dst_col: u16,
    rows: u16,
    cols: u16,
) {
    let rows = rows
        .min(frame.rows.saturating_sub(src_row))
        .min(frame.rows.saturating_sub(dst_row));
    let cols = cols
        .min(frame.cols.saturating_sub(src_col))
        .min(frame.cols.saturating_sub(dst_col));
    if rows == 0 || cols == 0 {
        return;
    }
    let mut temp = vec![0u8; rows as usize * cols as usize * CELL_SIZE];
    for r in 0..rows as usize {
        let src_off = frame.cell_offset(src_row + r as u16, src_col);
        let src_end = src_off + cols as usize * CELL_SIZE;
        let dst_off = r * cols as usize * CELL_SIZE;
        temp[dst_off..dst_off + cols as usize * CELL_SIZE]
            .copy_from_slice(&frame.cells[src_off..src_end]);
    }
    for r in 0..rows as usize {
        let dst_off = frame.cell_offset(dst_row + r as u16, dst_col);
        let dst_end = dst_off + cols as usize * CELL_SIZE;
        let src_off = r * cols as usize * CELL_SIZE;
        frame.cells[dst_off..dst_end]
            .copy_from_slice(&temp[src_off..src_off + cols as usize * CELL_SIZE]);
    }
}

fn append_full_width_fill_ops(
    current: &FrameState,
    basis: &mut FrameState,
    out: &mut Vec<u8>,
    op_count: &mut u16,
) {
    let rows = current.rows as usize;
    let cols = current.cols as usize;
    if rows == 0 || cols == 0 {
        return;
    }

    let row_bytes = cols * CELL_SIZE;
    let mut row = 0usize;
    while row < rows {
        let row_off = row * row_bytes;
        if current.cells[row_off..row_off + row_bytes] == basis.cells[row_off..row_off + row_bytes]
        {
            row += 1;
            continue;
        }
        let Some(cell) = uniform_row_cell(current, row) else {
            row += 1;
            continue;
        };
        let mut end = row + 1;
        while end < rows {
            if uniform_row_cell(current, end).as_ref() != Some(&cell) {
                break;
            }
            end += 1;
        }

        if *op_count == u16::MAX {
            break;
        }
        out.push(OP_FILL_RECT);
        out.extend_from_slice(&(row as u16).to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&((end - row) as u16).to_le_bytes());
        out.extend_from_slice(&current.cols.to_le_bytes());
        out.extend_from_slice(&cell);
        *op_count = op_count.saturating_add(1);

        for r in row..end {
            let row_off = basis.cell_offset(r as u16, 0);
            for c in 0..cols {
                let off = row_off + c * CELL_SIZE;
                basis.cells[off..off + CELL_SIZE].copy_from_slice(&cell);
            }
        }

        row = end;
    }
}

fn uniform_row_cell(frame: &FrameState, row: usize) -> Option<[u8; CELL_SIZE]> {
    let cols = frame.cols as usize;
    if row >= frame.rows as usize || cols == 0 {
        return None;
    }
    let start = row * cols * CELL_SIZE;
    let mut first = [0u8; CELL_SIZE];
    first.copy_from_slice(&frame.cells[start..start + CELL_SIZE]);
    if first[1] & 0b110 != 0 {
        return None;
    }
    for col in 1..cols {
        let off = start + col * CELL_SIZE;
        if frame.cells[off..off + CELL_SIZE] != first {
            return None;
        }
    }
    Some(first)
}

fn encode_cell(dst: &mut [u8], ch: Option<char>, style: CellStyle, wide: bool, wide_cont: bool) {
    dst.fill(0);

    let mut f0 = 0u8;
    encode_color(style.fg, &mut f0, &mut dst[2..5], false);
    encode_color(style.bg, &mut f0, &mut dst[5..8], true);
    if style.bold {
        f0 |= 1 << 4;
    }
    if style.dim {
        f0 |= 1 << 5;
    }
    if style.italic {
        f0 |= 1 << 6;
    }
    if style.underline {
        f0 |= 1 << 7;
    }
    dst[0] = f0;

    let mut f1 = 0u8;
    if style.inverse {
        f1 |= 1;
    }
    if wide {
        f1 |= 1 << 1;
    }
    if wide_cont {
        f1 |= 1 << 2;
    }
    if let Some(ch) = ch {
        let mut buf = [0u8; 4];
        let encoded = ch.encode_utf8(&mut buf).as_bytes();
        let len = encoded.len().min(4);
        dst[8..8 + len].copy_from_slice(&encoded[..len]);
        f1 |= (len as u8) << 3;
    }
    dst[1] = f1;
}

fn encode_color(color: Color, flags: &mut u8, dst: &mut [u8], is_bg: bool) {
    let shift = if is_bg { 2 } else { 0 };
    match color {
        Color::Default => {}
        Color::Indexed(idx) => {
            *flags |= 1 << shift;
            dst[0] = idx;
        }
        Color::Rgb(r, g, b) => {
            *flags |= 2 << shift;
            dst[0] = r;
            dst[1] = g;
            dst[2] = b;
        }
    }
}

fn wrap_text_lines(text: &str, width: usize) -> Vec<String> {
    if width == 0 {
        return Vec::new();
    }
    let mut out = Vec::new();
    for paragraph in text.split('\n') {
        if paragraph.is_empty() {
            out.push(String::new());
            continue;
        }
        let mut line = String::new();
        let mut line_width = 0usize;
        for word in paragraph.split_whitespace() {
            push_wrapped_word(word, width, &mut out, &mut line, &mut line_width);
        }
        if !line.is_empty() {
            out.push(line);
        }
    }
    if out.is_empty() {
        out.push(String::new());
    }
    out
}

fn push_wrapped_word(
    word: &str,
    width: usize,
    out: &mut Vec<String>,
    line: &mut String,
    line_width: &mut usize,
) {
    let word_width = UnicodeWidthStr::width(word);
    if line.is_empty() {
        if word_width <= width {
            line.push_str(word);
            *line_width = word_width;
            return;
        }
    } else if *line_width + 1 + word_width <= width {
        line.push(' ');
        line.push_str(word);
        *line_width += 1 + word_width;
        return;
    } else {
        out.push(std::mem::take(line));
        *line_width = 0;
        if word_width <= width {
            line.push_str(word);
            *line_width = word_width;
            return;
        }
    }

    for ch in word.chars() {
        let ch_width = UnicodeWidthChar::width(ch).unwrap_or(1).max(1);
        if *line_width + ch_width > width && !line.is_empty() {
            out.push(std::mem::take(line));
            *line_width = 0;
        }
        line.push(ch);
        *line_width += ch_width;
    }
}

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

    #[test]
    fn update_round_trip_preserves_title_and_cells() {
        let style = CellStyle::default();
        let mut prev = FrameState::new(2, 8);
        prev.set_title("one");
        prev.write_text(0, 0, "hello", style);

        let mut next = prev.clone();
        next.set_title("two");
        next.write_text(1, 0, "world", style);

        let baseline = build_update_msg(7, &prev, &FrameState::default()).unwrap();
        let delta = build_update_msg(7, &next, &prev).unwrap();

        let mut term = TerminalState::new(2, 8);
        let ServerMsg::Update { payload, .. } = parse_server_msg(&baseline).unwrap() else {
            panic!("expected update");
        };
        assert!(term.feed_compressed(payload));
        assert_eq!(term.title(), "one");

        let ServerMsg::Update { payload, .. } = parse_server_msg(&delta).unwrap() else {
            panic!("expected update");
        };
        assert!(term.feed_compressed(payload));
        assert_eq!(term.title(), "two");
        assert_eq!(term.get_all_text(), "hello\nworld");
    }

    #[test]
    fn title_can_be_cleared_via_update() {
        let style = CellStyle::default();
        let mut prev = FrameState::new(1, 4);
        prev.set_title("busy");
        prev.write_text(0, 0, "ping", style);

        let mut next = prev.clone();
        next.set_title("");

        let baseline = build_update_msg(1, &prev, &FrameState::default()).unwrap();
        let delta = build_update_msg(1, &next, &prev).unwrap();

        let mut term = TerminalState::new(1, 4);
        let ServerMsg::Update { payload, .. } = parse_server_msg(&baseline).unwrap() else {
            panic!("expected update");
        };
        term.feed_compressed(payload);
        let ServerMsg::Update { payload, .. } = parse_server_msg(&delta).unwrap() else {
            panic!("expected update");
        };
        term.feed_compressed(payload);
        assert_eq!(term.title(), "");
    }

    #[test]
    fn scroll_heavy_update_can_use_ops_payload() {
        let style = CellStyle::default();
        let mut prev = FrameState::new(5, 6);
        prev.write_text(0, 0, "one", style);
        prev.write_text(1, 0, "two", style);
        prev.write_text(2, 0, "three", style);
        prev.write_text(3, 0, "four", style);
        prev.write_text(4, 0, "five", style);

        let mut next = FrameState::new(5, 6);
        next.write_text(0, 0, "two", style);
        next.write_text(1, 0, "three", style);
        next.write_text(2, 0, "four", style);
        next.write_text(3, 0, "five", style);

        let delta = build_update_msg(9, &next, &prev).unwrap();
        let ServerMsg::Update { payload, .. } = parse_server_msg(&delta).unwrap() else {
            panic!("expected update");
        };
        let decoded = decompress_size_prepended(payload).unwrap();
        let title_field = u16::from_le_bytes([decoded[10], decoded[11]]);
        assert_ne!(title_field & OPS_PRESENT, 0);

        let mut term = TerminalState::new(5, 6);
        let baseline = build_update_msg(9, &prev, &FrameState::default()).unwrap();
        let ServerMsg::Update { payload, .. } = parse_server_msg(&baseline).unwrap() else {
            panic!("expected update");
        };
        assert!(term.feed_compressed(payload));
        let ServerMsg::Update { payload, .. } = parse_server_msg(&delta).unwrap() else {
            panic!("expected update");
        };
        assert!(term.feed_compressed(payload));
        assert_eq!(term.get_all_text(), "two\nthree\nfour\nfive\n");
    }

    #[test]
    fn cooked_scroll_heavy_update_uses_copy_rect_op() {
        let style = CellStyle::default();
        let mut prev = FrameState::new(5, 6);
        prev.set_mode(MODE_ECHO | MODE_ICANON);
        prev.write_text(0, 0, "one", style);
        prev.write_text(1, 0, "two", style);
        prev.write_text(2, 0, "three", style);
        prev.write_text(3, 0, "four", style);
        prev.write_text(4, 0, "five", style);

        let mut next = FrameState::new(5, 6);
        next.set_mode(MODE_ECHO | MODE_ICANON);
        next.write_text(0, 0, "two", style);
        next.write_text(1, 0, "three", style);
        next.write_text(2, 0, "four", style);
        next.write_text(3, 0, "five", style);

        let delta = build_update_msg(9, &next, &prev).unwrap();
        let ServerMsg::Update { payload, .. } = parse_server_msg(&delta).unwrap() else {
            panic!("expected update");
        };
        let decoded = decompress_size_prepended(payload).unwrap();
        let op_count = u16::from_le_bytes([decoded[12], decoded[13]]);
        assert!(op_count >= 1);
        assert_eq!(decoded[14], OP_COPY_RECT);
    }

    #[test]
    fn mode_zero_scroll_uses_copy_rect() {
        let style = CellStyle::default();
        let mut prev = FrameState::new(5, 6);
        prev.write_text(0, 0, "one", style);
        prev.write_text(1, 0, "two", style);
        prev.write_text(2, 0, "three", style);
        prev.write_text(3, 0, "four", style);
        prev.write_text(4, 0, "five", style);

        let mut next = FrameState::new(5, 6);
        next.write_text(0, 0, "two", style);
        next.write_text(1, 0, "three", style);
        next.write_text(2, 0, "four", style);
        next.write_text(3, 0, "five", style);

        let delta = build_update_msg(9, &next, &prev).unwrap();
        let ServerMsg::Update { payload, .. } = parse_server_msg(&delta).unwrap() else {
            panic!("expected update");
        };
        let decoded = decompress_size_prepended(payload).unwrap();
        let op_count = u16::from_le_bytes([decoded[12], decoded[13]]);
        assert!(op_count >= 1);
        // mode=0 frames (scrollback) now use COPY_RECT for efficient scrolling
        assert_eq!(decoded[14], OP_COPY_RECT);

        // Verify round-trip correctness
        let baseline = build_update_msg(9, &prev, &FrameState::new(5, 6)).unwrap();
        let mut state = TerminalState::new(5, 6);
        let ServerMsg::Update { payload: bp, .. } = parse_server_msg(&baseline).unwrap() else {
            panic!("expected update");
        };
        state.feed_compressed(bp);
        state.feed_compressed(payload);
        assert_eq!(state.frame().cells(), next.cells());
    }

    #[test]
    fn callback_renderer_wraps_text() {
        let mut renderer = CallbackRenderer::new(2, 8);
        renderer.render(|dom| {
            dom.wrapped_text(
                Rect::new(0, 0, 2, 8),
                "alpha beta gamma",
                CellStyle::default(),
            );
        });
        assert_eq!(renderer.frame().get_all_text(), "alpha\nbeta");
    }

    #[test]
    fn scrolling_text_shows_tail() {
        let mut frame = FrameState::new(3, 8);
        frame.write_scrolling_text(
            Rect::new(0, 0, 3, 8),
            &["one", "two", "three", "four"],
            0,
            CellStyle::default(),
        );
        assert_eq!(frame.get_all_text(), "two\nthree\nfour");
    }

    #[test]
    fn search_results_round_trip_with_context() {
        let msg = [
            vec![S2C_SEARCH_RESULTS],
            7u16.to_le_bytes().to_vec(),
            1u16.to_le_bytes().to_vec(),
            42u16.to_le_bytes().to_vec(),
            1234u32.to_le_bytes().to_vec(),
            vec![1, 0b111],
            9u32.to_le_bytes().to_vec(),
            5u16.to_le_bytes().to_vec(),
            b"hello".to_vec(),
        ]
        .concat();

        let ServerMsg::SearchResults {
            request_id,
            results,
        } = parse_server_msg(&msg).unwrap()
        else {
            panic!("expected search results");
        };
        assert_eq!(request_id, 7);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].pty_id, 42);
        assert_eq!(results[0].score, 1234);
        assert_eq!(results[0].primary_source, 1);
        assert_eq!(results[0].matched_sources, 0b111);
        assert_eq!(results[0].scroll_offset, Some(9));
        assert_eq!(results[0].context, b"hello");
    }

    // --- Tag tests ---

    #[test]
    fn msg_create_no_tag_has_zero_tag_len() {
        let msg = msg_create(24, 80);
        assert_eq!(msg.len(), 7);
        assert_eq!(msg[0], C2S_CREATE);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 24);
        assert_eq!(u16::from_le_bytes([msg[3], msg[4]]), 80);
        assert_eq!(u16::from_le_bytes([msg[5], msg[6]]), 0);
    }

    #[test]
    fn msg_create_tagged_encodes_tag() {
        let msg = msg_create_tagged(24, 80, "my-pty");
        assert_eq!(msg[0], C2S_CREATE);
        let tag_len = u16::from_le_bytes([msg[5], msg[6]]) as usize;
        assert_eq!(tag_len, 6);
        assert_eq!(&msg[7..7 + tag_len], b"my-pty");
        assert_eq!(msg.len(), 7 + tag_len);
    }

    #[test]
    fn msg_create_tagged_command_encodes_both() {
        let msg = msg_create_tagged_command(30, 120, "editor", "vim");
        let tag_len = u16::from_le_bytes([msg[5], msg[6]]) as usize;
        assert_eq!(tag_len, 6);
        assert_eq!(&msg[7..13], b"editor");
        assert_eq!(&msg[13..], b"vim");
    }

    #[test]
    fn msg_create_command_has_empty_tag() {
        let msg = msg_create_command(24, 80, "ls");
        let tag_len = u16::from_le_bytes([msg[5], msg[6]]) as usize;
        assert_eq!(tag_len, 0);
        assert_eq!(&msg[7..], b"ls");
    }

    #[test]
    fn msg_create_tagged_empty_tag() {
        let msg = msg_create_tagged(24, 80, "");
        assert_eq!(msg.len(), 7);
        assert_eq!(u16::from_le_bytes([msg[5], msg[6]]), 0);
    }

    #[test]
    fn msg_create_tagged_unicode_tag() {
        let msg = msg_create_tagged(24, 80, "日本語");
        let tag_len = u16::from_le_bytes([msg[5], msg[6]]) as usize;
        assert_eq!(tag_len, "日本語".len());
        assert_eq!(std::str::from_utf8(&msg[7..7 + tag_len]).unwrap(), "日本語");
    }

    #[test]
    fn parse_created_with_tag() {
        let mut wire = vec![S2C_CREATED, 0x05, 0x00];
        wire.extend_from_slice(b"hello");
        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::Created { pty_id, tag } => {
                assert_eq!(pty_id, 5);
                assert_eq!(tag, "hello");
            }
            _ => panic!("expected Created"),
        }
    }

    #[test]
    fn parse_created_without_tag() {
        let wire = vec![S2C_CREATED, 0x03, 0x00];
        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::Created { pty_id, tag } => {
                assert_eq!(pty_id, 3);
                assert_eq!(tag, "");
            }
            _ => panic!("expected Created"),
        }
    }

    #[test]
    fn parse_created_n_with_tag() {
        let mut wire = vec![S2C_CREATED_N, 0x2a, 0x00, 0x05, 0x00];
        wire.extend_from_slice(b"hello");
        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::CreatedN { nonce, pty_id, tag } => {
                assert_eq!(nonce, 42);
                assert_eq!(pty_id, 5);
                assert_eq!(tag, "hello");
            }
            _ => panic!("expected CreatedN"),
        }
    }

    #[test]
    fn msg_create_n_format() {
        let msg = msg_create_n(42, 24, 80, "test");
        assert_eq!(msg[0], C2S_CREATE_N);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 42);
        assert_eq!(u16::from_le_bytes([msg[3], msg[4]]), 24);
        assert_eq!(u16::from_le_bytes([msg[5], msg[6]]), 80);
        assert_eq!(u16::from_le_bytes([msg[7], msg[8]]), 4);
        assert_eq!(&msg[9..], b"test");
    }

    #[test]
    fn msg_create_n_command_format() {
        let msg = msg_create_n_command(7, 30, 120, "bg", "make build");
        assert_eq!(msg[0], C2S_CREATE_N);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 7);
        assert_eq!(u16::from_le_bytes([msg[3], msg[4]]), 30);
        assert_eq!(u16::from_le_bytes([msg[5], msg[6]]), 120);
        let tag_len = u16::from_le_bytes([msg[7], msg[8]]) as usize;
        assert_eq!(tag_len, 2);
        assert_eq!(&msg[9..9 + tag_len], b"bg");
        assert_eq!(&msg[9 + tag_len..], b"make build");
    }

    #[test]
    fn parse_list_with_tags() {
        // 2 entries: id=1 tag="ab", id=2 tag=""
        let mut wire = vec![S2C_LIST, 0x02, 0x00];
        // entry 1: id=1, tag_len=2, tag="ab", cmd_len=0
        wire.extend_from_slice(&1u16.to_le_bytes());
        wire.extend_from_slice(&2u16.to_le_bytes());
        wire.extend_from_slice(b"ab");
        wire.extend_from_slice(&0u16.to_le_bytes());
        // entry 2: id=2, tag_len=0, cmd_len=0
        wire.extend_from_slice(&2u16.to_le_bytes());
        wire.extend_from_slice(&0u16.to_le_bytes());
        wire.extend_from_slice(&0u16.to_le_bytes());

        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::List { entries } => {
                assert_eq!(entries.len(), 2);
                assert_eq!(entries[0].pty_id, 1);
                assert_eq!(entries[0].tag, "ab");
                assert_eq!(entries[1].pty_id, 2);
                assert_eq!(entries[1].tag, "");
            }
            _ => panic!("expected List"),
        }
    }

    #[test]
    fn parse_list_empty() {
        let wire = vec![S2C_LIST, 0x00, 0x00];
        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::List { entries } => assert_eq!(entries.len(), 0),
            _ => panic!("expected List"),
        }
    }

    #[test]
    fn parse_list_truncated_gracefully() {
        // count=2 but only 1 complete entry
        let mut wire = vec![S2C_LIST, 0x02, 0x00];
        wire.extend_from_slice(&1u16.to_le_bytes());
        wire.extend_from_slice(&0u16.to_le_bytes());
        // missing second entry
        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::List { entries } => assert_eq!(entries.len(), 1),
            _ => panic!("expected List"),
        }
    }

    #[test]
    fn parse_list_with_long_tags() {
        let long_tag = "a".repeat(300);
        let mut wire = vec![S2C_LIST, 0x01, 0x00];
        wire.extend_from_slice(&42u16.to_le_bytes());
        wire.extend_from_slice(&(long_tag.len() as u16).to_le_bytes());
        wire.extend_from_slice(long_tag.as_bytes());

        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::List { entries } => {
                assert_eq!(entries.len(), 1);
                assert_eq!(entries[0].pty_id, 42);
                assert_eq!(entries[0].tag, long_tag);
            }
            _ => panic!("expected List"),
        }
    }

    #[test]
    fn create_and_created_tag_round_trip() {
        // Simulate: client sends create with tag, server echoes tag in created
        let create_msg = msg_create_tagged(24, 80, "my-session");
        let tag_len = u16::from_le_bytes([create_msg[5], create_msg[6]]) as usize;
        let tag = std::str::from_utf8(&create_msg[7..7 + tag_len]).unwrap();

        // Server builds S2C_CREATED with the tag
        let mut created_wire = vec![S2C_CREATED, 0x07, 0x00]; // pty_id = 7
        created_wire.extend_from_slice(tag.as_bytes());

        let msg = parse_server_msg(&created_wire).unwrap();
        match msg {
            ServerMsg::Created {
                pty_id,
                tag: parsed_tag,
            } => {
                assert_eq!(pty_id, 7);
                assert_eq!(parsed_tag, "my-session");
            }
            _ => panic!("expected Created"),
        }
    }

    // --- FrameState tests ---

    #[test]
    fn frame_state_accessors() {
        let mut f = FrameState::new(4, 10);
        assert_eq!(f.rows(), 4);
        assert_eq!(f.cols(), 10);
        assert_eq!(f.cursor_row(), 0);
        assert_eq!(f.cursor_col(), 0);
        assert_eq!(f.mode(), 0);
        assert_eq!(f.title(), "");
        assert_eq!(f.cells().len(), 4 * 10 * CELL_SIZE);
        assert_eq!(f.cells_mut().len(), 4 * 10 * CELL_SIZE);
        assert!(f.overflow().is_empty());
        assert!(f.overflow_mut().is_empty());
    }

    #[test]
    fn frame_state_from_parts() {
        let cells = vec![0u8; 2 * 4 * CELL_SIZE];
        let f = FrameState::from_parts(2, 4, 1, 3, 0x0F, "hello", cells.clone());
        assert_eq!(f.rows(), 2);
        assert_eq!(f.cols(), 4);
        assert_eq!(f.cursor_row(), 1);
        assert_eq!(f.cursor_col(), 3);
        assert_eq!(f.mode(), 0x0F);
        assert_eq!(f.title(), "hello");
        assert_eq!(f.cells(), &cells[..]);
    }

    #[test]
    fn frame_state_from_parts_wrong_size() {
        // cells with wrong size should be ignored (stays zeroed)
        let cells = vec![0u8; 10]; // wrong size
        let f = FrameState::from_parts(2, 4, 0, 0, 0, "", cells);
        assert_eq!(f.cells().len(), 2 * 4 * CELL_SIZE);
    }

    #[test]
    fn frame_state_resize() {
        let mut f = FrameState::new(4, 10);
        f.set_cursor(3, 9);
        f.resize(2, 5);
        assert_eq!(f.rows(), 2);
        assert_eq!(f.cols(), 5);
        assert_eq!(f.cursor_row(), 1); // clamped
        assert_eq!(f.cursor_col(), 4); // clamped
        assert_eq!(f.cells().len(), 2 * 5 * CELL_SIZE);
    }

    #[test]
    fn frame_state_resize_noop() {
        let mut f = FrameState::new(4, 10);
        let ptr_before = f.cells().as_ptr();
        f.resize(4, 10); // same size
        let ptr_after = f.cells().as_ptr();
        assert_eq!(ptr_before, ptr_after); // no realloc
    }

    #[test]
    fn frame_state_set_cursor_clamps() {
        let mut f = FrameState::new(4, 10);
        f.set_cursor(100, 200);
        assert_eq!(f.cursor_row(), 3);
        assert_eq!(f.cursor_col(), 9);
    }

    #[test]
    fn frame_state_set_title() {
        let mut f = FrameState::new(2, 2);
        assert!(f.set_title("new title"));
        assert_eq!(f.title(), "new title");
        assert!(!f.set_title("new title")); // same title returns false
        assert!(f.set_title("other"));
    }

    #[test]
    fn frame_state_get_text_and_write_text() {
        let mut f = FrameState::new(2, 10);
        f.write_text(0, 0, "Hello", CellStyle::default());
        f.write_text(1, 0, "World", CellStyle::default());
        let text = f.get_text(0, 0, 1, 9);
        assert!(text.contains("Hello"));
        assert!(text.contains("World"));
        let all = f.get_all_text();
        assert!(all.contains("Hello"));
    }

    #[test]
    fn frame_state_get_text_empty() {
        let f = FrameState::new(0, 0);
        assert_eq!(f.get_text(0, 0, 0, 0), "");
        assert_eq!(f.get_all_text(), "");
    }

    #[test]
    fn frame_state_get_cell() {
        let f = FrameState::new(2, 4);
        let cell = f.get_cell(0, 0);
        assert_eq!(cell.len(), CELL_SIZE);
        // Out of bounds
        assert!(f.get_cell(100, 100).is_empty());
    }

    #[test]
    fn frame_state_cell_content_blank() {
        let f = FrameState::new(2, 4);
        assert_eq!(f.cell_content(0, 0), " "); // blank cell
        assert_eq!(f.cell_content(100, 0), ""); // out of bounds
    }

    #[test]
    fn frame_state_cell_content_with_text() {
        let mut f = FrameState::new(2, 10);
        f.write_text(0, 0, "A", CellStyle::default());
        assert_eq!(f.cell_content(0, 0), "A");
    }

    #[test]
    fn frame_state_fill_rect() {
        let mut f = FrameState::new(4, 10);
        f.fill_rect(Rect::new(0, 0, 2, 5), 'X', CellStyle::default());
        assert_eq!(f.cell_content(0, 0), "X");
        assert_eq!(f.cell_content(1, 4), "X");
        assert_eq!(f.cell_content(2, 0), " "); // outside rect
    }

    #[test]
    fn frame_state_wrapped_text() {
        let mut f = FrameState::new(4, 10);
        let lines =
            f.write_wrapped_text(Rect::new(0, 0, 4, 5), "hello world", CellStyle::default());
        assert!(lines >= 2); // "hello world" wraps at width 5
    }

    #[test]
    fn frame_state_wrapped_text_empty_rect() {
        let mut f = FrameState::new(4, 10);
        assert_eq!(
            f.write_wrapped_text(Rect::new(0, 0, 0, 0), "hi", CellStyle::default()),
            0
        );
    }

    #[test]
    fn frame_state_scrolling_text() {
        let mut f = FrameState::new(4, 10);
        f.write_scrolling_text(
            Rect::new(0, 0, 3, 10),
            &["line1", "line2", "line3", "line4"],
            0,
            CellStyle::default(),
        );
        // Last 3 lines visible with offset_from_bottom=0
        assert_eq!(f.cell_content(0, 0), "l"); // "line2"
    }

    #[test]
    fn frame_state_scrolling_text_empty_rect() {
        let mut f = FrameState::new(4, 10);
        f.write_scrolling_text(Rect::new(0, 0, 0, 0), &["hi"], 0, CellStyle::default());
        // Should not panic
    }

    #[test]
    fn frame_state_clear() {
        let mut f = FrameState::new(2, 4);
        f.write_text(0, 0, "AB", CellStyle::default());
        f.clear(CellStyle::default());
        assert_eq!(f.cell_content(0, 0), " ");
    }

    // --- TerminalState tests ---

    #[test]
    fn terminal_state_accessors() {
        let t = TerminalState::new(24, 80);
        assert_eq!(t.rows(), 24);
        assert_eq!(t.cols(), 80);
        assert_eq!(t.cursor_row(), 0);
        assert_eq!(t.cursor_col(), 0);
        assert_eq!(t.mode(), 0);
        assert_eq!(t.title(), "");
        assert_eq!(t.cells().len(), 24 * 80 * CELL_SIZE);
        assert_eq!(t.frame().rows(), 24);
    }

    #[test]
    fn terminal_state_mutators() {
        let mut t = TerminalState::new(4, 10);
        t.frame_mut().set_title("test");
        assert_eq!(t.title(), "test");
    }

    #[test]
    fn terminal_state_set_title() {
        let mut t = TerminalState::new(4, 10);
        assert!(t.frame_mut().set_title("hello"));
        assert_eq!(t.title(), "hello");
        assert!(!t.frame_mut().set_title("hello")); // same
    }

    #[test]
    fn terminal_state_get_text() {
        let t = TerminalState::new(2, 10);
        let text = t.get_text(0, 0, 0, 9);
        assert!(text.is_empty() || text.chars().all(|c| c == ' ' || c == '\n'));
        assert!(t.get_cell(0, 0).len() == CELL_SIZE);
        assert!(t.get_cell(100, 100).is_empty());
    }

    #[test]
    fn terminal_state_resize() {
        let mut t = TerminalState::new(4, 10);
        t.frame_mut().resize(2, 5);
        // Note: TerminalState.dirty isn't updated by frame_mut().resize()
        // directly — that happens through feed_compressed. So just check frame.
        assert_eq!(t.rows(), 2);
        assert_eq!(t.cols(), 5);
    }

    #[test]
    fn terminal_state_feed_compressed_invalid() {
        let mut t = TerminalState::new(4, 10);
        assert!(!t.feed_compressed(b"garbage"));
        assert!(!t.feed_compressed(&[]));
    }

    #[test]
    fn terminal_state_feed_compressed_batch_empty() {
        let mut t = TerminalState::new(4, 10);
        assert!(!t.feed_compressed_batch(&[]));
    }

    #[test]
    fn terminal_state_feed_compressed_batch_truncated() {
        let mut t = TerminalState::new(4, 10);
        // Length header says 100 bytes but only 4 bytes present
        let batch = &[100, 0, 0, 0];
        assert!(!t.feed_compressed_batch(batch));
    }

    // --- Client message builder tests ---

    #[test]
    fn msg_input_format() {
        let msg = msg_input(5, b"hello");
        assert_eq!(msg[0], C2S_INPUT);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 5);
        assert_eq!(&msg[3..], b"hello");
    }

    #[test]
    fn msg_resize_format() {
        let msg = msg_resize(3, 24, 80);
        assert_eq!(msg[0], C2S_RESIZE);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 3);
        assert_eq!(u16::from_le_bytes([msg[3], msg[4]]), 24);
        assert_eq!(u16::from_le_bytes([msg[5], msg[6]]), 80);
    }

    #[test]
    fn msg_resize_batch_format() {
        let msg = msg_resize_batch(&[(3, 24, 80), (5, 40, 120)]);
        assert_eq!(msg[0], C2S_RESIZE);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 3);
        assert_eq!(u16::from_le_bytes([msg[3], msg[4]]), 24);
        assert_eq!(u16::from_le_bytes([msg[5], msg[6]]), 80);
        assert_eq!(u16::from_le_bytes([msg[7], msg[8]]), 5);
        assert_eq!(u16::from_le_bytes([msg[9], msg[10]]), 40);
        assert_eq!(u16::from_le_bytes([msg[11], msg[12]]), 120);
    }

    #[test]
    fn msg_focus_format() {
        let msg = msg_focus(7);
        assert_eq!(msg[0], C2S_FOCUS);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 7);
        assert_eq!(msg.len(), 3);
    }

    #[test]
    fn msg_close_format() {
        let msg = msg_close(9);
        assert_eq!(msg[0], C2S_CLOSE);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 9);
    }

    #[test]
    fn msg_subscribe_unsubscribe_format() {
        let sub = msg_subscribe(1);
        assert_eq!(sub[0], C2S_SUBSCRIBE);
        assert_eq!(u16::from_le_bytes([sub[1], sub[2]]), 1);

        let unsub = msg_unsubscribe(2);
        assert_eq!(unsub[0], C2S_UNSUBSCRIBE);
        assert_eq!(u16::from_le_bytes([unsub[1], unsub[2]]), 2);
    }

    #[test]
    fn msg_search_format() {
        let msg = msg_search(42, "test query");
        assert_eq!(msg[0], C2S_SEARCH);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 42);
        assert_eq!(&msg[3..], b"test query");
    }

    #[test]
    fn msg_ack_format() {
        let msg = msg_ack();
        assert_eq!(msg, vec![C2S_ACK]);
    }

    #[test]
    fn msg_scroll_format() {
        let msg = msg_scroll(5, 1000);
        assert_eq!(msg[0], C2S_SCROLL);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 5);
        assert_eq!(u32::from_le_bytes([msg[3], msg[4], msg[5], msg[6]]), 1000);
    }

    #[test]
    fn msg_display_rate_format() {
        let msg = msg_display_rate(120);
        assert_eq!(msg[0], C2S_DISPLAY_RATE);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 120);
    }

    #[test]
    fn msg_client_metrics_format() {
        let msg = msg_client_metrics(3, 5, 100);
        assert_eq!(msg[0], C2S_CLIENT_METRICS);
        assert_eq!(u16::from_le_bytes([msg[1], msg[2]]), 3);
        assert_eq!(u16::from_le_bytes([msg[3], msg[4]]), 5);
        assert_eq!(u16::from_le_bytes([msg[5], msg[6]]), 100);
    }

    // --- CallbackRenderer tests ---

    #[test]
    fn callback_renderer_resize() {
        let mut r = CallbackRenderer::new(2, 8);
        assert_eq!(r.frame().rows(), 2);
        r.resize(4, 16);
        assert_eq!(r.frame().rows(), 4);
        assert_eq!(r.frame().cols(), 16);
    }

    #[test]
    fn callback_renderer_fill() {
        let mut r = CallbackRenderer::new(4, 10);
        r.render(|dom| {
            dom.fill(Rect::new(0, 0, 2, 5), '#', CellStyle::default());
        });
        assert_eq!(r.frame().cell_content(0, 0), "#");
        assert_eq!(r.frame().cell_content(1, 4), "#");
    }

    #[test]
    fn callback_renderer_text() {
        let mut r = CallbackRenderer::new(4, 20);
        r.render(|dom| {
            dom.text(0, 0, "Hello", CellStyle::default());
        });
        assert_eq!(r.frame().cell_content(0, 0), "H");
        assert_eq!(r.frame().cell_content(0, 4), "o");
    }

    #[test]
    fn callback_renderer_set_title() {
        let mut r = CallbackRenderer::new(2, 8);
        r.render(|dom| {
            dom.set_title("my title");
        });
        assert_eq!(r.frame().title(), "my title");
    }

    #[test]
    fn callback_renderer_set_background() {
        let mut r = CallbackRenderer::new(2, 4);
        let style = CellStyle {
            bg: Color::Rgb(255, 0, 0),
            ..CellStyle::default()
        };
        r.render(|dom| {
            dom.set_background(style);
        });
        // Background fill should have been applied to all cells
        assert_eq!(r.frame().cells().len(), 2 * 4 * CELL_SIZE);
    }

    #[test]
    fn callback_renderer_scrolling_text() {
        let mut r = CallbackRenderer::new(4, 20);
        r.render(|dom| {
            dom.scrolling_text(
                Rect::new(0, 0, 3, 20),
                ["a", "b", "c", "d", "e"].map(String::from),
                0,
                CellStyle::default(),
            );
        });
        // Should show the last 3 lines
        assert_eq!(r.frame().cell_content(0, 0), "c");
    }

    // --- parse_server_msg edge cases ---

    #[test]
    fn parse_empty_returns_none() {
        assert!(parse_server_msg(&[]).is_none());
    }

    #[test]
    fn parse_unknown_type_returns_none() {
        assert!(parse_server_msg(&[0xFF, 0x00, 0x00]).is_none());
    }

    #[test]
    fn parse_update_too_short() {
        assert!(parse_server_msg(&[S2C_UPDATE, 0x00]).is_none());
    }

    #[test]
    fn parse_closed() {
        let msg = parse_server_msg(&[S2C_CLOSED, 0x05, 0x00]).unwrap();
        match msg {
            ServerMsg::Closed { pty_id } => assert_eq!(pty_id, 5),
            _ => panic!("expected Closed"),
        }
    }

    #[test]
    fn parse_title() {
        let mut wire = vec![S2C_TITLE, 0x01, 0x00];
        wire.extend_from_slice(b"mytitle");
        let msg = parse_server_msg(&wire).unwrap();
        match msg {
            ServerMsg::Title { pty_id, title } => {
                assert_eq!(pty_id, 1);
                assert_eq!(title, b"mytitle");
            }
            _ => panic!("expected Title"),
        }
    }

    // --- build_update_msg round-trip ---

    #[test]
    fn build_update_msg_round_trip_with_resize() {
        let style = CellStyle::default();
        let mut prev = FrameState::new(2, 4);
        prev.write_text(0, 0, "AB", style);

        let mut next = FrameState::new(3, 5); // different size
        next.write_text(0, 0, "XY", style);
        next.set_title("resized");

        let msg = build_update_msg(1, &next, &prev).unwrap();
        assert!(!msg.is_empty());

        // Apply to a terminal
        let mut t = TerminalState::new(2, 4);
        assert!(t.feed_compressed(&msg[3..])); // skip pty_id header
        assert_eq!(t.rows(), 3);
        assert_eq!(t.cols(), 5);
        assert_eq!(t.title(), "resized");
    }

    #[test]
    fn build_update_msg_cursor_change() {
        let mut prev = FrameState::new(4, 10);
        prev.set_cursor(0, 0);

        let mut next = prev.clone();
        next.set_cursor(2, 5);

        let msg = build_update_msg(0, &next, &prev).unwrap();

        let mut t = TerminalState::new(4, 10);
        assert!(t.feed_compressed(&msg[3..]));
        assert_eq!(t.cursor_row(), 2);
        assert_eq!(t.cursor_col(), 5);
    }

    #[test]
    fn build_update_msg_mode_change() {
        let prev = FrameState::new(2, 4);
        let mut next = prev.clone();
        next.set_mode(0x0F);

        let msg = build_update_msg(0, &next, &prev).unwrap();
        let mut t = TerminalState::new(2, 4);
        assert!(t.feed_compressed(&msg[3..]));
        assert_eq!(t.mode(), 0x0F);
    }

    #[test]
    fn feed_compressed_batch_multiple_frames() {
        let style = CellStyle::default();
        let prev = FrameState::new(2, 4);

        let mut mid = prev.clone();
        mid.write_text(0, 0, "AB", style);
        let msg1 = build_update_msg(0, &mid, &prev).unwrap();

        let mut next = mid.clone();
        next.write_text(1, 0, "CD", style);
        let msg2 = build_update_msg(0, &next, &mid).unwrap();

        // Build batch: [len1:4][compressed1][len2:4][compressed2]
        let payload1 = &msg1[3..];
        let payload2 = &msg2[3..];
        let mut batch = Vec::new();
        batch.extend_from_slice(&(payload1.len() as u32).to_le_bytes());
        batch.extend_from_slice(payload1);
        batch.extend_from_slice(&(payload2.len() as u32).to_le_bytes());
        batch.extend_from_slice(payload2);

        let mut t = TerminalState::new(2, 4);
        assert!(t.feed_compressed_batch(&batch));
        let text = t.get_all_text();
        assert!(text.contains("AB"));
        assert!(text.contains("CD"));
    }
}